List of usage examples for java.util.concurrent CyclicBarrier CyclicBarrier
public CyclicBarrier(int parties)
From source file:org.nuxeo.ecm.core.TestSQLRepositoryReadAcls.java
protected void doParallelPrepareUserReadAcls(int i) throws Throwable { // set ACP on root ACPImpl acp = new ACPImpl(); ACLImpl acl = new ACLImpl(); String username = "user" + i; acl.add(new ACE("Administrator", "Everything", true)); acl.add(new ACE(username, "Everything", true)); acp.addACL(acl);/* w w w . j a va 2s. c o m*/ String name = "doc" + i; DocumentModel doc = session.createDocumentModel("/", name, "File"); doc = session.createDocument(doc); doc.setACP(acp, true); session.save(); closeSession(); TransactionHelper.commitOrRollbackTransaction(); CyclicBarrier barrier = new CyclicBarrier(2); CountDownLatch firstReady = new CountDownLatch(1); PrepareUserReadAclsJob r1 = new PrepareUserReadAclsJob(name, username, database.repositoryName, firstReady, barrier); PrepareUserReadAclsJob r2 = new PrepareUserReadAclsJob(name, username, database.repositoryName, null, barrier); Thread t1 = null; Thread t2 = null; try { t1 = new Thread(r1, "t1"); t2 = new Thread(r2, "t2"); t1.start(); if (firstReady.await(60, TimeUnit.SECONDS)) { t2.start(); t1.join(); t1 = null; t2.join(); t2 = null; if (r1.throwable != null) { throw r1.throwable; } if (r2.throwable != null) { throw r2.throwable; } } // else timed out } finally { // error condition recovery if (t1 != null) { t1.interrupt(); } if (t2 != null) { t2.interrupt(); } } // after both threads have run, check that we don't see // duplicate documents TransactionHelper.startTransaction(); session = openSessionAs(username); checkOneDoc(session, name); // failed for PostgreSQL closeSession(); TransactionHelper.commitOrRollbackTransaction(); TransactionHelper.startTransaction(); openSession(); }
From source file:org.scribble.cli.ExecUtil.java
/** * Runs a process, up to a certain timeout, * /*from w ww . ja va 2 s. c o m*/ * @throws IOException * @throws TimeoutException * @throws ExecutionException * @throws InterruptedException */ public static ProcessSummary execUntil(Map<String, String> env, long timeout, String... command) throws IOException, InterruptedException, ExecutionException { ProcessBuilder builder = new ProcessBuilder(command); builder.environment().putAll(env); Process process = builder.start(); ExecutorService executorService = Executors.newFixedThreadPool(3); CyclicBarrier onStart = new CyclicBarrier(3); Future<String> stderr = executorService.submit(toString(process.getErrorStream(), onStart)); Future<String> stdout = executorService.submit(toString(process.getInputStream(), onStart)); Future<Integer> waitFor = executorService.submit(waitFor(process, onStart)); ProcessSummary result = null; try { waitFor.get(timeout, TimeUnit.MILLISECONDS); } catch (TimeoutException e) { // timeouts are ok } finally { process.destroy(); waitFor.get(); result = new ProcessSummary(stdout.get(), stderr.get(), process.exitValue()); executorService.shutdown(); } return result; }
From source file:de.codesourcery.eve.skills.ui.utils.ParallelUITasksRunner.java
public static boolean submitParallelTasks(final ApplicationThreadManager threadManager, final UITask parent, UITask... children) {/*from ww w. j a v a 2 s . c o m*/ final AtomicInteger childSuccesses = new AtomicInteger(0); final AtomicInteger childFailures = new AtomicInteger(0); if (parent == null) { throw new IllegalArgumentException("parent task cannot be NULL"); } if (ArrayUtils.isEmpty(children)) { throw new IllegalArgumentException("Need to provide at least one child task"); } final CyclicBarrier startBarrier = new CyclicBarrier(children.length + 1) { @Override public void reset() { System.out.println("========== resetting start barrier =========== "); super.reset(); } }; final CountDownLatch childrenTerminated = new CountDownLatch(children.length); int submittedChildren = 0; for (final UITask child : children) { final UITask wrapped = new UITask() { @Override public void successHook() throws Exception { boolean success = false; try { child.successHook(); success = true; } finally { if (success) { childSuccesses.incrementAndGet(); } else { childFailures.incrementAndGet(); } childrenTerminated.countDown(); } } @Override public void beforeExecution() { child.beforeExecution(); // note: when this method throws an exception , #failure() is invoked } @Override public void setEnabledHook(boolean yesNo) { child.setEnabledHook(yesNo); } @Override public void failureHook(Throwable t) throws Exception { try { child.failureHook(t); } finally { childFailures.incrementAndGet(); childrenTerminated.countDown(); } } @Override public void cancellationHook() { try { child.cancellationHook(); } finally { childFailures.incrementAndGet(); childrenTerminated.countDown(); } } @Override public String getId() { return child.getId(); } @Override public void run() throws Exception { try { if (log.isTraceEnabled()) { log.trace("run(): Child task " + getId() + " is now waiting."); } startBarrier.await(); // will BrokenBarrierException if any of the child tasks could not be started, } catch (InterruptedException e) { log.error("run(): Child task " + getId() + " was interrupted"); Thread.currentThread().interrupt(); } catch (BrokenBarrierException e) { log.error("run(): Child task" + getId() + " aborted, barrier broken."); throw new RuntimeException( "Child task not started because another child task failed submitTask()"); } if (log.isTraceEnabled()) { log.trace("run(): Child task " + getId() + " is now running."); } child.run(); } }; if (null == threadManager.submitTask(wrapped, false)) { log.error("submitParallelTasks(): Failed to submit child " + child); // note: I wait for (submittedChildren-childFailures) because some // child task may have already failed before reaching their run() method while (startBarrier.getNumberWaiting() != (submittedChildren - childFailures.get())) { log.info("submitParallelTasks(): Waiting for all child tasks to reach barrier ( " + startBarrier.getNumberWaiting() + " waiting)"); try { java.lang.Thread.sleep(500); } catch (Exception e) { } ; } startBarrier.reset(); // will cause all child threads waiting on this barrier to terminate return false; } submittedChildren++; } /* * All children are submitted and waiting at the barrier. */ final boolean parentSubmitted = null != threadManager.submitTask("Control thread of " + parent.getId(), new Runnable() { @Override public void run() { try { while (true) { try { log.debug("run(): Parent task " + parent.getId() + " is waiting for it's children to start..."); startBarrier.await(5, TimeUnit.SECONDS); break; } catch (TimeoutException e) { if (childFailures.get() != 0) { runFailureHookOnEDT(parent, childFailures.get() + " child tasks of parent task " + parent.getId() + " failed to start."); return; } } } } catch (InterruptedException e) { runFailureHookOnEDT(parent, "Parent task " + parent.getId() + " was interrupted while waiting" + " for it's children to start."); startBarrier.reset(); // let children fail. Thread.currentThread().interrupt(); return; } catch (BrokenBarrierException e) { runFailureHookOnEDT(parent, "Parent task " + parent.getId() + " failed to wait for it's children"); throw new RuntimeException("Internal error - task " + parent.getId() + " failed to wait for it's children?"); } log.debug("run(): Task " + parent.getId() + " is waiting for it's children to finish"); try { childrenTerminated.await(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); runFailureHookOnEDT(parent, "Parent task " + parent.getId() + " was interrupted while waiting for it's children"); return; } log.info("run(): All children of parent task " + parent.getId() + " have finished ( success: " + childSuccesses.get() + " / failure: " + childFailures.get() + ")"); if (childFailures.get() > 0) { runFailureHookOnEDT(parent, childFailures.get() + " child tasks of parent " + parent.getId() + " have FAILED."); return; } if (null == threadManager.submitTask(parent, false)) { runFailureHookOnEDT(parent, "Failed to submit parent task " + parent.getId()); return; } } }, false); if (!parentSubmitted) { log.debug("submitParallelTasks(): Failed to submit parent task " + parent.getId() + " , terminating child tasks."); startBarrier.reset(); // aborts all child tasks with a BrokenBarrierException } return parentSubmitted; }
From source file:org.jolokia.client.request.J4pReadIntegrationTest.java
@Test public void error404ConnectionTest() throws Exception { final J4pReadRequest req = new J4pReadRequest(itSetup.getAttributeMBean(), "LongSeconds"); try {// w ww. j a va 2 s . c o m stop(); startWithoutAgent(); j4pClient.execute(req); fail(); } catch (J4pRemoteException exp) { assertEquals(404, exp.getStatus()); } stop(); start(); final CyclicBarrier barrier = new CyclicBarrier(10); final Queue errors = new ConcurrentLinkedQueue(); Runnable run = new Runnable() { public void run() { try { j4pClient.execute(req); } catch (Exception e) { errors.add(1); System.err.println(e); } try { barrier.await(); } catch (InterruptedException ex) { return; } catch (BrokenBarrierException ex) { return; } } }; for (int i = 0; i < 10; i++) { new Thread(run).start(); } if (barrier.await() == 0) { //System.err.println("Finished"); assertEquals(0, errors.size(), "Concurrent calls should work"); } }
From source file:org.casbah.provider.openssl.OpenSslWrapper.java
public int executeCommand(InputStream input, OutputStream output, OutputStream error, final List<String> parameters) throws IOException, InterruptedException { List<String> fullParams = new ArrayList<String>(parameters); fullParams.add(0, opensslExecutable); ProcessBuilder processBuilder = new ProcessBuilder(fullParams); CyclicBarrier barrier = new CyclicBarrier(3); Map<String, String> env = processBuilder.environment(); env.put(CASBAH_SSL_CA_ROOT, caRootDir.getAbsolutePath()); Process proc = processBuilder.start(); if (input != null) { BufferedOutputStream stdin = new BufferedOutputStream(proc.getOutputStream()); IOUtils.copy(input, stdin);// w w w . ja va2s . c o m stdin.flush(); } StreamConsumer outputConsumer = new StreamConsumer(output, proc.getInputStream(), barrier, TIMEOUT); StreamConsumer errorConsumer = new StreamConsumer(error, proc.getErrorStream(), barrier, TIMEOUT); outputConsumer.start(); errorConsumer.start(); int returnValue = proc.waitFor(); try { barrier.await(TIMEOUT, TimeUnit.SECONDS); } catch (Exception e) { e.printStackTrace(); } return returnValue; }
From source file:com.googlecode.ehcache.annotations.performance.CacheKeyGeneratorPerformanceTest.java
@Test public void testCacheKeyGeneratorPerformance() throws Exception { final ThreadGroupRunner threadGroupRunner = new ThreadGroupRunner("CacheKeyGeneratorPerformanceTest-", true);// www . j a v a 2 s . co m final int threads = 20; this.testThreadStateLatch = new CyclicBarrier(threads + 1); threadGroupRunner.addTask(threads, new KeyGenerationRunnable()); threadGroupRunner.start(); final CachingReflectionHelper reflectionHelper = new CachingReflectionHelper(); final String[] cacheNames = sort(this.cacheManager.getCacheNames()); final StringBuilder header = new StringBuilder(); header.append("Key Count|Duration|"); for (final String cacheName : cacheNames) { header.append(cacheName).append("|Size|Hits|Misses|"); } header.append("generator|include method|include parameter types|use reflection"); System.out.println(header); for (int totalLoopCount = 1; totalLoopCount <= 16; totalLoopCount++) { int duration = 10; if (totalLoopCount == 1) { duration = 3; } else { System.err.println("Sleeping 5s Before: " + duration); TimeUnit.SECONDS.sleep(5); } this.switchingCacheKeyGenerator.reset(); CacheKeyGenerator<Serializable> cacheKeyGenerator; while ((cacheKeyGenerator = this.switchingCacheKeyGenerator.nextCacheKeyGenerator()) != null) { if (cacheKeyGenerator instanceof ReflectionHelperAware) { ((ReflectionHelperAware) cacheKeyGenerator).setReflectionHelper(reflectionHelper); } for (int configIndex = 0; configIndex < 4; configIndex++) { final String generatorConfig; if (cacheKeyGenerator instanceof AbstractDeepCacheKeyGenerator) { @SuppressWarnings("unchecked") final AbstractDeepCacheKeyGenerator<?, Serializable> deepCacheKeyGenerator = (AbstractDeepCacheKeyGenerator<?, Serializable>) cacheKeyGenerator; switch (configIndex) { case 0: deepCacheKeyGenerator.setCheckforCycles(true); deepCacheKeyGenerator.setIncludeMethod(false); deepCacheKeyGenerator.setIncludeParameterTypes(false); deepCacheKeyGenerator.setUseReflection(false); generatorConfig = "|false|false|false"; break; case 1: deepCacheKeyGenerator.setCheckforCycles(true); deepCacheKeyGenerator.setIncludeMethod(true); deepCacheKeyGenerator.setIncludeParameterTypes(false); deepCacheKeyGenerator.setUseReflection(false); generatorConfig = "|true|false|false"; break; case 2: deepCacheKeyGenerator.setCheckforCycles(true); deepCacheKeyGenerator.setIncludeMethod(true); deepCacheKeyGenerator.setIncludeParameterTypes(true); deepCacheKeyGenerator.setUseReflection(false); generatorConfig = "|true|true|false"; break; case 3: deepCacheKeyGenerator.setCheckforCycles(true); deepCacheKeyGenerator.setIncludeMethod(true); deepCacheKeyGenerator.setIncludeParameterTypes(true); deepCacheKeyGenerator.setUseReflection(true); generatorConfig = "|true|true|true"; break; default: throw new IllegalStateException(); } } else { generatorConfig = "|basicKeyGenerator"; configIndex = 4; } TASK_PICKER.setSeed(0); reflectionHelper.clearCache(); for (final String cacheName : this.cacheManager.getCacheNames()) { final Ehcache ehcache = this.cacheManager.getEhcache(cacheName); final LiveCacheStatistics statistics = ehcache.getLiveCacheStatistics(); statistics.clearStatistics(); ehcache.removeAll(); assertEquals(0, ehcache.getSize()); assertEquals(0, statistics.getCacheHitCount()); assertEquals(0, statistics.getCacheMissCount()); } //Setup state and start threads this.totalKeyCount.set(0); this.runTest = true; this.testThreadStateLatch.await(); //Sleep main thread for duration of test TimeUnit.SECONDS.sleep(duration); //Switch the test running flag and wait for threads to update the key count this.runTest = false; this.testThreadStateLatch.await(); final StringBuilder cacheStats = new StringBuilder(); cacheStats.append(this.totalKeyCount.get()).append("|").append(duration).append("|"); for (final String cacheName : cacheNames) { final Ehcache ehcache = this.cacheManager.getEhcache(cacheName); final LiveCacheStatistics statistics = ehcache.getLiveCacheStatistics(); cacheStats.append(cacheName).append("|").append(ehcache.getSize()).append("|") .append(statistics.getCacheHitCount()).append("|") .append(statistics.getCacheMissCount()).append("|"); } cacheStats.append(cacheKeyGenerator.getClass().getName()).append(generatorConfig); System.out.println(cacheStats); } } } synchronized (this.testCompleteMutex) { this.testThreadStateLatch.await(); this.testComplete = true; } threadGroupRunner.join(); }
From source file:com.esminis.server.library.service.server.installpackage.InstallerPackage.java
private void stopServer(Context context, ServerControl serverControl) { final CyclicBarrier barrier = new CyclicBarrier(2); final BroadcastReceiver receiver = new BroadcastReceiver() { @Override//from ww w .j a v a 2s .c o m public void onReceive(Context context, Intent intent) { if (intent.getAction() == null || !intent.getAction().equals(MainActivity.getIntentActionServerStatus(context))) { return; } final Bundle extras = intent.getExtras(); if (extras == null || extras.containsKey("errorLine") || extras.getBoolean("running")) { return; } try { barrier.await(); } catch (InterruptedException | BrokenBarrierException ignored) { } } }; context.registerReceiver(receiver, new IntentFilter(MainActivity.getIntentActionServerStatus(context))); preferences.set(context, Preferences.SERVER_STARTED, false); serverControl.requestStop(null); try { barrier.await(); } catch (InterruptedException | BrokenBarrierException ignored) { } context.unregisterReceiver(receiver); }
From source file:hr.fer.zemris.vhdllab.platform.ui.command.DevFloodWithCompliationRequestsCommand.java
private void floodWithCompilationRequests(final Integer fileId, final String name) { String input = JOptionPane.showInputDialog("How many?", "30"); int floodCount = Integer.parseInt(input); final List<String> results = Collections.synchronizedList(new ArrayList<String>(floodCount)); final CyclicBarrier barrier = new CyclicBarrier(floodCount); List<Thread> threads = new ArrayList<Thread>(floodCount); long start = System.currentTimeMillis(); for (int i = 0; i < floodCount; i++) { Thread thread = new Thread(new Runnable() { @SuppressWarnings("synthetic-access") @Override//from ww w .j av a2 s .c o m public void run() { try { barrier.await(); } catch (Exception e) { throw new UnhandledException(e); } logger.info("sending at: " + System.currentTimeMillis()); List<CompilationMessage> messages; try { messages = simulator.compile(fileId); } catch (SimulatorTimeoutException e) { String message = localizationSource.getMessage("simulator.compile.timout", new Object[] { name }); messages = Collections.singletonList(new CompilationMessage(message)); } catch (NoAvailableProcessException e) { String message = localizationSource.getMessage("simulator.compile.no.processes", new Object[] { name }); messages = Collections.singletonList(new CompilationMessage(message)); } if (messages.isEmpty()) { results.add("Successful"); } else { results.add(messages.get(0).getText()); } } }); thread.start(); threads.add(thread); } logger.info("waiting for threads to complete..."); for (Thread thread : threads) { try { thread.join(); } catch (InterruptedException e) { throw new UnhandledException(e); } } long end = System.currentTimeMillis(); logger.info("ended in " + (end - start) + " ms"); showResults(results); }
From source file:de.hybris.platform.test.HJMPOptimisticConcurrencyPerformanceTest.java
private void doTestMissingUpdateProblem() throws JaloBusinessException, InterruptedException { final Media m = MediaManager.getInstance().createMedia("codeBefore"); try {// ww w.jav a2 s . c o m m.setMime("mimeBefore"); m.setDescription("descriptionBefore"); final CyclicBarrier txStartJoinPoint = new CyclicBarrier(2); final AtomicReference<Throwable> tx1Error = new AtomicReference<Throwable>(); final AtomicReference<Throwable> tx2Error = new AtomicReference<Throwable>(); final Thread[] threads = createTxThreads(// new TxRunnable() { @Override public void run() throws Exception { txStartJoinPoint.await(10, TimeUnit.SECONDS); // wait for other tx to begin assertEquals("codeBefore", m.getCode()); txStartJoinPoint.await(10, TimeUnit.SECONDS); // wait for other tx to have read same version m.setMime("tx1Mime"); m.setCode("tx1Code"); } }, // new TxRunnable() { @Override public void run() throws Exception { txStartJoinPoint.await(10, TimeUnit.SECONDS); // wait for other tx assertEquals("codeBefore", m.getCode()); txStartJoinPoint.await(10, TimeUnit.SECONDS); // wait for other tx to have read same version m.setMime("tx2Mime"); m.setDescription("tx2Description"); } }, tx1Error, tx2Error); threads[0].start(); threads[1].start(); threads[0].join(50 * 1000); threads[1].join(50 * 1000); assertFalse(threads[0].isAlive()); assertFalse(threads[1].isAlive()); if (isConcurrentModificationCheckEnabled()) { assertEquals("missing update from tx1", "tx1Code", m.getCode()); assertEquals("missing update from tx1", "tx1Mime", m.getMime()); assertEquals("unexpected update from tx2", "descriptionBefore", m.getDescription()); assertNull("unexpected error from tx1", tx1Error.get()); assertNotNull("expected error from tx2", tx2Error.get()); } else { assertNull("unexpected error from tx1", tx1Error.get()); assertNull("unexpected error from tx2", tx2Error.get()); assertEquals("missing update from tx1", "tx1Code", m.getCode()); assertEquals("missing update from tx2", "tx2Description", m.getDescription()); assertEquals("missing update from tx2", "tx2Mime", m.getMime()); } } finally { m.remove(); } }
From source file:jetbrains.exodus.gc.GarbageCollectorTestInMemory.java
@Test public void testTextIndexLikeWithDeletionsAndConcurrentReading() throws InterruptedException, BrokenBarrierException { final long started = System.currentTimeMillis(); prepare();/*from ww w .ja va 2 s. c o m*/ final Transaction txn = env.beginTransaction(); final Store store = env.openStore("store", getStoreConfig(false), txn); final Store storeDups = env.openStore("storeDups", getStoreConfig(true), txn); txn.commit(); final Throwable[] throwable = { null }; final JobProcessor[] processors = new JobProcessor[10]; for (int i = 0; i < processors.length; ++i) { processors[i] = ThreadJobProcessorPool.getOrCreateJobProcessor("test processor" + i); processors[i].start(); } final CyclicBarrier barrier = new CyclicBarrier(processors.length + 1); processors[0].queue(new Job() { @Override protected void execute() throws Throwable { barrier.await(); try { while (System.currentTimeMillis() - started < TEST_DURATION) { env.executeInTransaction(new TransactionalExecutable() { @Override public void execute(@NotNull final Transaction txn) { int randomInt = rnd.nextInt() & 0x3fffffff; final int count = 4 + (randomInt) & 0x1f; for (int j = 0; j < count; randomInt += ++j) { final int intKey = randomInt & 0x3fff; final ArrayByteIterable key = IntegerBinding.intToCompressedEntry(intKey); final int valueLength = 50 + (randomInt % 100); store.put(txn, key, new ArrayByteIterable(new byte[valueLength])); storeDups.put(txn, key, IntegerBinding.intToEntry(randomInt % 32)); } randomInt = (randomInt * randomInt) & 0x3fffffff; for (int j = 0; j < count; randomInt += ++j) { final int intKey = randomInt & 0x3fff; final ArrayByteIterable key = IntegerBinding.intToCompressedEntry(intKey); store.delete(txn, key); try (Cursor cursor = storeDups.openCursor(txn)) { if (cursor.getSearchBoth(key, IntegerBinding.intToEntry(randomInt % 32))) { cursor.deleteCurrent(); } } } } }); Thread.sleep(0); } } catch (Throwable t) { throwable[0] = t; } } }); for (int i = 1; i < processors.length; ++i) { processors[i].queue(new Job() { @Override protected void execute() throws Throwable { try { barrier.await(); while (System.currentTimeMillis() - started < TEST_DURATION) { int randomInt = rnd.nextInt() & 0x3fffffff; for (int j = 0; j < 100; randomInt += ++j) { final int intKey = randomInt & 0x3fff; final ArrayByteIterable key = IntegerBinding.intToCompressedEntry(intKey); getAutoCommit(store, key); getAutoCommit(storeDups, key); Thread.sleep(0); } Thread.sleep(50); } } catch (Throwable t) { throwable[0] = t; } } }); } barrier.await(); for (final JobProcessor processor : processors) { processor.finish(); } final Throwable t = throwable[0]; if (t != null) { memory.dump(new File(System.getProperty("user.home"), "dump")); logging.error("User code exception: ", t); Assert.assertTrue(false); } }