use of java.util.concurrent.BrokenBarrierException in project ignite by apache.
the class GridConcurrentLinkedHashMapBenchmark method test.
/**
* Test a generic access method on map.
*
* @param readOp Access method to test.
* @param threadCnt Number of threads to run.
* @param writeProportion Amount of writes from total number of iterations.
*/
@SuppressWarnings({ "BusyWait" })
private static void test(C2<Integer, ConcurrentLinkedHashMap<Integer, Integer>, Integer> readOp, int threadCnt, double writeProportion) {
assert writeProportion < 1;
ConcurrentLinkedHashMap<Integer, Integer> map = new ConcurrentLinkedHashMap<>();
CyclicBarrier barrier = new CyclicBarrier(threadCnt + 1);
Collection<TestThread> threads = new ArrayList<>(threadCnt);
for (int i = 0; i < threadCnt; i++) {
TestThread thread = new TestThread(readOp, map, writeProportion, barrier);
threads.add(thread);
thread.start();
}
long start;
try {
// Wait threads warm-up.
while (barrier.getNumberWaiting() != threadCnt) Thread.sleep(1);
// Starting test and letting it run for 1 minute.
barrier.await();
start = System.currentTimeMillis();
Thread.sleep(60000);
} catch (InterruptedException ignored) {
return;
} catch (BrokenBarrierException e) {
e.printStackTrace();
return;
}
for (TestThread th : threads) th.interrupt();
try {
for (TestThread th : threads) th.join();
} catch (InterruptedException ignored) {
return;
}
long time = System.currentTimeMillis() - start;
long iters = 0;
for (TestThread th : threads) iters += th.iterations();
System.out.printf("%8s, %8d, %12d, %12d, %12d, %8.3f, %8.2f\n", readOp.toString(), threadCnt, 1000 * iters / time, 1000 * iters / (time * threadCnt), iters, time / (double) 1000, writeProportion);
}
use of java.util.concurrent.BrokenBarrierException in project ignite by apache.
the class IgniteOffheapReadWriteLockSelfTest method checkTagIdUpdate.
/**
* @throws Exception if failed.
*/
private void checkTagIdUpdate(final boolean waitBeforeSwitch) throws Exception {
final int numPairs = 100;
final Pair[] data = new Pair[numPairs];
for (int i = 0; i < numPairs; i++) data[i] = new Pair();
final OffheapReadWriteLock lock = new OffheapReadWriteLock(16);
final long ptr = GridUnsafe.allocateMemory(OffheapReadWriteLock.LOCK_SIZE);
lock.init(ptr, TAG_0);
final AtomicInteger reads = new AtomicInteger();
final AtomicInteger writes = new AtomicInteger();
final AtomicBoolean done = new AtomicBoolean(false);
final int threadCnt = 32;
final CyclicBarrier barr = new CyclicBarrier(threadCnt);
IgniteInternalFuture<Long> fut = GridTestUtils.runMultiThreadedAsync(new Callable<Object>() {
/**
* {@inheritDoc}
*/
@Override
public Object call() throws Exception {
try {
ThreadLocalRandom rnd = ThreadLocalRandom.current();
int tag = TAG_0;
long lastSwitch = System.currentTimeMillis();
while (true) {
boolean write = rnd.nextInt(10) < 2;
boolean locked;
boolean switched = false;
if (write) {
locked = lock.writeLock(ptr, tag);
if (locked) {
try {
assertTrue(lock.isWriteLocked(ptr));
assertFalse(lock.isReadLocked(ptr));
int idx = rnd.nextInt(numPairs);
int delta = rnd.nextInt(100_000);
data[idx].a += delta;
data[idx].b -= delta;
} finally {
switched = System.currentTimeMillis() - lastSwitch > 1_000 || !waitBeforeSwitch;
if (switched && waitBeforeSwitch)
info("Switching...");
int tag1 = (tag + (switched ? 1 : 0)) & 0xFFFF;
if (tag1 == 0)
tag1 = 1;
lock.writeUnlock(ptr, tag1);
}
writes.incrementAndGet();
}
} else {
locked = lock.readLock(ptr, tag);
if (locked) {
try {
assert locked;
assertFalse(lock.isWriteLocked(ptr));
assertTrue(lock.isReadLocked(ptr));
for (int i1 = 0; i1 < data.length; i1++) {
Pair pair = data[i1];
assertEquals("Failed check for index: " + i1, pair.a, -pair.b);
}
} finally {
lock.readUnlock(ptr);
}
reads.incrementAndGet();
}
}
if (!locked || switched) {
try {
barr.await();
} catch (BrokenBarrierException ignore) {
// Done.
return null;
}
tag = (tag + 1) & 0xFFFF;
if (tag == 0)
tag = 1;
if (waitBeforeSwitch || (!waitBeforeSwitch && tag == 1))
info("Switch to a new tag: " + tag);
if (done.get()) {
barr.reset();
return null;
}
lastSwitch = System.currentTimeMillis();
}
}
} catch (Throwable e) {
e.printStackTrace();
}
return null;
}
}, threadCnt, "tester");
for (int i = 0; i < 30; i++) {
Thread.sleep(1_000);
info("Reads: " + reads.getAndSet(0) + ", writes=" + writes.getAndSet(0));
}
done.set(true);
fut.get();
validate(data);
}
use of java.util.concurrent.BrokenBarrierException in project ignite by apache.
the class GridTcpCommunicationSpiMultithreadedSelfTest method testFlowSend.
/**
* @throws Exception If failed.
*/
public void testFlowSend() throws Exception {
reject = true;
final CyclicBarrier barrier = new CyclicBarrier(THREAD_CNT);
final Random rnd = new Random();
final ClusterNode from = randomNode(rnd);
ClusterNode tmp;
do {
tmp = randomNode(rnd);
} while (tmp.id().equals(from.id()));
final ClusterNode to = tmp;
final int iterationCnt = 1000;
final AtomicInteger threadId = new AtomicInteger();
final int interval = 50;
IgniteInternalFuture<?> fut = multithreadedAsync(new Runnable() {
/**
* {@inheritDoc}
*/
@Override
public void run() {
try {
// Only first thread will print messages.
int id = threadId.getAndIncrement();
for (int i = 0; i < iterationCnt; i++) {
if (id == 0 && (i % 50) == 0)
info(">>> Running iteration " + i);
try {
for (ClusterNode node : nodes) {
Message msg = new GridTestMessage(from.id(), msgId.getAndIncrement(), 0);
spis.get(from.id()).sendMessage(node, msg);
}
} catch (IgniteException e) {
log.warning(">>> Oops, unable to send message (safe to ignore).", e);
}
barrier.await();
}
} catch (InterruptedException ignored) {
Thread.currentThread().interrupt();
} catch (BrokenBarrierException e) {
info("Wait on barrier failed: " + e);
Thread.currentThread().interrupt();
}
}
}, THREAD_CNT, "message-sender");
final AtomicBoolean run = new AtomicBoolean(true);
IgniteInternalFuture<?> fut2 = multithreadedAsync(new Runnable() {
@Override
public void run() {
try {
while (run.get() && !Thread.currentThread().isInterrupted()) {
U.sleep(interval * 3 / 2);
((TcpCommunicationSpi) spis.get(from.id())).onNodeLeft(to.id());
}
} catch (IgniteInterruptedCheckedException ignored) {
Thread.currentThread().interrupt();
}
}
}, 1);
fut.get();
run.set(false);
fut2.get();
// Wait when all messages are acknowledged to do not break next tests' logic.
for (CommunicationSpi<Message> spi : spis.values()) {
GridNioServer srv = U.field(spi, "nioSrvr");
Collection<? extends GridNioSession> sessions = GridTestUtils.getFieldValue(srv, "sessions");
for (GridNioSession ses : sessions) {
final GridNioRecoveryDescriptor snd = ses.outRecoveryDescriptor();
if (snd != null) {
GridTestUtils.waitForCondition(new GridAbsPredicate() {
@Override
public boolean apply() {
return snd.messagesRequests().isEmpty();
}
}, 10_000);
assertEquals("Unexpected messages: " + snd.messagesRequests(), 0, snd.messagesRequests().size());
}
}
}
}
use of java.util.concurrent.BrokenBarrierException in project jersey by jersey.
the class ParallelTest method testParallel.
@Test
public void testParallel() throws BrokenBarrierException, InterruptedException, TimeoutException {
final ScheduledExecutorService executor = Executors.newScheduledThreadPool(PARALLEL_CLIENTS);
try {
final WebTarget target = target();
for (int i = 1; i <= PARALLEL_CLIENTS; i++) {
final int id = i;
executor.submit(new Runnable() {
@Override
public void run() {
try {
startBarrier.await();
Response response;
response = target.path(PATH).request().get();
assertEquals("GET", response.readEntity(String.class));
receivedCounter.incrementAndGet();
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
LOGGER.log(Level.WARNING, "Client thread " + id + " interrupted.", ex);
} catch (BrokenBarrierException ex) {
LOGGER.log(Level.INFO, "Client thread " + id + " failed on broken barrier.", ex);
} catch (Throwable t) {
t.printStackTrace();
LOGGER.log(Level.WARNING, "Client thread " + id + " failed on unexpected exception.", t);
} finally {
doneLatch.countDown();
}
}
});
}
startBarrier.await(1, TimeUnit.SECONDS);
assertTrue("Waiting for clients to finish has timed out.", doneLatch.await(5 * getAsyncTimeoutMultiplier(), TimeUnit.SECONDS));
assertEquals("Resource counter", PARALLEL_CLIENTS, resourceCounter.get());
assertEquals("Received counter", PARALLEL_CLIENTS, receivedCounter.get());
} finally {
executor.shutdownNow();
Assert.assertTrue("Executor termination", executor.awaitTermination(5, TimeUnit.SECONDS));
}
}
use of java.util.concurrent.BrokenBarrierException in project druid by druid-io.
the class NamedIntrospectionHandler method testConcurrencyStaaaaaaaaaaartStop.
@Test
public void testConcurrencyStaaaaaaaaaaartStop() throws Exception {
lookupReferencesManager.stop();
final CyclicBarrier cyclicBarrier = new CyclicBarrier(CONCURRENT_THREADS);
final Runnable start = new Runnable() {
@Override
public void run() {
try {
cyclicBarrier.await();
} catch (InterruptedException | BrokenBarrierException e) {
throw Throwables.propagate(e);
}
lookupReferencesManager.start();
}
};
final Collection<ListenableFuture<?>> futures = new ArrayList<>(CONCURRENT_THREADS);
for (int i = 0; i < CONCURRENT_THREADS; ++i) {
futures.add(executorService.submit(start));
}
lookupReferencesManager.stop();
Futures.allAsList(futures).get(100, TimeUnit.MILLISECONDS);
for (ListenableFuture future : futures) {
Assert.assertNull(future.get());
}
}
Aggregations