All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.wildfly.clustering.server.infinispan.scheduler.CacheKeysTask Maven / Gradle / Ivy

/*
 * Copyright The WildFly Authors
 * SPDX-License-Identifier: Apache-2.0
 */

package org.wildfly.clustering.server.infinispan.scheduler;

import java.util.Iterator;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.stream.Stream;

import org.infinispan.Cache;
import org.wildfly.clustering.cache.Key;
import org.wildfly.clustering.cache.infinispan.embedded.distribution.CacheStreamFilter;

/**
 * Invokes a task against cache entries matching a filter.
 * @author Paul Ferraro
 * @param  cache key type
 * @param  cache value type
 */
public class CacheKeysTask implements Consumer> {
	private final Cache cache;
	private final Predicate filter;
	private final Consumer task;

	public static , V, M> CacheKeysTask schedule(Cache cache, Predicate filter, Scheduler scheduler) {
		org.wildfly.clustering.cache.function.Consumer schedule = scheduler::schedule;
		return new CacheKeysTask<>(cache, filter, schedule.map(Key::getId));
	}

	public static , V, M> CacheKeysTask cancel(Cache cache, Predicate filter, Scheduler scheduler) {
		org.wildfly.clustering.cache.function.Consumer cancel = scheduler::cancel;
		return new CacheKeysTask<>(cache, filter, cancel.map(Key::getId));
	}

	public CacheKeysTask(Cache cache, Predicate filter, Consumer task) {
		this.cache = cache;
		this.filter = filter;
		this.task = task;
	}

	@Override
	public void accept(CacheStreamFilter filter) {
		// Iterate over filtered keys
		try (Stream stream = filter.apply(this.cache.keySet().stream()).filter(this.filter)) {
			Iterator keys = stream.iterator();
			while (keys.hasNext()) {
				if (Thread.currentThread().isInterrupted()) break;
				this.task.accept(keys.next());
			}
		}
	}
}