Search in sources :

Example 1 with IgniteCondition

use of org.apache.ignite.IgniteCondition 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).");
}
Also used : Ignite(org.apache.ignite.Ignite) IgniteLock(org.apache.ignite.IgniteLock) IgniteCondition(org.apache.ignite.IgniteCondition)

Example 2 with IgniteCondition

use of org.apache.ignite.IgniteCondition 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();
}
Also used : GridConcurrentHashSet(org.apache.ignite.internal.util.GridConcurrentHashSet) IgniteLock(org.apache.ignite.IgniteLock) IgniteCondition(org.apache.ignite.IgniteCondition) IgniteInterruptedException(org.apache.ignite.IgniteInterruptedException) ExpectedException(org.junit.rules.ExpectedException) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) IgniteException(org.apache.ignite.IgniteException) IOException(java.io.IOException)

Example 3 with IgniteCondition

use of org.apache.ignite.IgniteCondition in project ignite by apache.

the class GridCacheLockImpl method getOrCreateCondition.

/** {@inheritDoc} */
@Override
public IgniteCondition getOrCreateCondition(String name) {
    ctx.kernalContext().gateway().readLock();
    try {
        initializeReentrantLock();
        IgniteCondition result = sync.newCondition(name);
        sync.validate(false);
        return result;
    } catch (IgniteCheckedException e) {
        throw U.convertException(e);
    } finally {
        ctx.kernalContext().gateway().readUnlock();
    }
}
Also used : IgniteCheckedException(org.apache.ignite.IgniteCheckedException) IgniteCondition(org.apache.ignite.IgniteCondition)

Example 4 with IgniteCondition

use of org.apache.ignite.IgniteCondition in project ignite by apache.

the class IgniteLockAbstractSelfTest method testConditionInterruptAwait.

/**
     * @throws Exception If failed.
     */
private void testConditionInterruptAwait(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<>();
    IgniteInternalFuture<?> fut = multithreadedAsync(new Callable<Object>() {

        @Override
        public Object call() throws Exception {
            assertFalse(lock0.isHeldByCurrentThread());
            startedThreads.add(Thread.currentThread());
            boolean isInterrupted = false;
            lock0.lock();
            IgniteCondition cond = lock0.getOrCreateCondition("cond");
            try {
                cond.await();
            } catch (IgniteInterruptedException ignored) {
                isInterrupted = true;
            } finally {
                // Assert that thread was interrupted.
                assertTrue(isInterrupted);
                // Assert that lock is still locked.
                assertTrue(lock0.isLocked());
                // Assert that this thread does own the lock.
                assertTrue(lock0.isHeldByCurrentThread());
                // Release lock.
                if (lock0.isHeldByCurrentThread())
                    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();
    fut.get();
    assertFalse(lock0.isLocked());
    for (Thread t : startedThreads) assertFalse(lock0.hasQueuedThread(t));
    lock0.close();
}
Also used : GridConcurrentHashSet(org.apache.ignite.internal.util.GridConcurrentHashSet) IgniteLock(org.apache.ignite.IgniteLock) IgniteInterruptedException(org.apache.ignite.IgniteInterruptedException) IgniteCondition(org.apache.ignite.IgniteCondition) IgniteInterruptedException(org.apache.ignite.IgniteInterruptedException) ExpectedException(org.junit.rules.ExpectedException) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) IgniteException(org.apache.ignite.IgniteException) IOException(java.io.IOException)

Example 5 with IgniteCondition

use of org.apache.ignite.IgniteCondition in project ignite by apache.

the class IgniteLockAbstractSelfTest method testConditionAwaitUninterruptibly.

/**
     * @throws Exception If failed.
     */
private void testConditionAwaitUninterruptibly(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<>();
    IgniteInternalFuture<?> fut = multithreadedAsync(new Callable<Object>() {

        @Override
        public Object call() throws Exception {
            assertFalse(lock0.isHeldByCurrentThread());
            startedThreads.add(Thread.currentThread());
            boolean isInterrupted = false;
            lock0.lock();
            IgniteCondition cond = lock0.getOrCreateCondition("cond");
            try {
                cond.awaitUninterruptibly();
            } catch (IgniteInterruptedException ignored) {
                isInterrupted = true;
            } finally {
                // Assert that thread was not interrupted.
                assertFalse(isInterrupted);
                // Assert that lock is still locked.
                assertTrue(lock0.isLocked());
                // Assert that this thread does own the lock.
                assertTrue(lock0.isHeldByCurrentThread());
                // Clear interrupt flag.
                assertTrue(Thread.interrupted());
                // Release lock.
                if (lock0.isHeldByCurrentThread())
                    lock0.unlock();
            }
            return null;
        }
    }, totalThreads);
    // Wait for all threads to attempt to acquire lock.
    while (startedThreads.size() != totalThreads) {
        Thread.sleep(500);
    }
    lock0.lock();
    for (Thread t : startedThreads) {
        t.interrupt();
        lock0.getOrCreateCondition("cond").signal();
    }
    lock0.unlock();
    fut.get();
    assertFalse(lock0.isLocked());
    for (Thread t : startedThreads) assertFalse(lock0.hasQueuedThread(t));
    lock0.close();
}
Also used : GridConcurrentHashSet(org.apache.ignite.internal.util.GridConcurrentHashSet) IgniteLock(org.apache.ignite.IgniteLock) IgniteInterruptedException(org.apache.ignite.IgniteInterruptedException) IgniteCondition(org.apache.ignite.IgniteCondition) IgniteInterruptedException(org.apache.ignite.IgniteInterruptedException) ExpectedException(org.junit.rules.ExpectedException) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) IgniteException(org.apache.ignite.IgniteException) IOException(java.io.IOException)

Aggregations

IgniteCondition (org.apache.ignite.IgniteCondition)6 IgniteLock (org.apache.ignite.IgniteLock)5 IgniteCheckedException (org.apache.ignite.IgniteCheckedException)4 IOException (java.io.IOException)3 IgniteException (org.apache.ignite.IgniteException)3 IgniteInterruptedException (org.apache.ignite.IgniteInterruptedException)3 GridConcurrentHashSet (org.apache.ignite.internal.util.GridConcurrentHashSet)3 ExpectedException (org.junit.rules.ExpectedException)3 Ignite (org.apache.ignite.Ignite)2 ArrayList (java.util.ArrayList)1 Callable (java.util.concurrent.Callable)1 IgniteInternalFuture (org.apache.ignite.internal.IgniteInternalFuture)1 IgniteCallable (org.apache.ignite.lang.IgniteCallable)1