Search in sources :

Example 1 with FencedLock

use of com.hazelcast.cp.lock.FencedLock in project hazelcast by hazelcast.

the class AbstractFencedLockAdvancedTest method testLockAcquired_whenLockOwnerShutsDown.

@Test
public void testLockAcquired_whenLockOwnerShutsDown() {
    lock.lock();
    CountDownLatch remoteLockedLatch = new CountDownLatch(1);
    spawn(() -> {
        HazelcastInstance otherInstance = instances[0] == proxyInstance ? instances[1] : instances[0];
        FencedLock remoteLock = otherInstance.getCPSubsystem().getLock(lock.getName());
        remoteLock.lock();
        remoteLockedLatch.countDown();
    });
    assertTrueEventually(() -> {
        LockService service = getNodeEngineImpl(primaryInstance).getService(LockService.SERVICE_NAME);
        LockRegistry registry = service.getRegistryOrNull(this.lock.getGroupId());
        assertNotNull(registry);
        Lock lock = registry.getResourceOrNull(objectName);
        assertNotNull(lock);
        assertFalse(lock.getInternalWaitKeysMap().isEmpty());
    });
    proxyInstance.shutdown();
    assertOpenEventually(remoteLockedLatch);
}
Also used : HazelcastInstance(com.hazelcast.core.HazelcastInstance) FencedLock(com.hazelcast.cp.lock.FencedLock) CountDownLatch(java.util.concurrent.CountDownLatch) FencedLock(com.hazelcast.cp.lock.FencedLock) Test(org.junit.Test)

Example 2 with FencedLock

use of com.hazelcast.cp.lock.FencedLock in project hazelcast by hazelcast.

the class FencedLockBasicTest method test_lockInterruptibly.

@Test
public void test_lockInterruptibly() throws InterruptedException {
    HazelcastInstance newInstance = factory.newHazelcastInstance(createConfig(3, 3));
    FencedLock lock = newInstance.getCPSubsystem().getLock("lock@group1");
    lock.lockInterruptibly();
    lock.unlock();
    for (HazelcastInstance instance : instances) {
        instance.getLifecycleService().terminate();
    }
    CountDownLatch latch = new CountDownLatch(1);
    AtomicReference<Throwable> ref = new AtomicReference<>();
    Thread thread = new Thread(() -> {
        try {
            latch.countDown();
            lock.lockInterruptibly();
        } catch (Throwable t) {
            ref.set(t);
        }
    });
    thread.start();
    assertOpenEventually(latch);
    thread.interrupt();
    assertTrueEventually(() -> {
        Throwable t = ref.get();
        assertTrue(t instanceof InterruptedException);
    });
}
Also used : HazelcastInstance(com.hazelcast.core.HazelcastInstance) FencedLock(com.hazelcast.cp.lock.FencedLock) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) ParallelJVMTest(com.hazelcast.test.annotation.ParallelJVMTest) QuickTest(com.hazelcast.test.annotation.QuickTest) Test(org.junit.Test)

Example 3 with FencedLock

use of com.hazelcast.cp.lock.FencedLock in project hazelcast by hazelcast.

the class HazelcastOSGiInstanceTest method getLockCalledSuccessfullyOverOSGiInstance.

@Test
public void getLockCalledSuccessfullyOverOSGiInstance() {
    FencedLock mockLock = mock(FencedLock.class);
    HazelcastInstance mockHazelcastInstance = mock(HazelcastInstance.class);
    HazelcastOSGiInstance hazelcastOSGiInstance = createHazelcastOSGiInstance(mockHazelcastInstance);
    CPSubsystem cpSubsystem = mock(CPSubsystem.class);
    when(mockHazelcastInstance.getCPSubsystem()).thenReturn(cpSubsystem);
    when(cpSubsystem.getLock("my-lock")).thenReturn(mockLock);
    assertEquals(mockLock, hazelcastOSGiInstance.getCPSubsystem().getLock("my-lock"));
    verify(cpSubsystem).getLock("my-lock");
}
Also used : FencedLock(com.hazelcast.cp.lock.FencedLock) HazelcastInstance(com.hazelcast.core.HazelcastInstance) CPSubsystem(com.hazelcast.cp.CPSubsystem) HazelcastOSGiTestUtil.createHazelcastOSGiInstance(com.hazelcast.osgi.impl.HazelcastOSGiTestUtil.createHazelcastOSGiInstance) ParallelJVMTest(com.hazelcast.test.annotation.ParallelJVMTest) QuickTest(com.hazelcast.test.annotation.QuickTest) Test(org.junit.Test)

