use of org.apache.ignite.IgniteLock in project ignite by apache.
the class IgniteDataStructureUniqueNameTest method testUniqueName.
/**
* @param singleGrid If {@code true} uses single grid.
* @throws Exception If failed.
*/
private void testUniqueName(final boolean singleGrid) throws Exception {
final String name = IgniteUuid.randomUuid().toString();
final int DS_TYPES = 6;
final int THREADS = DS_TYPES * 3;
for (int iter = 0; iter < 20; iter++) {
log.info("Iteration: " + iter);
List<IgniteInternalFuture<Object>> futs = new ArrayList<>(THREADS);
final CyclicBarrier barrier = new CyclicBarrier(THREADS);
for (int i = 0; i < THREADS; i++) {
final int idx = i;
IgniteInternalFuture<Object> fut = GridTestUtils.runAsync(new Callable<Object>() {
@Override
public Object call() throws Exception {
try {
Thread.currentThread().setName("test thread-" + idx);
barrier.await();
Ignite ignite = singleGrid ? ignite(0) : ignite(idx % gridCount());
Object res;
switch(idx % DS_TYPES) {
case 0:
log.info("Create atomic long, grid: " + ignite.name());
res = ignite.atomicLong(name, 0, true);
break;
case 1:
log.info("Create atomic sequence, grid: " + ignite.name());
res = ignite.atomicSequence(name, 0, true);
break;
case 2:
log.info("Create atomic stamped, grid: " + ignite.name());
res = ignite.atomicStamped(name, 0, true, true);
break;
case 3:
log.info("Create atomic reference, grid: " + ignite.name());
res = ignite.atomicReference(name, null, true);
break;
case 4:
log.info("Create queue, grid: " + ignite.name());
res = ignite.queue(name, 0, config(false));
break;
case 5:
log.info("Create set, grid: " + ignite.name());
res = ignite.set(name, config(false));
break;
default:
fail();
return null;
}
log.info("Thread created: " + res);
return res;
} catch (IgniteException e) {
log.info("Failed: " + e);
return e;
}
}
});
futs.add(fut);
}
Closeable dataStructure = null;
int createdCnt = 0;
for (IgniteInternalFuture<Object> fut : futs) {
Object res = fut.get();
if (res instanceof IgniteException || res instanceof IgniteCheckedException)
continue;
assertTrue("Unexpected object: " + res, res instanceof IgniteAtomicLong || res instanceof IgniteAtomicSequence || res instanceof IgniteAtomicReference || res instanceof IgniteAtomicStamped || res instanceof IgniteCountDownLatch || res instanceof IgniteQueue || res instanceof IgniteSet || res instanceof IgniteSemaphore || res instanceof IgniteLock);
log.info("Data structure created: " + dataStructure);
createdCnt++;
if (dataStructure != null)
assertEquals(dataStructure.getClass(), res.getClass());
else
dataStructure = (Closeable) res;
}
assertNotNull(dataStructure);
assertEquals(3, createdCnt);
dataStructure.close();
}
}
use of org.apache.ignite.IgniteLock in project ignite by apache.
the class IgniteLockAbstractSelfTest method testHasQueuedThreads.
/**
* @throws Exception If failed.
*/
private void testHasQueuedThreads(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());
startedThreads.add(Thread.currentThread());
lock0.lock();
// Wait until every thread tries to lock.
do {
Thread.sleep(1000);
} while (startedThreads.size() != totalThreads);
try {
info("Acquired in separate thread. ");
assertTrue(lock0.isHeldByCurrentThread());
assertFalse(lock0.hasQueuedThread(Thread.currentThread()));
finishedThreads.add(Thread.currentThread());
if (startedThreads.size() != finishedThreads.size()) {
assertTrue(lock0.hasQueuedThreads());
}
for (Thread t : startedThreads) {
assertTrue(lock0.hasQueuedThread(t) != finishedThreads.contains(t));
}
} finally {
lock0.unlock();
assertFalse(lock0.isHeldByCurrentThread());
}
return null;
}
}, totalThreads);
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 IgniteClientDataStructuresAbstractTest method testReentrantLock.
/**
* @param creator Creator node.
* @param other Other node.
* @throws Exception If failed.
*/
private void testReentrantLock(Ignite creator, final Ignite other) throws Exception {
assertNull(creator.reentrantLock("lock1", true, false, false));
assertNull(other.reentrantLock("lock1", true, false, false));
try (IgniteLock lock = creator.reentrantLock("lock1", true, false, true)) {
assertNotNull(lock);
assertFalse(lock.isLocked());
final Semaphore semaphore = new Semaphore(0);
IgniteInternalFuture<?> fut = GridTestUtils.runAsync(new Callable<Object>() {
@Override
public Object call() throws Exception {
IgniteLock lock0 = other.reentrantLock("lock1", true, false, false);
lock0.lock();
assertTrue(lock0.isLocked());
semaphore.release();
U.sleep(1000);
log.info("Release reentrant lock.");
lock0.unlock();
return null;
}
});
semaphore.acquire();
log.info("Try acquire lock.");
assertTrue(lock.tryLock(5000, TimeUnit.MILLISECONDS));
log.info("Finished wait.");
fut.get();
assertTrue(lock.isLocked());
lock.unlock();
assertFalse(lock.isLocked());
}
assertNull(creator.reentrantLock("lock1", true, false, false));
assertNull(other.reentrantLock("lock1", true, false, false));
}
use of org.apache.ignite.IgniteLock in project ignite by apache.
the class IgniteLockAbstractSelfTest method testFairness.
/**
* Tests if lock is evenly acquired among nodes when fair flag is set on.
* Since exact ordering of lock acquisitions cannot be guaranteed because it also depends
* on the OS thread scheduling, certain deviation from uniform distribution is tolerated.
* @throws Exception If failed.
*/
public void testFairness() throws Exception {
if (gridCount() == 1)
return;
// Total number of ops.
final long opsCount = 10000;
// Allowed deviation from uniform distribution.
final double tolerance = 0.05;
// Shared counter.
final String OPS_COUNTER = "ops_counter";
// Number of threads, one per node.
final int threadCount = gridCount();
final AtomicLong threadCounter = new AtomicLong(0);
Ignite ignite = startGrid(gridCount());
// Initialize reentrant lock.
IgniteLock l = ignite.reentrantLock("lock", true, true, true);
// Initialize OPS_COUNTER.
ignite.getOrCreateCache(OPS_COUNTER).put(OPS_COUNTER, (long) 0);
final Map<Integer, Long> counts = new ConcurrentHashMap<>();
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, Long> closure = new IgniteClosure<Ignite, Long>() {
@Override
public Long apply(Ignite ignite) {
IgniteLock l = ignite.reentrantLock("lock", true, true, true);
long localCount = 0;
IgniteCountDownLatch latch = ignite.countDownLatch("latch", threadCount, false, true);
latch.countDown();
latch.await();
while (true) {
l.lock();
try {
long opsCounter = (long) ignite.getOrCreateCache(OPS_COUNTER).get(OPS_COUNTER);
if (opsCounter == opsCount)
break;
ignite.getOrCreateCache(OPS_COUNTER).put(OPS_COUNTER, ++opsCounter);
localCount++;
if (localCount > 1000) {
assertTrue(localCount < (1 + tolerance) * opsCounter / threadCount);
assertTrue(localCount > (1 - tolerance) * opsCounter / threadCount);
}
if (localCount % 100 == 0) {
info("Node [id=" + ignite.cluster().localNode().id() + "] acquired " + localCount + " times. " + "Total ops count: " + opsCounter + "/" + opsCount + "]");
}
} finally {
l.unlock();
}
}
return localCount;
}
};
long localCount = closure.apply(grid);
counts.put(localNodeId, localCount);
return null;
}
}, threadCount);
fut.get();
long totalSum = 0;
for (int i = 0; i < gridCount(); i++) {
totalSum += counts.get(i);
info("Node " + grid(i).localNode().id() + " acquired the lock " + counts.get(i) + " times. ");
}
assertEquals(totalSum, opsCount);
l.close();
ignite.close();
}
use of org.apache.ignite.IgniteLock in project ignite by apache.
the class IgniteLockAbstractSelfTest method checkFailover.
/**
* @param failoverSafe Failover safe flag.
* @throws Exception If failed.
*/
private void checkFailover(final boolean failoverSafe, final boolean fair) throws Exception {
IgniteEx g = startGrid(NODES_CNT + 1);
// For vars locality.
{
// Ensure not exists.
assert g.reentrantLock("lock", failoverSafe, fair, false) == null;
IgniteLock lock = g.reentrantLock("lock", failoverSafe, fair, true);
lock.lock();
assert lock.tryLock();
assertEquals(2, lock.getHoldCount());
}
Ignite g0 = grid(0);
final IgniteLock lock0 = g0.reentrantLock("lock", false, fair, false);
assert !lock0.tryLock();
assertEquals(0, lock0.getHoldCount());
IgniteInternalFuture<?> fut = multithreadedAsync(new Callable<Object>() {
@Override
public Object call() throws Exception {
try {
lock0.lock();
info("Acquired in separate thread.");
// Lock is acquired silently only in failoverSafe mode.
assertTrue(failoverSafe);
lock0.unlock();
info("Released lock in separate thread.");
} catch (IgniteException e) {
if (!failoverSafe)
info("Ignored expected exception: " + e);
else
throw e;
}
return null;
}
}, 1);
Thread.sleep(100);
g.close();
fut.get(500);
lock0.close();
}
Aggregations