List of usage examples for java.util.concurrent Semaphore Semaphore
public Semaphore(int permits)
From source file:org.knime.al.nodes.score.novelty.localnoveltyscorer.LocalNoveltyScorer.java
public double[] calculateNoveltyScores() throws Exception { final ThreadPool pool = KNIMEConstants.GLOBAL_THREAD_POOL; final int procCount = (int) (Runtime.getRuntime().availableProcessors() * (2.0 / 3)); final Semaphore semaphore = new Semaphore(procCount); final int numTestSamples = m_globalKernelMatrix.getColumnDimension(); final NoveltyScoreCalculationCallable[] nct = new NoveltyScoreCalculationCallable[numTestSamples]; for (int i = 0; i < numTestSamples; i++) { nct[i] = new NoveltyScoreCalculationCallable(i, semaphore, m_numNeighbors, m_trainingKernelMatrix, m_globalKernelMatrix, m_labels, m_normalize); }//from w w w. java2s . c om final Future<?>[] scores = new Future<?>[numTestSamples]; final KNIMETimer timer = KNIMETimer.getInstance(); final TimerTask timerTask = new TimerTask() { @Override public void run() { try { m_exec.checkCanceled(); } catch (final CanceledExecutionException ce) { for (int i = 0; i < scores.length; i++) { if (scores[i] != null) { scores[i].cancel(true); } } super.cancel(); } } }; timer.scheduleAtFixedRate(timerTask, 0, 3000); double progCounter = 0; for (int i = 0; i < numTestSamples; i++) { try { m_exec.checkCanceled(); } catch (final Exception e) { for (int j = 0; j < i; j++) { if (scores[j] != null) { scores[j].cancel(true); } } timerTask.cancel(); throw e; } semaphore.acquire(); scores[i] = pool.enqueue(nct[i]); m_exec.setProgress(progCounter / (2 * numTestSamples), "Local novelty score calculation started (" + i + "/" + numTestSamples + ")"); progCounter += 1; } final double[] result = new double[numTestSamples]; for (int i = 0; i < numTestSamples; i++) { semaphore.acquire(); try { m_exec.checkCanceled(); result[i] = (Double) scores[i].get(); nct[i].ok(); } catch (final Exception e) { for (int j = 0; j < scores.length; j++) { scores[j].cancel(true); } timerTask.cancel(); throw e; } m_exec.setProgress(progCounter / (2 * numTestSamples), "Local novelty score calculated (" + i + "/" + numTestSamples + ")"); progCounter += 1; semaphore.release(); } timerTask.cancel(); return result; }
From source file:com.yahoo.omid.tso.persistence.BookKeeperStateBuilder.java
BookKeeperStateBuilder(TSOServerConfig config) { this.timestampOracle = new TimestampOracle(); this.config = config; this.throttleReads = new Semaphore(PARALLEL_READS); }
From source file:de.zazaz.iot.bosch.indego.ifttt.IftttIndegoAdapter.java
/** * This starts the adapter./* ww w .j a v a 2s . c om*/ */ public synchronized void startup() { if (threadWorker != null) { throw new IllegalStateException("The adapter is already started"); } flagShutdown.set(false); semThreadWaker = new Semaphore(0); threadWorker = new Thread(new Runnable() { @Override public void run() { runOuter(); } }); LOG.debug("Starting worker thread"); try { threadWorker.start(); LOG.debug("Worker thread started"); } catch (RuntimeException ex) { LOG.error("Failed to start worker thread", ex); threadWorker = null; throw ex; } }
From source file:org.apache.asterix.experiment.client.SocketTweetGenerator.java
public void start() throws Exception { final Semaphore sem = new Semaphore((receiverAddresses.size() - 1) * -1); int i = 0;/*from ww w .ja v a2s. c o m*/ for (Pair<String, Integer> address : receiverAddresses) { threadPool.submit(new DataGenerator(mode, sem, address.getLeft(), address.getRight(), i + partitionRangeStart, dataGenDuration, queryGenDuration, nDataIntervals, startDataInterval, orchHost, orchPort, openStreetMapFilePath, locationSampleInterval, recordCountPerBatchDuringIngestionOnly, recordCountPerBatchDuringQuery, dataGenSleepTimeDuringIngestionOnly, dataGenSleepTimeDuringQuery)); ++i; } sem.acquire(); }
From source file:org.jboss.pnc.jenkinsbuilddriver.test.JenkinsDriverRemoteTest.java
@Test //@Ignore("To be fixed by NCL-554") public void startJenkinsJobTestCase() throws Exception { BuildConfigurationAudited pbc = getBuildConfiguration(); RunningEnvironment runningEnvironment = getRunningEnvironment(); final Semaphore mutex = new Semaphore(1); ObjectWrapper<Boolean> completed = new ObjectWrapper<>(false); ObjectWrapper<BuildDriverResult> resultWrapper = new ObjectWrapper<>(); ObjectWrapper<Long> buildStarted = new ObjectWrapper<>(); ObjectWrapper<Long> buildTook = new ObjectWrapper<>(); class BuildTask { CompletedBuild buildJobDetails;/*from w w w .jav a 2 s. c o m*/ } final BuildTask buildTask = new BuildTask(); Consumer<CompletedBuild> onComplete = (completedBuild) -> { buildTask.buildJobDetails = completedBuild; completed.set(true); buildTook.set(System.currentTimeMillis() - buildStarted.get()); log.info("Received build completed in " + buildTook.get() + "ms."); try { resultWrapper.set(completedBuild.getBuildResult()); } catch (BuildDriverException e) { throw new AssertionError("Cannot get build result.", e); } mutex.release(); }; Consumer<Throwable> onError = (e) -> { throw new AssertionError(e); }; mutex.acquire(); RunningBuild runningBuild = jenkinsBuildDriver.startProjectBuild(mock(BuildExecution.class), pbc, runningEnvironment); buildStarted.set(System.currentTimeMillis()); runningBuild.monitor(onComplete, onError); mutex.tryAcquire(60, TimeUnit.SECONDS); // wait for callback to release Assert.assertTrue("There was no complete callback.", completed.get()); Assert.assertNotNull(buildTask.buildJobDetails); long minBuildTime = 5000; Assert.assertTrue( "Received build completed in " + buildTook.get() + " while expected >" + minBuildTime + ".", buildTook.get() >= minBuildTime); BuildDriverResult buildDriverResult = resultWrapper.get(); Assert.assertEquals(BuildDriverStatus.SUCCESS, buildDriverResult.getBuildDriverStatus()); Assert.assertTrue("Incomplete build log.", buildDriverResult.getBuildLog().contains("Building in workspace")); Assert.assertTrue("Incomplete build log.", buildDriverResult.getBuildLog().contains("Finished: SUCCESS")); Assert.assertTrue("There was no complete callback.", completed.get()); }
From source file:org.telegram.ui.ChannelEditTypeActivity.java
@SuppressWarnings("unchecked") @Override//from w w w . j a va2 s . c o m public boolean onFragmentCreate() { currentChat = MessagesController.getInstance().getChat(chatId); if (currentChat == null) { final Semaphore semaphore = new Semaphore(0); MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() { @Override public void run() { currentChat = MessagesStorage.getInstance().getChat(chatId); semaphore.release(); } }); try { semaphore.acquire(); } catch (Exception e) { FileLog.e("tmessages", e); } if (currentChat != null) { MessagesController.getInstance().putChat(currentChat, true); } else { return false; } } isPrivate = currentChat.username == null || currentChat.username.length() == 0; if (isPrivate) { TLRPC.TL_channels_checkUsername req = new TLRPC.TL_channels_checkUsername(); req.username = "1"; req.channel = new TLRPC.TL_inputChannelEmpty(); ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { @Override public void run(TLObject response, final TLRPC.TL_error error) { AndroidUtilities.runOnUIThread(new Runnable() { @Override public void run() { canCreatePublic = error == null || !error.text.equals("CHANNELS_ADMIN_PUBLIC_TOO_MUCH"); if (!canCreatePublic) { loadAdminedChannels(); } } }); } }); } NotificationCenter.getInstance().addObserver(this, NotificationCenter.chatInfoDidLoaded); return super.onFragmentCreate(); }
From source file:com.codefollower.lealone.omid.tso.persistence.BookKeeperStateBuilder.java
private BookKeeperStateBuilder(TSOServerConfig config) { this.timestampOracle = new TimestampOracle(); this.config = config; this.throttleReads = new Semaphore(PARALLEL_READS); }
From source file:com.flipkart.poseidon.handlers.http.impl.HttpConnectionPool.java
/** Constructor * @param host Host Name//from w w w .j a va 2 s.com * @param port Port Name * @param secure * @param connectionTimeout * @param operationTimeout * @param maxConnections * @param processQueueSize * @param timeToLiveInSecs */ protected HttpConnectionPool(final String name, String host, Integer port, Boolean secure, Integer connectionTimeout, Integer operationTimeout, Integer maxConnections, Integer processQueueSize, Integer timeToLiveInSecs) { this.name = name; this.host = host; this.port = port; this.secure = secure; this.headers = new HashMap<String, String>(); this.processQueue = new Semaphore(processQueueSize + maxConnections); if (timeToLiveInSecs != null) { this.timeToLiveInSecs = timeToLiveInSecs; } this.requestGzipEnabled = false; this.responseGzipEnabled = false; // create scheme SchemeRegistry schemeRegistry = new SchemeRegistry(); if (this.secure) { schemeRegistry.register(new Scheme("https", port, SSLSocketFactory.getSocketFactory())); } else { schemeRegistry.register(new Scheme("http", port, PlainSocketFactory.getSocketFactory())); } // create connection manager PoolingClientConnectionManager cm; if (this.timeToLiveInSecs > 0) { cm = new PoolingClientConnectionManager(schemeRegistry, this.timeToLiveInSecs, TimeUnit.SECONDS); } else { cm = new PoolingClientConnectionManager(schemeRegistry); } // Max pool size cm.setMaxTotal(maxConnections); // Increase default max connection per route to 20 cm.setDefaultMaxPerRoute(maxConnections); // Increase max connections for host:port HttpHost httpHost = new HttpHost(host, port); cm.setMaxPerRoute(new HttpRoute(httpHost), maxConnections); // set timeouts HttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, connectionTimeout); HttpConnectionParams.setSoTimeout(httpParams, operationTimeout); // create client pool this.client = new DefaultHttpClient(cm, httpParams); // policies (cookie) this.client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.IGNORE_COOKIES); // adding gzip support for http client addGzipHeaderInRequestResponse(); }
From source file:org.artifactory.repo.service.ImportJob.java
public ImportJob() { int maxParallelImports = Math.max(ConstantValues.importMaxParallelRepos.getInt(), 1); parallelImportsGate = new Semaphore(maxParallelImports); callablesFactory = new ImportHandlerCallablesFactory(parallelImportsGate, TaskCallback.currentTaskToken()); taskExecutor = new CachedThreadPoolTaskExecutor(); repositoryService = InternalContextHelper.get().beanForType(InternalRepositoryService.class); }
From source file:com.netflix.curator.framework.recipes.barriers.TestDistributedDoubleBarrier.java
@Test public void testOverSubscribed() throws Exception { final Timing timing = new Timing(); final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); ExecutorService service = Executors.newCachedThreadPool(); ExecutorCompletionService<Void> completionService = new ExecutorCompletionService<Void>(service); try {/* w w w. ja v a 2 s.c o m*/ client.start(); final Semaphore semaphore = new Semaphore(0); final CountDownLatch latch = new CountDownLatch(1); for (int i = 0; i < (QTY + 1); ++i) { completionService.submit(new Callable<Void>() { @Override public Void call() throws Exception { DistributedDoubleBarrier barrier = new DistributedDoubleBarrier(client, "/barrier", QTY) { @Override protected List<String> getChildrenForEntering() throws Exception { semaphore.release(); Assert.assertTrue(timing.awaitLatch(latch)); return super.getChildrenForEntering(); } }; Assert.assertTrue(barrier.enter(timing.seconds(), TimeUnit.SECONDS)); Assert.assertTrue(barrier.leave(timing.seconds(), TimeUnit.SECONDS)); return null; } }); } Assert.assertTrue(semaphore.tryAcquire(QTY + 1, timing.seconds(), TimeUnit.SECONDS)); // wait until all QTY+1 barriers are trying to enter latch.countDown(); for (int i = 0; i < (QTY + 1); ++i) { completionService.take().get(); // to check for assertions } } finally { service.shutdown(); IOUtils.closeQuietly(client); } }