List of usage examples for java.util.concurrent Semaphore release
public void release()
From source file:com.qwazr.search.index.IndexInstance.java
IndexStatus getStatus() throws IOException, InterruptedException { final Semaphore sem = schema.acquireReadSemaphore(); try {/*from w w w.j a v a2 s . c o m*/ return getIndexStatus(); } finally { if (sem != null) sem.release(); } }
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 {//from www. ja va2 s.com 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); } }
From source file:com.qwazr.search.index.IndexInstance.java
final void deleteAll() throws IOException, InterruptedException, ServerException { final Semaphore sem = schema.acquireWriteSemaphore(); try {/* w ww. ja va 2s.c o m*/ indexWriter.deleteAll(); nrtCommit(); } finally { if (sem != null) sem.release(); } }
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 w w. ja v a2 s. c om*/ 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:com.castlemock.web.basis.model.RepositoryImpl.java
/** * Delete an instance that match the provided id * @param id The instance that matches the provided id will be deleted in the database *//* w ww . j ava 2 s .c o m*/ @Override public void delete(final I id) { Preconditions.checkNotNull(id, "The provided id cannot be null"); final String filename = getFilename(id); LOGGER.debug("Start the deletion of " + entityClass.getSimpleName() + " with id " + id); Semaphore writeLock = getWriteLock(id); try { writeLock.acquire(); fileRepositorySupport.delete(filename); collection.remove(id); LOGGER.debug("Deletion of " + entityClass.getSimpleName() + " with id " + id + " was successfully completed"); } catch (InterruptedException e) { throw new IllegalStateException("Unable to accuire the write lock", e); } finally { writeLock.release(); } }
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 a v a2 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:com.cwp.android.baidutest.MyApplication.java
public static void startMaInfoMonitoring() { //?MaInfo?/*w ww. ja va2 s .co m*/ BmobRealTimeData rtd = new BmobRealTimeData(); //start? //?? rtd.start(mContext, new ValueEventListener() { @Override public void onConnectCompleted() { //? Log.d("->MyApplication", "BmobRealTimeData->currentThread=" + Thread.currentThread()); Log.d("->MyApplication", "BmobRealTimeData->?:" + rtd.isConnected()); //? if (rtd.isConnected()) { rtd.subTableUpdate("MaInfo"); } } @Override public void onDataChange(JSONObject jsonObject) { // new Thread(() -> { Log.d("->MyApplication", "onDataChange->currentThread=" + Thread.currentThread()); Log.d("->MyApplication", "onDataChange->(" + jsonObject.optString("action") + ")\n?" + jsonObject); if (BmobRealTimeData.ACTION_UPDATETABLE.equals(jsonObject.optString("action"))) { JSONObject data = jsonObject.optJSONObject("data"); Log.d("->MyApplication", "onDataChange->?"); String username = data.optString("username"); String vin = data.optString("vin"); try { mSyncSemaphore.acquire(); } catch (InterruptedException e) { e.printStackTrace(); } //????????????? List<AutoInfo> list = AutoInfoLocalDBOperation .queryBy(mContext, AutoInfoConstants.COLUMN_USERNAME + " = ? and " + AutoInfoConstants.COLUMN_VIN + " = ?", new String[] { username, vin }); if (list.size() != 0) { Log.d("->MyApplication", "onDataChange->?"); //? AutoInfo autoInfo = list.get(0); String brand = autoInfo.getBrand(); String model = autoInfo.getModel(); String plateNum = autoInfo.getLicensePlateNum(); Message message = Message.obtain(); message.what = -1; message.obj = brand + " " + model + " " + plateNum; //??????? if (data.optInt("gasolineVolume") < 20) {//?<20% // mHandler.sendEmptyMessage(1); } //?15000? //?1500?(??)????? //??? //??5.E.a-c,???? //???? Semaphore semaphore = new Semaphore(1); double mileage = data.optDouble("mileage"); //mileage?15000?? if (mileage >= 15000) { try { semaphore.acquire(); } catch (InterruptedException e) { e.printStackTrace(); } String scanTime = data.optString("scanTime"); BmobQuery<MaInfo> query = new BmobQuery<MaInfo>(); query.addWhereEqualTo("username", username); query.addWhereEqualTo("vin", vin); query.addWhereLessThan("scanTime", scanTime); query.addQueryKeys("scanTime"); query.order("-scanTime"); final Semaphore finalSemaphore = semaphore; query.findObjects(mContext, new FindListener<MaInfo>() { @Override public void onSuccess(List<MaInfo> list) { int current = (int) mileage / 15000; Log.d("", "current=" + current + ",mileage=" + mileage); if (list.size() == 0) { message.obj = current; message.what = 2; mHandler.sendMessage(message); } else { double lastMileage = list.get(0).getMileage(); int last = (int) lastMileage / 15000; if (current > last) { Message message = Message.obtain(); message.obj = current; message.what = 2; mHandler.sendMessage(message); } } finalSemaphore.release(); } @Override public void onError(int i, String s) { finalSemaphore.release(); } }); } try { semaphore.acquire(); } catch (InterruptedException e) { e.printStackTrace(); } //??????????? if (data.optString("enginePerfor").equals("")) {//? mHandler.sendEmptyMessage(3); } if (data.optString("lamp").equals("")) {//? mHandler.sendEmptyMessage(4); } if (data.optString("transmissionPerfor").equals("")) {//? mHandler.sendEmptyMessage(5); } semaphore.release(); //???? mHandler.sendEmptyMessage(0); mSyncSemaphore.release(); Log.d("++++++++++++++++++++", "++++++++++++++++"); } else { mSyncSemaphore.release(); } } }).start(); } }); }
From source file:com.netflix.curator.x.discovery.TestServiceDiscovery.java
@Test public void testCrashedServer() throws Exception { List<Closeable> closeables = Lists.newArrayList(); TestingServer server = new TestingServer(); closeables.add(server);/*ww w. ja v a 2 s . c o m*/ try { Timing timing = new Timing(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); closeables.add(client); client.start(); final Semaphore semaphore = new Semaphore(0); ServiceInstance<String> instance = ServiceInstance.<String>builder().payload("thing").name("test") .port(10064).build(); ServiceDiscovery<String> discovery = new ServiceDiscoveryImpl<String>(client, "/test", new JsonInstanceSerializer<String>(String.class), instance) { @Override protected void internalRegisterService(ServiceInstance<String> service) throws Exception { super.internalRegisterService(service); semaphore.release(); } }; closeables.add(discovery); discovery.start(); timing.acquireSemaphore(semaphore); Assert.assertEquals(discovery.queryForInstances("test").size(), 1); KillSession.kill(client.getZookeeperClient().getZooKeeper(), server.getConnectString()); server.stop(); server = new TestingServer(server.getPort(), server.getTempDirectory()); closeables.add(server); timing.acquireSemaphore(semaphore); Assert.assertEquals(discovery.queryForInstances("test").size(), 1); } finally { for (Closeable c : closeables) { IOUtils.closeQuietly(c); } } }
From source file:com.gooddata.http.client.GoodDataHttpClientIntegrationTest.java
License:asdf
@Test public void shouldRefreshTTConcurrent() throws Exception { mock401OnProjects();//ww w . j a v a2 s .com // this serves to block second thread, until the first one gets 401 on projects, which causes TT refresh // the test aims to test the second thread is not cycling on 401 and cumulating wrong TT headers final Semaphore semaphore = new Semaphore(1); requestOnPath(GDC_PROJECTS_PATH, "TT1").respondUsing(new Responder() { boolean first = true; @Override public StubResponse nextResponse(Request request) { if (first) { first = false; return StubResponse.builder().status(200).body(BODY_PROJECTS, CHARSET) .header(CONTENT_HEADER, CONTENT_TYPE_JSON_UTF).build(); } else { semaphore.release(); return StubResponse.builder().status(401).body(BODY_401, CHARSET) .header(CONTENT_HEADER, CONTENT_TYPE_JSON_UTF) .header(WWW_AUTHENTICATE_HEADER, GOODDATA_REALM + " " + TT_COOKIE) .delay(5, TimeUnit.SECONDS).build(); } } }); mock200OnProjects("TT2"); mock401OnPath(GDC_PROJECTS2_PATH, "TT1"); mock200OnPath(GDC_PROJECTS2_PATH, "TT2"); mock401OnToken(); respond200OnToken(mock200OnToken("TT1").thenRespond(), "TT2"); mockLogin(); final HttpClient client = createGoodDataClient(jadlerLogin, jadlerPassword, jadlerHost); // one get at the beginning causing successful login performGet(client, jadlerHost, GDC_PROJECTS_PATH, 200); // to be able to finish when both threads finished final CountDownLatch countDown = new CountDownLatch(2); final ExecutorService executor = Executors.newFixedThreadPool(2); semaphore.acquire(); // will be released in jadler executor.submit(new PerformGetWithCountDown(client, GDC_PROJECTS_PATH, countDown)); semaphore.acquire(); // causes waiting executor.submit(new PerformGetWithCountDown(client, GDC_PROJECTS2_PATH, countDown)); countDown.await(10, TimeUnit.SECONDS); verifyThatRequest().havingMethodEqualTo("GET").havingPathEqualTo(GDC_TOKEN_PATH) .havingHeaderEqualTo(SST_HEADER, "SST") // if received more than twice, it means the second thread didn't wait, while the first was refreshing TT .receivedTimes(2); verifyThatRequest().havingMethodEqualTo("GET").havingPathEqualTo(GDC_PROJECTS2_PATH) .havingHeaderEqualTo(TT_HEADER, "TT1") // the second thread should try only once with expired TT1 .receivedOnce(); verifyThatRequest().havingMethodEqualTo("GET").havingPathEqualTo(GDC_PROJECTS2_PATH) .havingHeaderEqualTo(TT_HEADER, "TT1").havingHeaderEqualTo(TT_HEADER, "TT2") // the second thread should not set more than one X-GDC-AuthTT header .receivedNever(); }
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(); 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);//from w w w .j a v a 2s.c o m 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(); }