List of usage examples for java.util.concurrent Semaphore Semaphore
public Semaphore(int permits)
From source file:com.bt.aloha.batchtest.ultramonkey.SyncServiceImpl.java
@Override public String makeCall(String caller, String callee) { String callId = null;//from w w w . j ava 2 s . c om synchronized (makeCallLock) { callId = super.makeCall(caller, callee); callConnectedSemaphores.put(callId, new Semaphore(0)); } if (waitForCallConnectedEvent(callId)) { return callId; } throw new ServiceException("No call connected event received for callId " + callId); }
From source file:com.solace.samples.BasicRequestor.java
public void run(String... args) { System.out.println("BasicRequestor initializing..."); try {//from ww w. j a va 2 s . c o m // Create an Mqtt client final MqttClient mqttClient = new MqttClient("tcp://" + args[0], "HelloWorldBasicRequestor"); MqttConnectOptions connOpts = new MqttConnectOptions(); connOpts.setCleanSession(true); // Connect the client System.out.println("Connecting to Solace broker: tcp://" + args[0]); mqttClient.connect(connOpts); System.out.println("Connected"); // Semaphore used for synchronizing b/w threads final Semaphore latch = new Semaphore(0); // Topic the client will use to send request messages final String requestTopic = "T/GettingStarted/request"; // Callback - Anonymous inner-class for receiving the Reply-To topic from the Solace broker mqttClient.setCallback(new MqttCallback() { public void messageArrived(String topic, MqttMessage message) throws Exception { // If the topic is "$SYS/client/reply-to" then set our replyToTopic // to with the contents of the message payload received if (topic != null && topic.equals("$SYS/client/reply-to")) { replyToTopic = new String(message.getPayload()); System.out.println("\nReceived Reply-to topic from Solace for the MQTT client:" + "\n\tReply-To: " + replyToTopic + "\n"); } else { // Received a response to our request try { // Parse the response payload and convert to a JSONObject Object obj = parser.parse(new String(message.getPayload())); JSONObject jsonPayload = (JSONObject) obj; System.out.println("\nReceived a response!" + "\n\tCorrel. Id: " + (String) jsonPayload.get("correlationId") + "\n\tMessage: " + (String) jsonPayload.get("message") + "\n"); } catch (ParseException ex) { System.out.println("Exception parsing response message!"); ex.printStackTrace(); } } latch.release(); // unblock main thread } public void connectionLost(Throwable cause) { System.out.println("Connection to Solace broker lost!" + cause.getMessage()); latch.release(); } public void deliveryComplete(IMqttDeliveryToken token) { } }); // Subscribe client to the special Solace topic for requesting a unique // Reply-to destination for the MQTT client System.out.println("Requesting Reply-To topic from Solace..."); mqttClient.subscribe("$SYS/client/reply-to", 0); // Wait for till we have received the reply to Topic try { latch.acquire(); } catch (InterruptedException e) { System.out.println("I was awoken while waiting"); } // Check if we have a Reply-To topic if (replyToTopic == null || replyToTopic.isEmpty()) { System.out.println("Unable to request Reply-To from Solace. Exiting"); System.exit(0); } // Subscribe client to the Solace provide Reply-To topic with a QoS level of 0 System.out.println("Subscribing client to Solace provide Reply-To topic"); mqttClient.subscribe(replyToTopic, 0); // Create the request payload in JSON format JSONObject obj = new JSONObject(); obj.put("correlationId", UUID.randomUUID().toString()); obj.put("replyTo", replyToTopic); obj.put("message", "Sample Request"); String reqPayload = obj.toJSONString(); // Create a request message and set the request payload MqttMessage reqMessage = new MqttMessage(reqPayload.getBytes()); reqMessage.setQos(0); System.out.println("Sending request to: " + requestTopic); // Publish the request message mqttClient.publish(requestTopic, reqMessage); // Wait for till we have received a response try { latch.acquire(); // block here until message received } catch (InterruptedException e) { System.out.println("I was awoken while waiting"); } // Disconnect the client mqttClient.disconnect(); System.out.println("Exiting"); System.exit(0); } catch (MqttException me) { System.out.println("reason " + me.getReasonCode()); System.out.println("msg " + me.getMessage()); System.out.println("loc " + me.getLocalizedMessage()); System.out.println("cause " + me.getCause()); System.out.println("excep " + me); me.printStackTrace(); } }
From source file:com.amazonaws.services.simpleworkflow.flow.worker.ActivityTaskPoller.java
public void setTaskExecutorService(ThreadPoolExecutor taskExecutorService) { this.taskExecutorService = taskExecutorService; pollSemaphore = new Semaphore(taskExecutorService.getMaximumPoolSize()); }
From source file:com.pinterest.rocksplicator.controller.WorkerPoolTest.java
@Test public void testAssignSameCluster() throws Exception { Semaphore idleWorkersSemaphore = new Semaphore(0); ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1, 1, 0, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(1)); WorkerPool workerPool = new WorkerPool(threadPoolExecutor, idleWorkersSemaphore, new TaskQueue() { });//from w w w. j ava2 s . com Task task = getSleepIncrementTask(); workerPool.assignTask(task); Thread.sleep(2000); Assert.assertEquals(1, SleepIncrementTask.executionCounter.intValue()); workerPool.assignTask(task); Thread.sleep(2000); Assert.assertEquals(2, (int) SleepIncrementTask.executionCounter); Assert.assertEquals(2, idleWorkersSemaphore.availablePermits()); }
From source file:com.netflix.curator.framework.recipes.cache.TestNodeCache.java
@Test public void testDeleteThenCreate() throws Exception { NodeCache cache = null;/*from w w w .j a v a2 s . c o m*/ CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); try { client.create().creatingParentsIfNeeded().forPath("/test/foo", "one".getBytes()); final AtomicReference<Throwable> error = new AtomicReference<Throwable>(); client.getUnhandledErrorListenable().addListener(new UnhandledErrorListener() { @Override public void unhandledError(String message, Throwable e) { error.set(e); } }); final Semaphore semaphore = new Semaphore(0); cache = new NodeCache(client, "/test/foo"); cache.getListenable().addListener(new NodeCacheListener() { @Override public void nodeChanged() throws Exception { semaphore.release(); } }); cache.start(true); Assert.assertEquals(cache.getCurrentData().getData(), "one".getBytes()); client.delete().forPath("/test/foo"); Assert.assertTrue(semaphore.tryAcquire(1, 10, TimeUnit.SECONDS)); client.create().forPath("/test/foo", "two".getBytes()); Assert.assertTrue(semaphore.tryAcquire(1, 10, TimeUnit.SECONDS)); Throwable t = error.get(); if (t != null) { Assert.fail("Assert", t); } Assert.assertEquals(cache.getCurrentData().getData(), "two".getBytes()); cache.close(); } finally { IOUtils.closeQuietly(cache); IOUtils.closeQuietly(client); } }
From source file:io.hops.erasure_coding.ReedSolomonDecoder.java
public ReedSolomonDecoder(Configuration conf) { super(conf, Codec.getCodec("rs")); this.reedSolomonCode = new ReedSolomonCode[parallelism]; stripeSize = this.codec.stripeLength; paritySize = this.codec.parityLength; for (int i = 0; i < parallelism; i++) { reedSolomonCode[i] = new ReedSolomonCode(stripeSize, paritySize); }/*from w w w . j a v a 2 s .c om*/ decodeOps = new Semaphore(parallelism); }
From source file:org.wso2.carbon.analytics.eventsink.internal.queue.AnalyticsEventQueue.java
@SuppressWarnings("unchecked") public AnalyticsEventQueue(int tenantId) { Disruptor<WrappedEventFactory.WrappedEvent> eventQueue = new Disruptor<>(new WrappedEventFactory(), ServiceHolder.getAnalyticsEventSinkConfiguration().getQueueSize(), Executors.newCachedThreadPool()); eventQueue.handleEventsWith(new AnalyticsEventQueueWorker(tenantId, this)); this.currentEventSize = 0; this.ringBuffer = eventQueue.start(); this.currentSize = new AtomicInteger(0); this.maxSize = ServiceHolder.getAnalyticsEventSinkConfiguration().getMaxQueueCapacity(); this.semaphore = new Semaphore(1); if (log.isDebugEnabled()) { log.debug("Event Queue Size = " + ServiceHolder.getAnalyticsEventSinkConfiguration().getQueueSize()); }//from w ww . jav a 2 s .c o m }
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);/*from www . ja va 2 s.com*/ 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:frames.CreatePublisher.java
public CreatePublisher() { initComponents();//w w w . ja v a 2 s . c o m //Create semaphore with a single permission semaphore = new Semaphore(1); //Centralizes frame setLocationRelativeTo(null); //Make CreatePublisher frame visible setVisible(true); }
From source file:com.pinterest.rocksplicator.controller.DispatcherTest.java
@Test public void testNoPendingTask() throws Exception { // Assuming there is no task in the queue in the test. PowerMockito.when(taskQueue.dequeueTask(anyString())).thenReturn(null); Semaphore idleWorkersSemaphore = new Semaphore(1); ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1, 1, 0, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(1)); WorkerPool workerPool = new WorkerPool(threadPoolExecutor, idleWorkersSemaphore, taskQueue); TaskDispatcher dispatcher = new TaskDispatcher(1, idleWorkersSemaphore, workerPool, taskQueue); dispatcher.start();/*w ww . j av a2 s.c om*/ Thread.sleep(1000); Assert.assertEquals(1, idleWorkersSemaphore.availablePermits()); Thread.sleep(1000); Assert.assertEquals(1, idleWorkersSemaphore.availablePermits()); dispatcher.stop(); }