use of org.apache.ignite.lang.IgniteClosure in project ignite by apache.
the class IgniteLockAbstractSelfTest method testLockInterruptiblyMultinode.
/**
* @throws Exception If failed.
*/
private void testLockInterruptiblyMultinode(final boolean fair) throws Exception {
if (gridCount() == 1)
return;
// Initialize reentrant lock.
final IgniteLock lock0 = grid(0).reentrantLock("lock", true, fair, true);
assertEquals(0, lock0.getHoldCount());
assertFalse(lock0.hasQueuedThreads());
lock0.lock();
// Number of threads, one per node.
final int threadCount = gridCount();
final AtomicLong threadCounter = new AtomicLong(0);
IgniteInternalFuture<?> fut = multithreadedAsync(new Callable<Object>() {
@Override
public Object call() throws Exception {
final int localNodeId = (int) threadCounter.getAndIncrement();
final Ignite grid = grid(localNodeId);
IgniteClosure<Ignite, Void> closure = new IgniteClosure<Ignite, Void>() {
@Override
public Void apply(Ignite ignite) {
final IgniteLock l = ignite.reentrantLock("lock", true, true, true);
final AtomicReference<Thread> thread = new AtomicReference<>();
final AtomicBoolean done = new AtomicBoolean(false);
final AtomicBoolean exceptionThrown = new AtomicBoolean(false);
final IgniteCountDownLatch latch = ignite.countDownLatch("latch", threadCount, false, true);
IgniteInternalFuture<?> fut = GridTestUtils.runAsync(new Callable<Void>() {
@Override
public Void call() throws Exception {
try {
thread.set(Thread.currentThread());
l.lockInterruptibly();
} catch (IgniteInterruptedException ignored) {
exceptionThrown.set(true);
} finally {
done.set(true);
}
return null;
}
});
// Wait until l.lock() has been called.
while (!l.hasQueuedThreads()) {
// No-op.
}
latch.countDown();
latch.await();
thread.get().interrupt();
while (!done.get()) {
// No-op.
}
try {
fut.get();
} catch (IgniteCheckedException e) {
fail(e.getMessage());
throw new RuntimeException(e);
}
assertTrue(exceptionThrown.get());
return null;
}
};
closure.apply(grid);
return null;
}
}, threadCount);
fut.get();
lock0.unlock();
info("Checking if interrupted threads are removed from global waiting queue...");
// Check if interrupted threads are removed from global waiting queue.
boolean locked = lock0.tryLock(1000, MILLISECONDS);
info("Interrupted threads successfully removed from global waiting queue. ");
assertTrue(locked);
lock0.unlock();
assertFalse(lock0.isLocked());
lock0.close();
}
use of org.apache.ignite.lang.IgniteClosure in project ignite by apache.
the class IgniteRoundRobinErrorAfterClientReconnectTest method testClientReconnect.
/**
* @throws Exception If failed.
*/
public void testClientReconnect() throws Exception {
final Ignite cli = grid(CLI_IDX);
final GridFutureAdapter<Boolean> fut = new GridFutureAdapter<>();
cli.events().localListen(new IgnitePredicate<Event>() {
@Override
public boolean apply(Event event) {
try {
cli.compute().apply(new IgniteClosure<String, Void>() {
@Override
public Void apply(String arg) {
return null;
}
}, "Hello!");
fut.onDone(true);
return true;
} catch (Exception e) {
fut.onDone(e);
return false;
}
}
}, EventType.EVT_CLIENT_NODE_RECONNECTED);
stopGrid(SRV_IDX);
startGrid(SRV_IDX);
assert fut.get();
}
use of org.apache.ignite.lang.IgniteClosure in project ignite by apache.
the class CacheMetricsForClusterGroupSelfTest method assertMetrics.
/**
* @param cache Cache.
*/
private void assertMetrics(IgniteCache<Integer, Integer> cache) {
CacheMetrics[] ms = new CacheMetrics[GRID_CNT];
for (int i = 0; i < GRID_CNT; i++) {
CacheMetrics metrics = cache.metrics(grid(i).cluster().forCacheNodes(cache.getName()));
for (int j = 0; j < GRID_CNT; j++) ms[j] = grid(j).cache(cache.getName()).localMetrics();
// Static metrics
for (int j = 0; j < GRID_CNT; j++) assertEquals(metrics.name(), ms[j].name());
// Dynamic metrics
assertEquals(metrics.getCacheGets(), sum(ms, new IgniteClosure<CacheMetrics, Long>() {
@Override
public Long apply(CacheMetrics input) {
return input.getCacheGets();
}
}));
assertEquals(metrics.getCachePuts(), sum(ms, new IgniteClosure<CacheMetrics, Long>() {
@Override
public Long apply(CacheMetrics input) {
return input.getCachePuts();
}
}));
assertEquals(metrics.getCacheHits(), sum(ms, new IgniteClosure<CacheMetrics, Long>() {
@Override
public Long apply(CacheMetrics input) {
return input.getCacheHits();
}
}));
}
}
use of org.apache.ignite.lang.IgniteClosure in project ignite by apache.
the class GridScheduleSelfTest method testScheduleRunnable.
/**
* @throws Exception If failed.
*/
public void testScheduleRunnable() throws Exception {
final CountDownLatch latch = new CountDownLatch(1);
SchedulerFuture<?> fut = null;
// 1 minute frequency.
long freq = 60;
// 2 seconds delay.
long delay = 2;
try {
// Execute 2 times after 2 seconds delay every minute.
fut = grid(0).scheduler().scheduleLocal(new Runnable() {
@Override
public void run() {
latch.countDown();
info(">>> EXECUTING SCHEDULED RUNNABLE! <<<");
}
}, "{2, 2} * * * * *");
assert !fut.isDone();
assert !fut.isCancelled();
assert fut.last() == null;
final AtomicInteger notifyCnt = new AtomicInteger();
fut.listen(new CI1<IgniteFuture<?>>() {
@Override
public void apply(IgniteFuture<?> e) {
notifyCnt.incrementAndGet();
}
});
final SchedulerFuture<?> fut0 = fut;
//noinspection ThrowableNotThrown
assertThrows(log, new Callable<Object>() {
@Override
public Object call() throws Exception {
fut0.listenAsync(new IgniteInClosure<IgniteFuture<?>>() {
@Override
public void apply(IgniteFuture<?> fut) {
// No-op
}
}, null);
return null;
}
}, NullPointerException.class, null);
fut.listenAsync(new IgniteInClosure<IgniteFuture<?>>() {
@Override
public void apply(IgniteFuture<?> fut) {
assertEquals(Thread.currentThread().getName(), CUSTOM_THREAD_NAME);
notifyCnt.incrementAndGet();
}
}, exec);
//noinspection ThrowableNotThrown
assertThrows(log, new Callable<Object>() {
@Override
public Object call() throws Exception {
fut0.chainAsync(new IgniteClosure<IgniteFuture<?>, String>() {
@Override
public String apply(IgniteFuture<?> fut) {
return null;
}
}, null);
return null;
}
}, NullPointerException.class, null);
IgniteFuture<String> chained1 = fut.chainAsync(new IgniteClosure<IgniteFuture<?>, String>() {
@Override
public String apply(IgniteFuture<?> fut) {
assertEquals(Thread.currentThread().getName(), CUSTOM_THREAD_NAME);
fut.get();
return "done-custom";
}
}, exec);
long timeTillRun = freq + delay;
info("Going to wait for the first run: " + timeTillRun);
latch.await(timeTillRun, SECONDS);
assertEquals(0, latch.getCount());
assert !fut.isDone();
assert !fut.isCancelled();
assert fut.last() == null;
assertFalse(chained1.isDone());
info("Going to wait for 2nd run: " + timeTillRun);
// Wait until scheduling will be finished.
Thread.sleep(timeTillRun * 1000);
assert fut.isDone();
assert notifyCnt.get() == 2 * 2;
assert !fut.isCancelled();
assert fut.last() == null;
assertEquals("done-custom", chained1.get());
assertTrue(chained1.isDone());
} finally {
assert fut != null;
fut.cancel();
}
}
use of org.apache.ignite.lang.IgniteClosure in project ignite by apache.
the class GridDhtAtomicCache method updateAll0.
/**
* Entry point for all public API put/transform methods.
*
* @param map Put map. Either {@code map}, {@code invokeMap} or {@code conflictPutMap} should be passed.
* @param invokeMap Invoke map. Either {@code map}, {@code invokeMap} or {@code conflictPutMap} should be passed.
* @param invokeArgs Optional arguments for EntryProcessor.
* @param conflictPutMap Conflict put map.
* @param conflictRmvMap Conflict remove map.
* @param retval Return value required flag.
* @param rawRetval Return {@code GridCacheReturn} instance.
* @param async Async operation flag.
* @return Completion future.
*/
@SuppressWarnings("ConstantConditions")
private IgniteInternalFuture updateAll0(@Nullable Map<? extends K, ? extends V> map, @Nullable Map<? extends K, ? extends EntryProcessor> invokeMap, @Nullable Object[] invokeArgs, @Nullable Map<KeyCacheObject, GridCacheDrInfo> conflictPutMap, @Nullable Map<KeyCacheObject, GridCacheVersion> conflictRmvMap, final boolean retval, final boolean rawRetval, final GridCacheOperation op, boolean async) {
assert ctx.updatesAllowed();
if (map != null && keyCheck)
validateCacheKeys(map.keySet());
ctx.checkSecurity(SecurityPermission.CACHE_PUT);
final CacheOperationContext opCtx = ctx.operationContextPerCall();
if (opCtx != null && opCtx.hasDataCenterId()) {
assert conflictPutMap == null : conflictPutMap;
assert conflictRmvMap == null : conflictRmvMap;
if (op == GridCacheOperation.TRANSFORM) {
assert invokeMap != null : invokeMap;
conflictPutMap = F.viewReadOnly((Map) invokeMap, new IgniteClosure<EntryProcessor, GridCacheDrInfo>() {
@Override
public GridCacheDrInfo apply(EntryProcessor o) {
return new GridCacheDrInfo(o, ctx.versions().next(opCtx.dataCenterId()));
}
});
invokeMap = null;
} else if (op == GridCacheOperation.DELETE) {
assert map != null : map;
conflictRmvMap = F.viewReadOnly((Map) map, new IgniteClosure<V, GridCacheVersion>() {
@Override
public GridCacheVersion apply(V o) {
return ctx.versions().next(opCtx.dataCenterId());
}
});
map = null;
} else {
assert map != null : map;
conflictPutMap = F.viewReadOnly((Map) map, new IgniteClosure<V, GridCacheDrInfo>() {
@Override
public GridCacheDrInfo apply(V o) {
return new GridCacheDrInfo(ctx.toCacheObject(o), ctx.versions().next(opCtx.dataCenterId()));
}
});
map = null;
}
}
UUID subjId = ctx.subjectIdPerCall(null, opCtx);
int taskNameHash = ctx.kernalContext().job().currentTaskNameHash();
final GridNearAtomicUpdateFuture updateFut = new GridNearAtomicUpdateFuture(ctx, this, ctx.config().getWriteSynchronizationMode(), op, map != null ? map.keySet() : invokeMap != null ? invokeMap.keySet() : conflictPutMap != null ? conflictPutMap.keySet() : conflictRmvMap.keySet(), map != null ? map.values() : invokeMap != null ? invokeMap.values() : null, invokeArgs, (Collection) (conflictPutMap != null ? conflictPutMap.values() : null), conflictRmvMap != null ? conflictRmvMap.values() : null, retval, rawRetval, opCtx != null ? opCtx.expiry() : null, CU.filterArray(null), subjId, taskNameHash, opCtx != null && opCtx.skipStore(), opCtx != null && opCtx.isKeepBinary(), opCtx != null && opCtx.recovery(), opCtx != null && opCtx.noRetries() ? 1 : MAX_RETRIES);
if (async) {
return asyncOp(new CO<IgniteInternalFuture<Object>>() {
@Override
public IgniteInternalFuture<Object> apply() {
updateFut.map();
return updateFut;
}
});
} else {
updateFut.map();
return updateFut;
}
}
Aggregations