use of org.apache.ignite.IgniteLock in project ignite by apache.
the class IgniteLockExample method main.
/**
* Executes example.
*
* @param args Command line arguments, none required.
*/
public static void main(String[] args) {
try (Ignite ignite = Ignition.start("examples/config/example-ignite.xml")) {
System.out.println();
System.out.println(">>> Cache atomic reentrant lock example started.");
// Make name of reentrant lock.
final String reentrantLockName = UUID.randomUUID().toString();
// Initialize lock.
IgniteLock lock = ignite.reentrantLock(reentrantLockName, true, false, true);
// Init distributed cache.
IgniteCache<String, Integer> cache = ignite.getOrCreateCache(CACHE_NAME);
// Init shared variable.
cache.put(QUEUE_ID, 0);
// Shared variable indicating number of jobs left to be completed.
cache.put(SYNC_NAME, NUM_PRODUCERS + NUM_CONSUMERS);
// Start consumers on all cluster nodes.
for (int i = 0; i < NUM_CONSUMERS; i++) ignite.compute().runAsync(new Consumer(reentrantLockName));
// Start producers on all cluster nodes.
for (int i = 0; i < NUM_PRODUCERS; i++) ignite.compute().runAsync(new Producer(reentrantLockName));
System.out.println("Master node is waiting for all other nodes to finish...");
// Wait for everyone to finish.
try {
lock.lock();
IgniteCondition notDone = lock.getOrCreateCondition(SYNC_NAME);
int count = cache.get(SYNC_NAME);
while (count > 0) {
notDone.await();
count = cache.get(SYNC_NAME);
}
} finally {
lock.unlock();
}
}
System.out.flush();
System.out.println();
System.out.println("Finished reentrant lock example...");
System.out.println("Check all nodes for output (this node is also part of the cluster).");
}
use of org.apache.ignite.IgniteLock in project ignite by apache.
the class GridCacheAbstractDataStructuresFailoverSelfTest method doTestReentrantLock.
/**
* @throws Exception If failed.
*/
private void doTestReentrantLock(final ConstantTopologyChangeWorker topWorker, final boolean failoverSafe, final boolean fair) throws Exception {
IgniteEx ig = grid(0);
try (IgniteLock lock = ig.reentrantLock(STRUCTURE_NAME, failoverSafe, fair, true)) {
IgniteInternalFuture<?> fut = topWorker.startChangingTopology(new IgniteClosure<Ignite, Void>() {
@Override
public Void apply(Ignite ignite) {
final IgniteLock l = ignite.reentrantLock(STRUCTURE_NAME, failoverSafe, fair, false);
final AtomicBoolean done = new AtomicBoolean(false);
GridTestUtils.runAsync(new Callable<Void>() {
@Override
public Void call() throws Exception {
try {
l.lock();
} finally {
done.set(true);
}
return null;
}
});
// Wait until l.lock() has been called.
while (!l.hasQueuedThreads() && !done.get()) {
// No-op.
}
return null;
}
});
while (!fut.isDone()) {
try {
lock.lock();
} catch (IgniteException e) {
// Exception may happen in non-failoversafe mode.
if (failoverSafe)
throw e;
} finally {
// Broken lock cannot be used in non-failoversafe mode.
if (!lock.isBroken() || failoverSafe) {
assertTrue(lock.isHeldByCurrentThread());
lock.unlock();
assertFalse(lock.isHeldByCurrentThread());
}
}
}
fut.get();
for (Ignite g : G.allGrids()) {
IgniteLock l = g.reentrantLock(STRUCTURE_NAME, failoverSafe, fair, false);
assertTrue(g.name(), !l.isHeldByCurrentThread() || lock.isBroken());
}
}
}
use of org.apache.ignite.IgniteLock in project ignite by apache.
the class IgniteLockAbstractSelfTest method testLockSerialization.
/**
* @throws Exception If failed.
*/
public void testLockSerialization() throws Exception {
final IgniteLock lock = grid(0).reentrantLock("lock", true, true, true);
info("Lock created: " + lock);
lock.isFailoverSafe();
lock.isFair();
grid(ThreadLocalRandom.current().nextInt(G.allGrids().size())).compute().broadcast(new IgniteCallable<Object>() {
@Nullable
@Override
public Object call() throws Exception {
Thread.sleep(1000);
lock.lock();
try {
info("Inside lock: " + lock.getHoldCount());
} finally {
lock.unlock();
}
return null;
}
});
}
use of org.apache.ignite.IgniteLock in project ignite by apache.
the class IgniteLockAbstractSelfTest method testHasConditionQueuedThreads.
/**
* @throws Exception If failed.
*/
private void testHasConditionQueuedThreads(final boolean fair) throws Exception {
final IgniteLock lock0 = grid(0).reentrantLock("lock", true, fair, true);
assertEquals(0, lock0.getHoldCount());
assertFalse(lock0.hasQueuedThreads());
final int totalThreads = 5;
final Set<Thread> startedThreads = new GridConcurrentHashSet<>();
final Set<Thread> finishedThreads = new GridConcurrentHashSet<>();
IgniteInternalFuture<?> fut = multithreadedAsync(new Callable<Object>() {
@Override
public Object call() throws Exception {
assertFalse(lock0.isHeldByCurrentThread());
IgniteCondition cond = lock0.getOrCreateCondition("cond");
lock0.lock();
startedThreads.add(Thread.currentThread());
// Wait until every thread tries to lock.
do {
cond.await();
Thread.sleep(1000);
} while (startedThreads.size() != totalThreads);
try {
info("Acquired in separate thread. Number of threads waiting on condition: " + lock0.getWaitQueueLength(cond));
assertTrue(lock0.isHeldByCurrentThread());
assertFalse(lock0.hasQueuedThread(Thread.currentThread()));
finishedThreads.add(Thread.currentThread());
if (startedThreads.size() != finishedThreads.size()) {
assertTrue(lock0.hasWaiters(cond));
}
for (Thread t : startedThreads) {
if (!finishedThreads.contains(t))
assertTrue(lock0.hasWaiters(cond));
}
assertTrue(lock0.getWaitQueueLength(cond) == (startedThreads.size() - finishedThreads.size()));
} finally {
cond.signal();
lock0.unlock();
assertFalse(lock0.isHeldByCurrentThread());
}
return null;
}
}, totalThreads);
IgniteCondition cond = lock0.getOrCreateCondition("cond");
lock0.lock();
try {
// Wait until all threads are waiting on condition.
while (lock0.getWaitQueueLength(cond) != totalThreads) {
lock0.unlock();
Thread.sleep(1000);
lock0.lock();
}
// Signal once to get things started.
cond.signal();
} finally {
lock0.unlock();
}
fut.get();
assertFalse(lock0.hasQueuedThreads());
for (Thread t : startedThreads) assertFalse(lock0.hasQueuedThread(t));
lock0.close();
}
use of org.apache.ignite.IgniteLock in project ignite by apache.
the class IgniteLockAbstractSelfTest method testLock.
/**
* @throws Exception If failed.
*/
private void testLock(final boolean fair) throws Exception {
final IgniteLock lock0 = grid(0).reentrantLock("lock", true, fair, true);
assertEquals(0, lock0.getHoldCount());
assertFalse(lock0.hasQueuedThreads());
final int totalThreads = 2;
final Set<Thread> startedThreads = new GridConcurrentHashSet<>();
lock0.lock();
IgniteInternalFuture<?> fut = multithreadedAsync(new Callable<Object>() {
@Override
public Object call() throws Exception {
assertFalse(lock0.isHeldByCurrentThread());
startedThreads.add(Thread.currentThread());
boolean isInterrupted = false;
try {
lock0.lock();
} catch (IgniteInterruptedException ignored) {
isInterrupted = true;
fail("Lock() method is uninterruptible.");
} finally {
// Assert that thread was not interrupted.
assertFalse(isInterrupted);
// Assert that interrupted flag is set and clear it in order to call unlock().
assertTrue(Thread.interrupted());
// Assert that lock is still owned by this thread.
assertTrue(lock0.isLocked());
// Assert that this thread does own the lock.
assertTrue(lock0.isHeldByCurrentThread());
// Release lock.
lock0.unlock();
}
return null;
}
}, totalThreads);
// Wait for all threads to attempt to acquire lock.
while (startedThreads.size() != totalThreads) {
Thread.sleep(500);
}
for (Thread t : startedThreads) t.interrupt();
lock0.unlock();
fut.get();
assertFalse(lock0.isLocked());
for (Thread t : startedThreads) assertFalse(lock0.hasQueuedThread(t));
lock0.close();
}
Aggregations