List of usage examples for java.util.concurrent Semaphore acquire
public void acquire() throws InterruptedException
From source file:io.kodokojo.bdd.stage.cluster.ClusterApplicationGiven.java
private void startKodokojo() { String keystorePath = System.getProperty("javax.net.ssl.keyStore", null); if (StringUtils.isBlank(keystorePath)) { String keystorePathDefined = new File("").getAbsolutePath() + "/src/test/resources/keystore/mykeystore.jks"; System.out.println(keystorePathDefined); System.setProperty("javax.net.ssl.keyStore", keystorePathDefined); }//from w ww .j av a 2 s . c o m BrickUrlFactory brickUrlFactory = new MarathonBrickUrlFactory(marathonUrl); System.setProperty("javax.net.ssl.keyStorePassword", "password"); System.setProperty("security.ssl.rootCa.ks.alias", "rootcafake"); System.setProperty("security.ssl.rootCa.ks.password", "password"); System.setProperty("application.dns.domain", "kodokojo.io"); System.setProperty("redis.host", redisService.getHost()); System.setProperty("redis.port", "" + redisService.getPort()); System.setProperty("marathon.url", "http://" + dockerTestSupport.getServerIp() + ":8080"); System.setProperty("lb.defaultIp", dockerTestSupport.getServerIp()); System.setProperty("application.dns.domain", "kodokojo.dev"); LOGGER.debug("redis.port: {}", System.getProperty("redis.port")); injector = Guice.createInjector(new PropertyModule(new String[] {}), new RedisModule(), new SecurityModule(), new ServiceModule(), new ActorModule(), new AwsModule(), new EmailSenderModule(), new UserEndpointModule(), new ProjectEndpointModule(), new AbstractModule() { @Override protected void configure() { } @Provides @Singleton ServiceLocator provideServiceLocator(MarathonConfig marathonConfig) { return new MarathonServiceLocator(marathonConfig.url()); } @Provides @Singleton ConfigurationStore provideConfigurationStore(MarathonConfig marathonConfig) { return new MarathonConfigurationStore(marathonConfig.url()); } @Provides @Singleton BrickManager provideBrickManager(MarathonConfig marathonConfig, BrickConfigurerProvider brickConfigurerProvider, ProjectStore projectStore, ApplicationConfig applicationConfig, BrickUrlFactory brickUrlFactory) { MarathonServiceLocator marathonServiceLocator = new MarathonServiceLocator( marathonConfig.url()); return new MarathonBrickManager(marathonConfig.url(), marathonServiceLocator, brickConfigurerProvider, projectStore, false, applicationConfig.domain(), brickUrlFactory); } }); Launcher.INJECTOR = injector; userStore = injector.getInstance(UserStore.class); projectStore = injector.getInstance(ProjectStore.class); entityStore = injector.getInstance(EntityStore.class); //BrickFactory brickFactory = injector.getInstance(BrickFactory.class); restEntryPointHost = "localhost"; restEntryPointPort = TestUtils.getEphemeralPort(); projectManager = new DefaultProjectManager(domain, injector.getInstance(ConfigurationStore.class), projectStore, injector.getInstance(BootstrapConfigurationProvider.class), new NoOpDnsManager(), new DefaultBrickConfigurerProvider(brickUrlFactory), injector.getInstance(BrickConfigurationStarter.class), brickUrlFactory); httpUserSupport = new HttpUserSupport(new OkHttpClient(), restEntryPointHost + ":" + restEntryPointPort); Set<SparkEndpoint> sparkEndpoints = new HashSet<>( injector.getInstance(Key.get(new TypeLiteral<Set<SparkEndpoint>>() { }))); Key<UserAuthenticator<SimpleCredential>> authenticatorKey = Key .get(new TypeLiteral<UserAuthenticator<SimpleCredential>>() { }); UserAuthenticator<SimpleCredential> userAuthenticator = injector.getInstance(authenticatorKey); sparkEndpoints.add(new ProjectSparkEndpoint(userAuthenticator, userStore, projectStore, projectManager, injector.getInstance(BrickFactory.class))); httpEndpoint = new HttpEndpoint(restEntryPointPort, new SimpleUserAuthenticator(userStore), sparkEndpoints); Semaphore semaphore = new Semaphore(1); try { semaphore.acquire(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } Thread t = new Thread(() -> { httpEndpoint.start(); semaphore.release(); }); t.start(); try { semaphore.acquire(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }
From source file:org.openengsb.opencit.core.projectmanager.internal.ProjectManagerImplTest.java
@Test @SuppressWarnings("unchecked") public void build_shouldSuspendPoller() throws Exception { List<CommitRef> fakeCommits = new LinkedList<CommitRef>(); fakeCommits.add(Mockito.mock(CommitRef.class)); final Semaphore eventSync = new Semaphore(0); when(workflowService.startFlow(eq("ci"), any(Map.class))).thenReturn(1L); doAnswer(new Answer<Void>() { @Override//from www . j a va2 s . c om public Void answer(InvocationOnMock invocation) throws Throwable { eventSync.acquire(); return null; } }).when(workflowService).waitForFlowToFinish(eq(1L), anyLong()); when(scmMock.update()).thenReturn(fakeCommits, (List<CommitRef>[]) null); scheduler.setPollInterval(100L); Project project = new Project("test"); project.setState(State.OK); projectManager.createProject(project); Thread.sleep(200); assertThat(scheduler.isProjectBuilding("test"), is(true)); Thread.sleep(200); verify(scmMock).update(); eventSync.release(); Thread.sleep(200); assertThat(scheduler.isProjectBuilding("test"), is(false)); assertThat(scheduler.isProjectPolling("test"), is(true)); }
From source file:org.openconcerto.erp.model.EditionFichePayeModel.java
/** * Validation des fiches selectionnes/*from www . ja va 2 s . co m*/ * * @param annee * @param idMois * @param du * @param au */ public void validationFiche(final String annee, final int idMois, final Date du, final Date au) { final Thread t = new Thread() { @Override public void run() { try { EditionFichePayeModel.this.bar.setMaximum(EditionFichePayeModel.this.vData.size() * 4 - 1); EditionFichePayeModel.this.bar.setString(null); EditionFichePayeModel.this.bar.setStringPainted(false); int tmp = 0; EditionFichePayeModel.this.bar.setValue(tmp); final SQLElement eltSal = Configuration.getInstance().getDirectory().getElement("SALARIE"); final SQLElement eltFichePaye = Configuration.getInstance().getDirectory() .getElement("FICHE_PAYE"); // On cre la fiche de paye pour chacun des salaris slectionns for (int i = 0; i < EditionFichePayeModel.this.vData.size(); i++) { Map<String, Object> m = EditionFichePayeModel.this.vData.get(i); Boolean bCreate = (Boolean) m.get("A_CREER"); if (bCreate.booleanValue()) { final int idSal = ((Number) m.get("ID_SALARIE")).intValue(); SQLRow rowSalarie = eltSal.getTable().getRow(idSal); final String salName = rowSalarie.getString("CODE") + " " + rowSalarie.getString("NOM"); final SQLRow row = eltSal.getTable().getRow(idSal); final int idFiche = row.getInt("ID_FICHE_PAYE"); // Update de la periode SQLRowValues rowVals = new SQLRowValues(eltFichePaye.getTable()); rowVals.put("ANNEE", Integer.valueOf(annee)); rowVals.put("ID_MOIS", idMois); rowVals.put("DU", du); rowVals.put("AU", au); try { rowVals.update(idFiche); } catch (SQLException e) { e.printStackTrace(); } SwingUtilities.invokeLater(new Runnable() { public void run() { EditionFichePayeModel.this.labelEtat .setText(salName + " - Mise jour de la priode"); } }); EditionFichePayeModel.this.bar.setValue(tmp++); // Visualisation Boolean bVisu = (Boolean) m.get("VISU"); boolean resume = true; if (bVisu.booleanValue()) { final Semaphore semaphore = new Semaphore(1); try { semaphore.acquire(); // on demande le smaphore final VisualisationPayeFrame frame = new VisualisationPayeFrame(semaphore); SwingUtilities.invokeLater(new Runnable() { public void run() { frame.pack(); frame.setSelectedFichePaye(idFiche); frame.setVisible(true); } }); // synchronized (this) { // try { // System.err.println("Wait "); // this.wait(); // System.err.println("WakeUp"); // // } catch (InterruptedException e) { // e.printStackTrace(); // } // } semaphore.acquire(); System.err.println("Etat --> " + frame.getAnswer()); resume = frame.getAnswer(); } catch (InterruptedException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } EditionFichePayeModel.this.bar.setValue(tmp++); // test si l'utilisateur n'a pas annul l'action if (resume) { SwingUtilities.invokeLater(new Runnable() { public void run() { EditionFichePayeModel.this.labelEtat .setText(salName + " - Validation de la fiche"); } }); // Validation de la fiche FichePayeSQLElement.validationFiche(idFiche); // Update des rubriques SQLRow rowSalNew = eltSal.getTable().getRow(idSal); final int idFicheNew = rowSalNew.getInt("ID_FICHE_PAYE"); FichePayeModel ficheModel = new FichePayeModel(idFicheNew); ficheModel.loadAllElements(); EditionFichePayeModel.this.bar.setValue(tmp++); // Impression Boolean bPrint = (Boolean) m.get("IMPRESSION"); if (bPrint.booleanValue()) { SQLRow rowFiche = eltFichePaye.getTable().getRow(idFiche); FichePayeSheet.generation(rowFiche, false); FichePayeSheet.impression(rowFiche); } EditionFichePayeModel.this.bar.setValue(tmp++); } else { SwingUtilities.invokeLater(new Runnable() { public void run() { EditionFichePayeModel.this.labelEtat .setText(salName + " - Cration annule"); } }); tmp += 2; EditionFichePayeModel.this.bar.setValue(tmp); SwingUtilities.invokeLater(new Runnable() { public void run() { String msg = "Cration annule pour " + row.getString("CODE") + " " + row.getString("NOM") + " " + row.getString("PRENOM"); JOptionPane.showMessageDialog(null, msg, "Cration des payes", JOptionPane.INFORMATION_MESSAGE); } }); } } else { tmp += 4; EditionFichePayeModel.this.bar.setValue(tmp); } } } catch (Exception e) { ExceptionHandler.handle("Erreur pendant la cration des fiches de paye", e); } // Fin de l'edition SwingUtilities.invokeLater(new Runnable() { public void run() { updateAll(); JOptionPane.showMessageDialog(null, "Cration des payes termine", "Cration paye", JOptionPane.INFORMATION_MESSAGE); } }); EditionFichePayeModel.this.labelEtat.setText("Traitement termin"); EditionFichePayeModel.this.bar.setString("Termin"); EditionFichePayeModel.this.bar.setStringPainted(true); } }; t.start(); }
From source file:edu.chalmers.dat076.moviefinder.service.MovieFileDatabaseHandlerImpl.java
@Override public void saveFile(final Path path) { Runnable r = new Runnable() { @Override/*from w w w .ja va 2s . c o m*/ @Transactional public void run() { try { TemporaryMedia temporaryMedia = new TitleParser().parseMedia(path.getFileName().toString()); TraktResponse traktData = new TraktHandler().getByTmpMedia(temporaryMedia); if (traktData != null) { if (traktData instanceof TraktMovieResponse) { Movie movie = new Movie(path.toString(), traktData); try { try { movieSemaphore.acquire(); } catch (InterruptedException ex) { } movieRepository.save(movie); } catch (DataIntegrityViolationException e) { } finally { movieSemaphore.release(); } } else { TraktEpisodeResponse epr = (TraktEpisodeResponse) traktData; Semaphore sLock = serieLock.get(epr.getShow().getTitle()); if (sLock == null) { sLock = new Semaphore(1, true); serieLock.put(epr.getShow().getTitle(), sLock); } try { sLock.acquire(); Series s = seriesRepository.findByImdbId(epr.getShow().getImdbId()); if (s == null) { TraktShowResponse sr = new TraktHandler() .getByShowName(temporaryMedia.getName()); if (sr != null) { s = new Series(sr); seriesRepository.save(s); } } if (s != null) { Episode ep = new Episode(path.toString(), traktData, s); episodeRepository.save(ep); } } catch (InterruptedException ex) { } finally { sLock.release(); } } } } finally { lock.release(); } } }; try { lock.acquire(); } catch (InterruptedException ex) { } new Thread(r).start(); }
From source file:com.thoughtworks.studios.shine.cruise.stage.details.LazyStageGraphLoaderTest.java
@Test public void shouldNotReuseTransformerAcrossConcurrentInvocations() throws InterruptedException { final StageIdentifier stageId = new StageIdentifier("pipeline-foo", 23, "stage-1", "1"); final Semaphore invocationBlocker = new Semaphore(1); final DummyStageResourceImporter realLoader = new DummyStageResourceImporter(realGraph(), stageId, invocationBlocker);// w ww .ja v a 2 s. co m final LazyStageGraphLoader loader = new LazyStageGraphLoader(realLoader, stageStorage, 2); final XSLTTransformerRegistry[] transformerRegistryUsed = new XSLTTransformerRegistry[2]; invocationBlocker.acquire(); Thread firstThd = new Thread(new Runnable() { public void run() { loader.load(stageId); invocationBlocker.release(); } }); firstThd.start(); while (invocationBlocker.getQueueLength() == 0) { Thread.sleep(10); } transformerRegistryUsed[0] = realLoader.transformerRegistry; Thread secondThd = new Thread(new Runnable() { public void run() { stageStorage.clear(); loader.load(stageId); } }); secondThd.start(); while (invocationBlocker.getQueueLength() == 1) { Thread.sleep(10); } transformerRegistryUsed[1] = realLoader.transformerRegistry; invocationBlocker.release(); firstThd.join(); secondThd.join(); assertThat(transformerRegistryUsed[0], not(sameInstance(transformerRegistryUsed[1]))); }
From source file:Main.java
public void runTest() throws Exception { ThreadPoolExecutor tp = new ThreadPoolExecutor(1, 1, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>()); tp.setRejectedExecutionHandler(// w w w .j a va 2s .co m (Runnable r, ThreadPoolExecutor executor) -> System.out.println("Task rejected: " + r)); Semaphore oneTaskDone = new Semaphore(0); tp.execute(() -> { System.out.println("Sleeping"); try { Thread.sleep(300); } catch (Exception e) { e.printStackTrace(); } System.out.println("Done sleeping"); oneTaskDone.release(); }); tp.execute(new Runnable() { @Override public void run() { System.out.println("Never happends"); } @Override public String toString() { return "Rejected Runnable"; } }); oneTaskDone.acquire(); tp.execute(() -> System.out.println("Running")); tp.shutdown(); tp.awaitTermination(100, TimeUnit.MILLISECONDS); System.out.println("Finished"); }
From source file:com.pinterest.pinlater.client.PinLaterQueryIssuer.java
private void issueDequeueAckRequests(final 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 PinLaterDequeueRequest request = new PinLaterDequeueRequest(); request.setQueueName(queueName); request.setLimit(batchSize);/*w ww . j a v a 2 s. com*/ final long startTimeNanos = System.nanoTime(); queriesIssued.incrementAndGet(); permits.acquire(); iface.dequeueJobs(REQUEST_CONTEXT, request) .flatMap(new Function<PinLaterDequeueResponse, Future<Void>>() { @Override public Future<Void> apply(PinLaterDequeueResponse response) { if (response.getJobsSize() == 0) { return Future.Void(); } PinLaterJobAckRequest jobAckRequest = new PinLaterJobAckRequest(queueName); for (String job : response.getJobs().keySet()) { if (random.nextInt(100) < dequeueSuccessPercent) { jobAckRequest.addToJobsSucceeded(new PinLaterJobAckInfo(job)); } else { jobAckRequest.addToJobsFailed(new PinLaterJobAckInfo(job)); } } return iface.ackDequeuedJobs(REQUEST_CONTEXT, jobAckRequest); } }).respond(new Function<Try<Void>, BoxedUnit>() { @Override public BoxedUnit apply(Try<Void> voidTry) { permits.release(); statsLogger .requestComplete(Duration.fromNanoseconds(System.nanoTime() - startTimeNanos)); if (voidTry.isThrow()) { LOG.info("Exception for request: " + request + " : " + ((Throw) voidTry).e()); } return BoxedUnit.UNIT; } }); } permits.acquire(concurrency); LOG.info("Dequeue/ack queries issued: " + queriesIssued); }
From source file:com.bt.aloha.collections.memory.InMemoryCollectionImpl.java
public T get(String infoId) { if (infoId == null) throw new IllegalArgumentException("Info id must not be null"); Semaphore semaphore = getSemaphores().get(infoId); if (semaphore == null) { log.debug(String.format("No info object for %s in %s, returning null ", infoId, this.getClass().getSimpleName())); return null; }// www . j a v a2s.c om // log.debug("semaphores.size: " + getSemaphores().size()); // log.debug("infos.size: " + infos.size()); // log.debug("semaphore: " + semaphore.toString()); try { semaphore.acquire(); } catch (InterruptedException e) { log.error(String.format(FAILED_TO_READ_OBJECT_MESSAGE, infoId, this.getClass().getSimpleName(), e.getMessage())); throw new CollectionAccessInterruptedException(String.format(FAILED_TO_READ_OBJECT_MESSAGE, infoId, this.getClass().getSimpleName(), e.getMessage()), e); } try { if (infos.containsKey(infoId)) { T result = (T) infos.get(infoId).cloneObject(); log.debug(String.format("Retrieved info %s with version %s", infoId, result.getVersionId())); return (T) result; } log.debug(String.format("No info object for %s in %s, returning null ", infoId, this.getClass().getSimpleName())); return null; } finally { semaphore.release(); } }
From source file:com.netflix.curator.framework.recipes.cache.TestPathChildrenCache.java
@Test public void testRebuildNode() throws Exception { PathChildrenCache cache = null;/* w w w .j ava 2 s . co m*/ CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); try { client.create().creatingParentsIfNeeded().forPath("/test/one", "one".getBytes()); final CountDownLatch latch = new CountDownLatch(1); final AtomicInteger counter = new AtomicInteger(); final Semaphore semaphore = new Semaphore(1); cache = new PathChildrenCache(client, "/test", true) { @Override void getDataAndStat(String fullPath) throws Exception { semaphore.acquire(); counter.incrementAndGet(); super.getDataAndStat(fullPath); latch.countDown(); } }; cache.start(PathChildrenCache.StartMode.BUILD_INITIAL_CACHE); latch.await(); int saveCounter = counter.get(); client.setData().forPath("/test/one", "alt".getBytes()); cache.rebuildNode("/test/one"); Assert.assertEquals(cache.getCurrentData("/test/one").getData(), "alt".getBytes()); Assert.assertEquals(saveCounter, counter.get()); semaphore.release(1000); } finally { IOUtils.closeQuietly(cache); IOUtils.closeQuietly(client); } }
From source file:com.netflix.curator.ensemble.exhibitor.TestExhibitorEnsembleProvider.java
@Test public void testExhibitorFailures() throws Exception { final AtomicReference<String> backupConnectionString = new AtomicReference<String>("backup1:1"); final AtomicReference<String> connectionString = new AtomicReference<String>( "count=1&port=2&server0=localhost"); Exhibitors exhibitors = new Exhibitors(Lists.newArrayList("foo", "bar"), 1000, new Exhibitors.BackupConnectionStringProvider() { @Override//from ww w . j av a 2 s.c o m public String getBackupConnectionString() { return backupConnectionString.get(); } }); ExhibitorRestClient mockRestClient = new ExhibitorRestClient() { @Override public String getRaw(String hostname, int port, String uriPath, String mimeType) throws Exception { String localConnectionString = connectionString.get(); if (localConnectionString == null) { throw new IOException(); } return localConnectionString; } }; final Semaphore semaphore = new Semaphore(0); ExhibitorEnsembleProvider provider = new ExhibitorEnsembleProvider(exhibitors, mockRestClient, "/foo", 10, new RetryOneTime(1)) { @Override protected void poll() { super.poll(); semaphore.release(); } }; provider.pollForInitialEnsemble(); try { provider.start(); Assert.assertEquals(provider.getConnectionString(), "localhost:2"); connectionString.set(null); semaphore.drainPermits(); semaphore.acquire(); // wait for next poll Assert.assertEquals(provider.getConnectionString(), "backup1:1"); backupConnectionString.set("backup2:2"); semaphore.drainPermits(); semaphore.acquire(); // wait for next poll Assert.assertEquals(provider.getConnectionString(), "backup2:2"); connectionString.set("count=1&port=3&server0=localhost3"); semaphore.drainPermits(); semaphore.acquire(); // wait for next poll Assert.assertEquals(provider.getConnectionString(), "localhost3:3"); } finally { IOUtils.closeQuietly(provider); } }