Search in sources :

Example 1 with IgniteLock

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

Example 2 with IgniteLock

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());
        }
    }
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) IgniteException(org.apache.ignite.IgniteException) IgniteEx(org.apache.ignite.internal.IgniteEx) IgniteLock(org.apache.ignite.IgniteLock) Ignite(org.apache.ignite.Ignite) Callable(java.util.concurrent.Callable) IgniteCallable(org.apache.ignite.lang.IgniteCallable)

Example 3 with IgniteLock

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;
        }
    });
}
Also used : IgniteLock(org.apache.ignite.IgniteLock) Nullable(org.jetbrains.annotations.Nullable) 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 4 with IgniteLock

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();
}
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 5 with IgniteLock

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();
}
Also used : GridConcurrentHashSet(org.apache.ignite.internal.util.GridConcurrentHashSet) IgniteLock(org.apache.ignite.IgniteLock) IgniteInterruptedException(org.apache.ignite.IgniteInterruptedException) 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

IgniteLock (org.apache.ignite.IgniteLock)26 IgniteException (org.apache.ignite.IgniteException)17 IgniteCheckedException (org.apache.ignite.IgniteCheckedException)15 IgniteInterruptedException (org.apache.ignite.IgniteInterruptedException)15 IOException (java.io.IOException)14 ExpectedException (org.junit.rules.ExpectedException)14 Ignite (org.apache.ignite.Ignite)12 GridConcurrentHashSet (org.apache.ignite.internal.util.GridConcurrentHashSet)8 IgniteCondition (org.apache.ignite.IgniteCondition)5 IgniteInternalFuture (org.apache.ignite.internal.IgniteInternalFuture)5 Callable (java.util.concurrent.Callable)4 IgniteCallable (org.apache.ignite.lang.IgniteCallable)4 IgniteCountDownLatch (org.apache.ignite.IgniteCountDownLatch)3 IgniteSemaphore (org.apache.ignite.IgniteSemaphore)3 Nullable (org.jetbrains.annotations.Nullable)3 ArrayList (java.util.ArrayList)2 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)2 AtomicLong (java.util.concurrent.atomic.AtomicLong)2 IgniteEx (org.apache.ignite.internal.IgniteEx)2 IgniteClosure (org.apache.ignite.lang.IgniteClosure)2