List of usage examples for java.util.concurrent Semaphore acquire
public void acquire() throws InterruptedException
From source file:org.jahia.services.render.filter.cache.AclCacheKeyPartGenerator.java
private Element generateCacheEntry(final String cacheKey, CacheEntryNotFoundCallback callback) throws RepositoryException { Element element = null;/* w ww . j a v a 2s . c o m*/ Semaphore semaphore = processings.get(cacheKey); if (semaphore == null) { semaphore = new Semaphore(1); processings.putIfAbsent(cacheKey, semaphore); } try { semaphore.acquire(); element = cache.get(cacheKey); if (element != null) { return element; } logger.debug("Getting ACL for {}", cacheKey); long l = System.currentTimeMillis(); element = new Element(cacheKey, callback.generateCacheEntry()); element.setEternal(true); cache.put(element); logger.debug("Getting ACL for {} took {} ms", cacheKey, System.currentTimeMillis() - l); } catch (InterruptedException e) { logger.debug(e.getMessage(), e); Thread.currentThread().interrupt(); } finally { semaphore.release(); } return element; }
From source file:org.apache.servicemix.nmr.core.ChannelImpl.java
/** * Synchronously send the exchange//from w w w .ja v a 2 s.c om * * @param exchange the exchange to send * @param timeout time to wait in milliseconds * @return <code>true</code> if the exchange has been processed succesfully */ public boolean sendSync(Exchange exchange, long timeout) { InternalExchange e = (InternalExchange) exchange; Semaphore lock = e.getRole() == Role.Consumer ? e.getConsumerLock(true) : e.getProviderLock(true); dispatch(e); Thread thread = Thread.currentThread(); String original = thread.getName(); try { if (timeout > 0) { if (!lock.tryAcquire(timeout, TimeUnit.MILLISECONDS)) { throw new TimeoutException(); } } else { thread.setName(original + " (waiting for exchange " + exchange.getId() + ")"); lock.acquire(); } e.setRole(e.getRole() == Role.Consumer ? Role.Provider : Role.Consumer); } catch (InterruptedException ex) { exchange.setError(ex); for (ExchangeListener l : nmr.getListenerRegistry().getListeners(ExchangeListener.class)) { l.exchangeFailed(exchange); } return false; } catch (TimeoutException ex) { exchange.setError(new AbortedException(ex)); for (ExchangeListener l : nmr.getListenerRegistry().getListeners(ExchangeListener.class)) { l.exchangeFailed(exchange); } return false; } finally { thread.setName(original); } return true; }
From source file:com.thoughtworks.go.server.service.BackupServiceIntegrationTest.java
@Test public void shouldReturnIfBackupIsInProgress() throws InterruptedException { final Semaphore waitForBackupToBegin = new Semaphore(1); final Semaphore waitForAssertion_whichHasToHappen_whileBackupIsRunning = new Semaphore(1); Database databaseStrategyMock = mock(Database.class); doAnswer((Answer<Object>) invocationOnMock -> { waitForBackupToBegin.release();//from w ww .ja va 2 s . c o m waitForAssertion_whichHasToHappen_whileBackupIsRunning.acquire(); return null; }).when(databaseStrategyMock).backup(any(File.class)); final BackupService backupService = new BackupService(artifactsDirHolder, goConfigService, new TimeProvider(), backupInfoRepository, systemEnvironment, configRepository, databaseStrategyMock, null); waitForBackupToBegin.acquire(); Thread thd = new Thread(() -> backupService.startBackup(admin)); thd.start(); waitForAssertion_whichHasToHappen_whileBackupIsRunning.acquire(); waitForBackupToBegin.acquire(); assertThat(backupService.isBackingUp(), is(true)); waitForAssertion_whichHasToHappen_whileBackupIsRunning.release(); thd.join(); }
From source file:com.netflix.curator.framework.recipes.locks.TestInterProcessMutexBase.java
@Test public void testReentrantSingleLock() throws Exception { final int THREAD_QTY = 10; CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start();//from w ww . j ava 2 s . co m try { final AtomicBoolean hasLock = new AtomicBoolean(false); final AtomicBoolean isFirst = new AtomicBoolean(true); final Semaphore semaphore = new Semaphore(1); final InterProcessLock mutex = makeLock(client); List<Future<Object>> threads = Lists.newArrayList(); ExecutorService service = Executors.newCachedThreadPool(); for (int i = 0; i < THREAD_QTY; ++i) { Future<Object> t = service.submit(new Callable<Object>() { @Override public Object call() throws Exception { semaphore.acquire(); mutex.acquire(); Assert.assertTrue(hasLock.compareAndSet(false, true)); try { if (isFirst.compareAndSet(true, false)) { semaphore.release(THREAD_QTY - 1); while (semaphore.availablePermits() > 0) { Thread.sleep(100); } } else { Thread.sleep(100); } } finally { mutex.release(); hasLock.set(false); } return null; } }); threads.add(t); } for (Future<Object> t : threads) { t.get(); } } finally { client.close(); } }
From source file:org.apache.flume.client.avro.TestReliableSpoolingFileEventReader.java
@Test public void testConsumeFileRandomlyNewFile() throws Exception { // Atomic moves are not supported in Windows. if (SystemUtils.IS_OS_WINDOWS) { return;//w w w . j a v a 2s . c om } final ReliableEventReader reader = new ReliableSpoolingFileEventReader.Builder().spoolDirectory(WORK_DIR) .consumeOrder(ConsumeOrder.RANDOM).build(); File fileName = new File(WORK_DIR, "new-file"); FileUtils.write(fileName, "New file created in the end. Shoud be read randomly.\n"); Set<String> expected = Sets.newHashSet(); int totalFiles = WORK_DIR.listFiles().length; final Set<String> actual = Sets.newHashSet(); ExecutorService executor = Executors.newSingleThreadExecutor(); final Semaphore semaphore1 = new Semaphore(0); final Semaphore semaphore2 = new Semaphore(0); Future<Void> wait = executor.submit(new Callable<Void>() { @Override public Void call() throws Exception { readEventsForFilesInDir(WORK_DIR, reader, actual, semaphore1, semaphore2); return null; } }); semaphore1.acquire(); File finalFile = new File(WORK_DIR, "t-file"); FileUtils.write(finalFile, "Last file"); semaphore2.release(); wait.get(); int listFilesCount = ((ReliableSpoolingFileEventReader) reader).getListFilesCount(); finalFile.delete(); createExpectedFromFilesInSetup(expected); expected.add(""); expected.add("New file created in the end. Shoud be read randomly."); expected.add("Last file"); Assert.assertTrue(listFilesCount < (totalFiles + 2)); Assert.assertEquals(expected, actual); }
From source file:com.impetus.ankush.common.framework.ClusterPreValidator.java
public Map validate(final Map params) { final LinkedHashMap result = new LinkedHashMap(); if (notContainsKey(params, "nodePorts", result)) { return result; }/* w w w .java 2 s .co m*/ if (params.containsKey(Constant.Keys.CLUSTERID)) { // Get cluster manager GenericManager<Cluster, Long> clusterManager = AppStoreWrapper.getManager(Constant.Manager.CLUSTER, Cluster.class); // get cluster id string String clusterIdStr = (String) params.get(Constant.Keys.CLUSTERID); // convert cluster id string into long value. Long clusterId = ParserUtil.getLongValue(clusterIdStr, 0); // Get the cluster object from database. Cluster cluster = clusterManager.get(clusterId); ClusterConfig clusterConfig = cluster.getClusterConfig(); // set username params.put(Constant.Keys.USERNAME, clusterConfig.getAuthConf().getUsername()); String pass = clusterConfig.getAuthConf().getPassword(); if (pass != null && !pass.isEmpty()) { params.put(Constant.Keys.PASSWORD, pass); } else { params.put(Constant.Keys.PRIVATEKEY, clusterConfig.getAuthConf().getPrivateKey()); } params.put(Constant.Agent.Key.AGENT_INSTALL_DIR, clusterConfig.getAgentInstallDir()); } else { if (notContainsKey(params, Constant.Keys.USERNAME, result)) { return result; } if (notContainsKey(params, Constant.Keys.PASSWORD, result)) { return result; } if (notContainsKey(params, Constant.Keys.PRIVATEKEY, result)) { return result; } } final String username = (String) params.get(Constant.Keys.USERNAME); final String password = (String) params.get(Constant.Keys.PASSWORD); final String privateKey = (String) params.get(Constant.Keys.PRIVATEKEY); final Map nodePorts = (Map) params.get("nodePorts"); Set<String> nodes = nodePorts.keySet(); final boolean authUsingPassword = (password != null && !password.isEmpty()); final String authInfo = authUsingPassword ? password : privateKey; try { final Semaphore semaphore = new Semaphore(nodes.size()); for (final String hostname : nodes) { semaphore.acquire(); AppStoreWrapper.getExecutor().execute(new Runnable() { @Override public void run() { SSHExec conn = null; LinkedHashMap<String, Object> map = new LinkedHashMap<String, Object>(); try { conn = SSHUtils.connectToNode(hostname, username, password, privateKey); map = getValidationMap(params, username, password, nodePorts, authUsingPassword, authInfo, hostname, conn); } catch (Exception e) { map.put("error", new Status("Error", "Unable to perform validations", CRITICAL)); logger.error(e.getMessage(), e); } finally { // setting overall status. map.put("status", getOverAllStatus((Collection) map.values())); // putting map against node. result.put(hostname, map); if (semaphore != null) { semaphore.release(); } if (conn != null) { conn.disconnect(); } } } }); } semaphore.acquire(nodes.size()); result.put("status", true); } catch (Exception e) { String message = e.getMessage(); if (message == null) { message = "Unable to validate nodes"; } result.put("error", Collections.singletonList(message)); result.put("status", false); logger.error(e.getMessage(), e); } return result; }
From source file:com.pinterest.pinlater.client.PinLaterQueryIssuer.java
private void issueEnqueueRequests(PinLater.ServiceIface iface) throws InterruptedException { Preconditions.checkNotNull(queueName, "Queue was not specified."); final AtomicLong queriesIssued = new AtomicLong(0); final Semaphore permits = new Semaphore(concurrency); while (numQueries == -1 || queriesIssued.get() < numQueries) { final PinLaterEnqueueRequest request = new PinLaterEnqueueRequest(); request.setQueueName(queueName); for (int i = 0; i < batchSize; i++) { PinLaterJob job = new PinLaterJob( ByteBuffer.wrap(new String("task_" + random.nextInt(Integer.MAX_VALUE)).getBytes())); job.setPriority(priority);//from www . jav a2 s. co m request.addToJobs(job); } final long startTimeNanos = System.nanoTime(); queriesIssued.incrementAndGet(); permits.acquire(); iface.enqueueJobs(REQUEST_CONTEXT, request) .respond(new Function<Try<PinLaterEnqueueResponse>, BoxedUnit>() { @Override public BoxedUnit apply(Try<PinLaterEnqueueResponse> responseTry) { permits.release(); statsLogger .requestComplete(Duration.fromNanoseconds(System.nanoTime() - startTimeNanos)); if (responseTry.isThrow()) { LOG.info("Exception for request: " + request + " : " + ((Throw) responseTry).e()); } return BoxedUnit.UNIT; } }); } permits.acquire(concurrency); LOG.info("Enqueue queries issued: " + queriesIssued); }
From source file:org.apache.bookkeeper.bookie.InterleavedLedgerStorageTest.java
@Test public void testConsistencyCheckConcurrentGC() throws Exception { final long signalDone = -1; final List<Exception> asyncErrors = new ArrayList<>(); final LinkedBlockingQueue<Long> toCompact = new LinkedBlockingQueue<>(); final Semaphore awaitingCompaction = new Semaphore(0); interleavedStorage.flush();/* w w w . ja v a2 s . c o m*/ final long lastLogId = entryLogger.getLeastUnflushedLogId(); final MutableInt counter = new MutableInt(0); entryLogger.setCheckEntryTestPoint((ledgerId, entryId, entryLogId, pos) -> { if (entryLogId < lastLogId) { if (counter.intValue() % 100 == 0) { try { toCompact.put(entryLogId); awaitingCompaction.acquire(); } catch (InterruptedException e) { asyncErrors.add(e); } } counter.increment(); } }); Thread mutator = new Thread(() -> { EntryLogCompactor compactor = new EntryLogCompactor(conf, entryLogger, interleavedStorage, entryLogger::removeEntryLog); while (true) { Long next = null; try { next = toCompact.take(); if (next == null || next == signalDone) { break; } compactor.compact(entryLogger.getEntryLogMetadata(next)); } catch (BufferedChannelBase.BufferedChannelClosedException e) { // next was already removed, ignore } catch (Exception e) { asyncErrors.add(e); break; } finally { if (next != null) { awaitingCompaction.release(); } } } }); mutator.start(); List<LedgerStorage.DetectedInconsistency> inconsistencies = interleavedStorage .localConsistencyCheck(Optional.empty()); for (LedgerStorage.DetectedInconsistency e : inconsistencies) { LOG.error("Found: {}", e); } Assert.assertEquals(0, inconsistencies.size()); toCompact.offer(signalDone); mutator.join(); for (Exception e : asyncErrors) { throw e; } if (!conf.isEntryLogPerLedgerEnabled()) { Assert.assertNotEquals(0, statsProvider.getCounter(BOOKIE_SCOPE + "." + STORAGE_SCRUB_PAGE_RETRIES).get().longValue()); } }
From source file:org.apache.geode.internal.net.SSLSocketIntegrationTest.java
@Test public void configureClientSSLSocketCanTimeOut() throws Exception { final Semaphore serverCoordination = new Semaphore(0); // configure a non-SSL server socket. We will connect // a client SSL socket to it and demonstrate that the // handshake times out final ServerSocket serverSocket = new ServerSocket(); serverSocket.bind(new InetSocketAddress(SocketCreator.getLocalHost(), 0)); Thread serverThread = new Thread() { public void run() { serverCoordination.release(); try (Socket clientSocket = serverSocket.accept()) { System.out.println("server thread accepted a connection"); serverCoordination.acquire(); } catch (Exception e) { System.err.println("accept failed"); e.printStackTrace();//from www. j a v a2 s.c o m } try { serverSocket.close(); } catch (IOException e) { // ignored } System.out.println("server thread is exiting"); } }; serverThread.setName("SocketCreatorJUnitTest serverSocket thread"); serverThread.setDaemon(true); serverThread.start(); serverCoordination.acquire(); SocketCreator socketCreator = SocketCreatorFactory .getSocketCreatorForComponent(SecurableCommunicationChannel.SERVER); int serverSocketPort = serverSocket.getLocalPort(); try { Awaitility.await("connect to server socket").atMost(30, TimeUnit.SECONDS).until(() -> { try { Socket clientSocket = socketCreator.connectForClient( SocketCreator.getLocalHost().getHostAddress(), serverSocketPort, 2000); clientSocket.close(); System.err.println( "client successfully connected to server but should not have been able to do so"); return false; } catch (SocketTimeoutException e) { // we need to verify that this timed out in the handshake // code System.out.println("client connect attempt timed out - checking stack trace"); StackTraceElement[] trace = e.getStackTrace(); for (StackTraceElement element : trace) { if (element.getMethodName().equals("configureClientSSLSocket")) { System.out.println("client connect attempt timed out in the appropriate method"); return true; } } // it wasn't in the configuration method so we need to try again } catch (IOException e) { // server socket may not be in accept() yet, causing a connection-refused // exception } return false; }); } finally { serverCoordination.release(); } }
From source file:com.thoughtworks.go.server.service.BuildAssignmentServiceIntegrationTest.java
@Test public void shouldNotReloadScheduledJobPlansWhenAgentWorkAssignmentIsInProgress() throws Exception { fixture.createPipelineWithFirstStageScheduled(); Pipeline pipeline = pipelineDao.mostRecentPipeline(fixture.pipelineName); JobInstance job = pipeline.getFirstStage().getJobInstances().first(); final JobInstanceService mockJobInstanceService = mock(JobInstanceService.class); final Pipeline pipeline1 = pipeline; final Semaphore sem = new Semaphore(1); sem.acquire(); when(mockJobInstanceService.orderedScheduledBuilds()) .thenReturn(jobInstanceService.orderedScheduledBuilds()); when(mockJobInstanceService.buildByIdWithTransitions(job.getId())) .thenReturn(jobInstanceService.buildByIdWithTransitions(job.getId())); ScheduledPipelineLoader scheduledPipelineLoader = new ScheduledPipelineLoader(null, null, null, null, null, null, null, null) {// w w w. j av a 2 s .c om @Override public Pipeline pipelineWithPasswordAwareBuildCauseByBuildId(long buildId) { sem.release(); sleepQuietly(1000); verify(mockJobInstanceService, times(1)).orderedScheduledBuilds(); return pipeline1; } }; final BuildAssignmentService buildAssignmentServiceUnderTest = new BuildAssignmentService(goConfigService, mockJobInstanceService, scheduleService, agentService, environmentConfigService, transactionTemplate, scheduledPipelineLoader, pipelineService, builderFactory, maintenanceModeService, elasticAgentPluginService, systemEnvironment, secretParamResolver, jobStatusTopic, consoleService); final Throwable[] fromThread = new Throwable[1]; buildAssignmentServiceUnderTest.onTimer(); Thread assigner = new Thread(() -> { try { final AgentConfig agentConfig = AgentMother.localAgentWithResources("some-other-resource"); buildAssignmentServiceUnderTest.assignWorkToAgent(agent(agentConfig)); } catch (Throwable e) { e.printStackTrace(); fromThread[0] = e; } finally { } }, "assignmentThread"); assigner.start(); sem.acquire(); buildAssignmentServiceUnderTest.onTimer(); assigner.join(); assertThat(fromThread[0], is(nullValue())); }