Example 4 with FencedLock

use of com.hazelcast.cp.lock.FencedLock in project Payara by payara.

the class CMCSingletonContainer method _getContext.

/*
     * Findbugs complains that the lock acquired in this method is not
     *  unlocked on all paths in this method.
     *
     * Even though the method doesn't unlock the (possibly) acquired
     * lock, the lock is guaranteed to be unlocked in releaseContext()
     * even in the presence of (both checked and unchecked) exceptions.
     *
     * The general pattern used by various parts of the EJB container code is:
     *
     * try {
     *      container.preInvoke(inv);
     *      returnValue = container.intercept(inv);
     * } catch (Exception1 e1) {
     *      ...
     * } catch (Exception2 e2) {
     *      ...
     * } finally {
     *      container.postInvoke();
     * }
     *
     * Thus, it is clear that, BaseContainer.postInvoke() which in turn
     * calls releaseContext() will be called if container.preInvoke()
     * is called. This ensures that CMCSingletonContainer (this class)
     * releases the lock acquired by _getContext().
     *
     * Also, note that the above works even for loopback methods as
     * container.preInvoke() and container,postInvoke() will be called
     * before every bean method.
     *
     */
@Override
protected ComponentContext _getContext(EjbInvocation inv) {
    super._getContext(inv);
    InvocationInfo invInfo = inv.invocationInfo;
    MethodLockInfo lockInfo = (invInfo.methodLockInfo == null) ? defaultMethodLockInfo : invInfo.methodLockInfo;
    Lock theLock;
    if (lockInfo.isDistributed()) {
        if (_logger.isLoggable(Level.FINE)) {
            // log all lock operations
            theLock = (Lock) Proxy.newProxyInstance(loader, new Class<?>[] { Lock.class }, (proxy, method, args) -> {
                FencedLock fencedLock = clusteredLookup.getDistributedLock();
                _logger.log(Level.FINE, "DistributedLock, about to call {0}, Locked: {1}, Locked by Us: {2}, thread ID {3}", new Object[] { method.getName(), fencedLock.isLocked(), fencedLock.isLockedByCurrentThread(), Thread.currentThread().getId() });
                Object rv = method.invoke(fencedLock, args);
                _logger.log(Level.FINE, "DistributedLock, after to call {0}, Locked: {1}, Locked by Us: {2}, thread ID {3}", new Object[] { method.getName(), fencedLock.isLocked(), fencedLock.isLockedByCurrentThread(), Thread.currentThread().getId() });
                return rv;
            });
        } else {
            theLock = clusteredLookup.getDistributedLock();
        }
    } else {
        theLock = lockInfo.isReadLockedMethod() ? readLock : writeLock;
    }
    if ((rwLock.getReadHoldCount() > 0) && (!rwLock.isWriteLockedByCurrentThread())) {
        if (lockInfo.isWriteLockedMethod()) {
            throw new IllegalLoopbackException("Illegal Reentrant Access : Attempt to make " + "a loopback call on a Write Lock method '" + invInfo.targetMethod1 + "' while a Read lock is already held");
        }
    }
    /*
         * Please see comment at the beginning of the method.
         * Even though the method doesn't unlock the (possibly) acquired
         * lock, the lock is guaranteed to be unlocked in releaseContext()
         * even if exceptions were thrown in _getContext()
         */
    if (!lockInfo.hasTimeout() || ((lockInfo.hasTimeout() && (lockInfo.getTimeout() == BLOCK_INDEFINITELY)))) {
        theLock.lock();
    } else {
        try {
            boolean lockStatus = theLock.tryLock(lockInfo.getTimeout(), lockInfo.getTimeUnit());
            if (!lockStatus) {
                String msg = "Couldn't acquire a lock within " + lockInfo.getTimeout() + " " + lockInfo.getTimeUnit();
                if (lockInfo.getTimeout() == NO_BLOCKING) {
                    throw new ConcurrentAccessException(msg);
                } else {
                    throw new ConcurrentAccessTimeoutException(msg);
                }
            }
        } catch (InterruptedException inEx) {
            String msg = "Couldn't acquire a lock within " + lockInfo.getTimeout() + " " + lockInfo.getTimeUnit();
            ConcurrentAccessException cae = (lockInfo.getTimeout() == NO_BLOCKING) ? new ConcurrentAccessException(msg) : new ConcurrentAccessTimeoutException(msg);
            cae.initCause(inEx);
            throw cae;
        }
    }
    // Now that we have acquired the lock, remember it
    inv.setCMCLock(theLock);
    // Now that we have the lock return the singletonCtx
    return singletonCtx;
}
Also used : IllegalLoopbackException(javax.ejb.IllegalLoopbackException) InvocationInfo(com.sun.ejb.InvocationInfo) FencedLock(com.hazelcast.cp.lock.FencedLock) ConcurrentAccessException(javax.ejb.ConcurrentAccessException) ConcurrentAccessTimeoutException(javax.ejb.ConcurrentAccessTimeoutException) MethodLockInfo(com.sun.ejb.MethodLockInfo) FencedLock(com.hazelcast.cp.lock.FencedLock) ReentrantReadWriteLock(java.util.concurrent.locks.ReentrantReadWriteLock) Lock(java.util.concurrent.locks.Lock)

