List of usage examples for java.util.concurrent Semaphore release
public void release()
From source file:com.qwazr.search.index.IndexInstance.java
final Collection<Object> postMappedDocuments(final Collection<Map<String, Object>> documents) throws IOException, InterruptedException { if (documents == null || documents.isEmpty()) return null; final Semaphore sem = schema.acquireWriteSemaphore(); try {/*from w w w . j a v a 2s . com*/ schema.checkSize(documents.size()); RecordsPoster.UpdateMapDocument poster = getDocumentPoster(); documents.forEach(poster); nrtCommit(); return poster.ids; } finally { if (sem != null) sem.release(); } }
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 av a 2 s .c o m*/ } 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.qwazr.search.index.IndexInstance.java
final <T> Collection<Object> postDocuments(final Map<String, Field> fields, final Collection<T> documents) throws IOException, InterruptedException { if (documents == null || documents.isEmpty()) return null; final Semaphore sem = schema.acquireWriteSemaphore(); try {//www. jav a 2s .c om schema.checkSize(documents.size()); RecordsPoster.UpdateObjectDocument poster = getDocumentPoster(fields); documents.forEach(poster); nrtCommit(); return poster.ids; } finally { if (sem != null) sem.release(); } }
From source file:org.apache.spark.network.RpcIntegrationSuite.java
private RpcResult sendRPC(String... commands) throws Exception { TransportClient client = clientFactory.createClient(TestUtils.getLocalHost(), server.getPort()); final Semaphore sem = new Semaphore(0); final RpcResult res = new RpcResult(); res.successMessages = Collections.synchronizedSet(new HashSet<String>()); res.errorMessages = Collections.synchronizedSet(new HashSet<String>()); RpcResponseCallback callback = new RpcResponseCallback() { @Override//w ww .j a v a 2s . co m public void onSuccess(ByteBuffer message) { String response = JavaUtils.bytesToString(message); res.successMessages.add(response); sem.release(); } @Override public void onFailure(Throwable e) { res.errorMessages.add(e.getMessage()); sem.release(); } }; for (String command : commands) { client.sendRpc(JavaUtils.stringToBytes(command), callback); } if (!sem.tryAcquire(commands.length, 5, TimeUnit.SECONDS)) { fail("Timeout getting response from the server"); } client.close(); return res; }
From source file:com.netflix.curator.framework.recipes.cache.TestPathChildrenCache.java
@Test public void testIssue27Alt() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start();/*from w ww.ja va2s.c o m*/ try { client.create().forPath("/base"); client.create().forPath("/base/a"); client.create().forPath("/base/b"); client.create().forPath("/base/c"); client.getChildren().forPath("/base"); final List<PathChildrenCacheEvent.Type> events = Lists.newArrayList(); final Semaphore semaphore = new Semaphore(0); PathChildrenCache cache = new PathChildrenCache(client, "/base", true); cache.getListenable().addListener(new PathChildrenCacheListener() { @Override public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception { events.add(event.getType()); semaphore.release(); } }); cache.start(PathChildrenCache.StartMode.BUILD_INITIAL_CACHE); client.delete().forPath("/base/a"); Assert.assertTrue(semaphore.tryAcquire(1, 10, TimeUnit.SECONDS)); client.create().forPath("/base/a"); Assert.assertTrue(semaphore.tryAcquire(1, 10, TimeUnit.SECONDS)); List<PathChildrenCacheEvent.Type> expected = Lists.newArrayList( PathChildrenCacheEvent.Type.CHILD_REMOVED, PathChildrenCacheEvent.Type.CHILD_ADDED); Assert.assertEquals(expected, events); } finally { client.close(); } }
From source file:com.netflix.curator.framework.recipes.cache.TestPathChildrenCache.java
@Test public void testIssue27() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start();//from ww w . ja v a 2 s.com try { client.create().forPath("/base"); client.create().forPath("/base/a"); client.create().forPath("/base/b"); client.create().forPath("/base/c"); client.getChildren().forPath("/base"); final List<PathChildrenCacheEvent.Type> events = Lists.newArrayList(); final Semaphore semaphore = new Semaphore(0); PathChildrenCache cache = new PathChildrenCache(client, "/base", true); cache.getListenable().addListener(new PathChildrenCacheListener() { @Override public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception { events.add(event.getType()); semaphore.release(); } }); cache.start(); Assert.assertTrue(semaphore.tryAcquire(3, 10, TimeUnit.SECONDS)); client.delete().forPath("/base/a"); Assert.assertTrue(semaphore.tryAcquire(1, 10, TimeUnit.SECONDS)); client.create().forPath("/base/a"); Assert.assertTrue(semaphore.tryAcquire(1, 10, TimeUnit.SECONDS)); List<PathChildrenCacheEvent.Type> expected = Lists.newArrayList(PathChildrenCacheEvent.Type.CHILD_ADDED, PathChildrenCacheEvent.Type.CHILD_ADDED, PathChildrenCacheEvent.Type.CHILD_ADDED, PathChildrenCacheEvent.Type.CHILD_REMOVED, PathChildrenCacheEvent.Type.CHILD_ADDED); Assert.assertEquals(expected, events); } finally { client.close(); } }
From source file:org.apache.flume.client.avro.TestReliableSpoolingFileEventReader.java
private void readEventsForFilesInDir(File dir, ReliableEventReader reader, Collection<String> actual, Semaphore semaphore1, Semaphore semaphore2) throws IOException { List<Event> events; boolean executed = false; for (int i = 0; i < listFiles(dir).size(); i++) { events = reader.readEvents(10);/* w w w .j av a 2s.c o m*/ for (Event e : events) { actual.add(new String(e.getBody())); } reader.commit(); try { if (!executed) { executed = true; if (semaphore1 != null) { semaphore1.release(); } if (semaphore2 != null) { semaphore2.acquire(); } } } catch (Exception ex) { throw new IOException(ex); } } }
From source file:org.telegram.ui.ChannelEditTypeActivity.java
@SuppressWarnings("unchecked") @Override/*from w ww . ja v a 2 s . co 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.netflix.curator.x.discovery.TestServiceDiscovery.java
@Test public void testCrashedServerMultiInstances() throws Exception { List<Closeable> closeables = Lists.newArrayList(); TestingServer server = new TestingServer(); closeables.add(server);// w w w. j a v a 2s . co 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> instance1 = ServiceInstance.<String>builder().payload("thing").name("test") .port(10064).build(); ServiceInstance<String> instance2 = ServiceInstance.<String>builder().payload("thing").name("test") .port(10065).build(); ServiceDiscovery<String> discovery = new ServiceDiscoveryImpl<String>(client, "/test", new JsonInstanceSerializer<String>(String.class), instance1) { @Override protected void internalRegisterService(ServiceInstance<String> service) throws Exception { super.internalRegisterService(service); semaphore.release(); } }; closeables.add(discovery); discovery.start(); discovery.registerService(instance2); timing.acquireSemaphore(semaphore, 2); Assert.assertEquals(discovery.queryForInstances("test").size(), 2); KillSession.kill(client.getZookeeperClient().getZooKeeper(), server.getConnectString()); server.stop(); server = new TestingServer(server.getPort(), server.getTempDirectory()); closeables.add(server); timing.acquireSemaphore(semaphore, 2); Assert.assertEquals(discovery.queryForInstances("test").size(), 2); } finally { for (Closeable c : closeables) { IOUtils.closeQuietly(c); } } }
From source file:org.paxle.core.threading.impl.Master.java
public void process(final Data cmd) throws Exception { // creating and assigning a dummy output queues final Semaphore s = new Semaphore(0); final IInputQueue<Data> inputQueue = new IInputQueue<Data>() { private int counter = 0; public Data dequeue() throws InterruptedException { if (counter > 0) throw new IllegalStateException("Method executed multiple times"); this.counter++; return cmd; }// w ww .jav a2s . co m public void waitForNext() throws InterruptedException { throw new IllegalStateException("You are not allowed to call this method"); } }; final IOutputQueue<Data> outputQueue = new IOutputQueue<Data>() { public void enqueue(Data command) throws InterruptedException { s.release(); } }; // process the command this.process(inputQueue, outputQueue, false); // waiting for the worker to finish execution s.acquire(); }