Example 5 with FencedLock

use of com.hazelcast.cp.lock.FencedLock in project Payara by payara.

the class HazelcastTimerStore method memberRemoved.

@Override
public void memberRemoved(MemberEvent event) {
    FencedLock hazelcastLock = hazelcast.getCPSubsystem().getLock("EJB-TIMER-LOCK");
    hazelcastLock.lock();
    try {
        Collection<HZTimer> allTimers = pkCache.values();
        Collection<HZTimer> removedTimers = new HashSet<>();
        for (HZTimer timer : allTimers) {
            if (timer.getMemberName().equals(event.getServer())) {
                removedTimers.add(timer);
            }
        }
        if (!removedTimers.isEmpty()) {
            logger.log(Level.INFO, "==> Restoring Timers ... ");
            Collection<HZTimer> restored = _restoreTimers(removedTimers);
            for (HZTimer timer : restored) {
                pkCache.put(timer.getKey().getTimerId(), timer);
            }
            logger.log(Level.INFO, "<== ... Timers Restored.");
        }
    } finally {
        hazelcastLock.unlock();
    }
}
Also used : FencedLock(com.hazelcast.cp.lock.FencedLock) HashSet(java.util.HashSet)

Aggregations

FencedLock (com.hazelcast.cp.lock.FencedLock)13 HazelcastInstance (com.hazelcast.core.HazelcastInstance)10 Test (org.junit.Test)10 ParallelJVMTest (com.hazelcast.test.annotation.ParallelJVMTest)8 QuickTest (com.hazelcast.test.annotation.QuickTest)7 Config (com.hazelcast.config.Config)3 CountDownLatch (java.util.concurrent.CountDownLatch)3 OperationTimeoutException (com.hazelcast.core.OperationTimeoutException)2 CPSubsystem (com.hazelcast.cp.CPSubsystem)1 ProxySessionManagerService (com.hazelcast.cp.internal.session.ProxySessionManagerService)1 RaftSessionService (com.hazelcast.cp.internal.session.RaftSessionService)1 HazelcastInstanceFactory.newHazelcastInstance (com.hazelcast.instance.impl.HazelcastInstanceFactory.newHazelcastInstance)1 HazelcastOSGiTestUtil.createHazelcastOSGiInstance (com.hazelcast.osgi.impl.HazelcastOSGiTestUtil.createHazelcastOSGiInstance)1 SlowTest (com.hazelcast.test.annotation.SlowTest)1 InvocationInfo (com.sun.ejb.InvocationInfo)1 MethodLockInfo (com.sun.ejb.MethodLockInfo)1 HashSet (java.util.HashSet)1 ExecutionException (java.util.concurrent.ExecutionException)1 Future (java.util.concurrent.Future)1 AtomicReference (java.util.concurrent.atomic.AtomicReference)1