List of usage examples for java.util.concurrent Semaphore release
public void release()
From source file:com.impetus.ankush2.ganglia.GangliaDeployer.java
@Override public boolean register(final ClusterConfig conf) { try {// www. j a v a 2s . co m if (String.valueOf(advanceConf.get(Constant.Keys.REGISTER_LEVEL)) .equalsIgnoreCase(Constant.RegisterLevel.LEVEL1.toString())) { return true; } final String infoMsg = "Registering " + getComponentName() + "..."; logger.info(infoMsg); // Getting node map for cluster deployment Map<String, Map<String, Object>> nodeMap = new HashMap<String, Map<String, Object>>( compConfig.getNodes()); // Node Registration process ... final Semaphore semaphore = new Semaphore(nodeMap.size()); for (final String host : nodeMap.keySet()) { semaphore.acquire(); AppStoreWrapper.getExecutor().execute(new Runnable() { @Override public void run() { conf.getNodes().get(host).setStatus(configureServiceMonitoring(host)); if (semaphore != null) { semaphore.release(); } } }); } semaphore.acquire(nodeMap.size()); // Return false if any of the node is not deployed. return AnkushUtils.getStatus(conf.getNodes()); } catch (Exception e) { addClusterError("Could not register " + getComponentName(), e); return false; } }
From source file:edu.chalmers.dat076.moviefinder.service.MovieFileDatabaseHandlerImpl.java
@Override public void saveFile(final Path path) { Runnable r = new Runnable() { @Override//from ww w.j a v a2 s . 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.parse.ParseUserTest.java
@Test public void testBecomeWithCallback() throws Exception { // Register a mock currentUserController to make setCurrentUser work ParseCurrentUserController currentUserController = mock(ParseCurrentUserController.class); when(currentUserController.setAsync(any(ParseUser.class))).thenReturn(Task.<Void>forResult(null)); ParseCorePlugins.getInstance().registerCurrentUserController(currentUserController); // Register a mock userController to make getUsreAsync work ParseUserController userController = mock(ParseUserController.class); ParseUser.State newUserState = new ParseUser.State.Builder().put("key", "value") .sessionToken("sessionToken").build(); when(userController.getUserAsync(anyString())).thenReturn(Task.forResult(newUserState)); ParseCorePlugins.getInstance().registerUserController(userController); final Semaphore done = new Semaphore(0); ParseUser.becomeInBackground("sessionToken", new LogInCallback() { @Override//from w ww. j a va2s . c om public void done(ParseUser user, ParseException e) { done.release(); assertNull(e); // Make sure user's data is correct assertEquals("sessionToken", user.getSessionToken()); assertEquals("value", user.get("key")); } }); // Make sure we call getUserAsync verify(userController, times(1)).getUserAsync("sessionToken"); // Make sure we set currentUser verify(currentUserController, times(1)).setAsync(any(ParseUser.class)); }
From source file:com.parse.ParseUserTest.java
@Test public void testLogInWithCallback() throws Exception { // Register a mock currentUserController to make setCurrentUser work ParseCurrentUserController currentUserController = mock(ParseCurrentUserController.class); when(currentUserController.setAsync(any(ParseUser.class))).thenReturn(Task.<Void>forResult(null)); ParseCorePlugins.getInstance().registerCurrentUserController(currentUserController); // Register a mock userController to make logIn work ParseUserController userController = mock(ParseUserController.class); ParseUser.State newUserState = new ParseUser.State.Builder().put("newKey", "newValue") .sessionToken("newSessionToken").build(); when(userController.logInAsync(anyString(), anyString())).thenReturn(Task.forResult(newUserState)); ParseCorePlugins.getInstance().registerUserController(userController); final Semaphore done = new Semaphore(0); ParseUser.logInInBackground("userName", "password", new LogInCallback() { @Override//from w w w . ja va2 s .c o m public void done(ParseUser user, ParseException e) { done.release(); assertNull(e); // Make sure user's data is correct assertEquals("newSessionToken", user.getSessionToken()); assertEquals("newValue", user.get("newKey")); } }); assertTrue(done.tryAcquire(5, TimeUnit.SECONDS)); // Make sure user is login verify(userController, times(1)).logInAsync("userName", "password"); // Make sure we set currentUser verify(currentUserController, times(1)).setAsync(any(ParseUser.class)); }
From source file:com.bt.aloha.collections.memory.InMemoryCollectionImpl.java
public void replace(T info) { if (info == null) throw new IllegalArgumentException(String.format( "Trying to replace element in collection %s with null info", this.getClass().getSimpleName())); String infoId = info.getId(); log.debug(String.format("InMemoryInfoCollection replacing %s", infoId)); Semaphore semaphore = getSemaphores().get(infoId); if (semaphore == null) throw new IllegalArgumentException( String.format("Trying to replace non-existing info %s in collection %s", infoId, this.getClass().getSimpleName())); try {/*from w w w. ja va 2 s . c o m*/ semaphore.acquire(); } catch (InterruptedException e) { log.error(String.format(FAILED_TO_READ_OBJECT_MESSAGE, infoId, this.getClass().getSimpleName(), e.getMessage()), e); throw new CollectionAccessInterruptedException(String.format(FAILED_TO_READ_OBJECT_MESSAGE, infoId, this.getClass().getSimpleName(), e.getMessage()), e); } try { T oldInfo = infos.get(infoId); if (!oldInfo.getVersionId().equals(info.getVersionId())) throw new ConcurrentUpdateException(infoId, String.format( "Info %s modified in collection %s, try again", infoId, this.getClass().getSimpleName())); T newInfo = info.cloneObject(); newInfo.updateVersionId(); doExtraUpdates(info, newInfo); infos.put(infoId, (T) newInfo); info.setVersionId(newInfo.getVersionId()); log.debug(String.format("Replaced info %s, new version %s", infoId, newInfo.getVersionId())); } finally { semaphore.release(); } }
From source file:nl.sogeti.android.gpstracker.viewer.LoggerMap.java
/** * Called when the activity is first created. */// ww w . java 2s . c om @Override protected void onCreate(Bundle load) { try { super.onCreate(load); } catch (NullPointerException exceptions) { // Unrecoverable Google Maps V1 crash Toast.makeText(this, R.string.error_map_nullpointer, Toast.LENGTH_LONG); } setContentView(R.layout.map); Toolbar toolbar = (Toolbar) findViewById(R.id.support_actionbar); setSupportActionBar(toolbar); findViewById(R.id.mapScreen).setDrawingCacheEnabled(true); mUnits = new UnitsI18n(this); mLoggerServiceManager = new GPSLoggerServiceManager(); final Semaphore calulatorSemaphore = new Semaphore(0); Thread calulator = new Thread("OverlayCalculator") { @Override public void run() { Looper.prepare(); mHandler = new Handler(); calulatorSemaphore.release(); Looper.loop(); } }; calulator.start(); try { calulatorSemaphore.acquire(); } catch (InterruptedException e) { Log.e(this, "Failed waiting for a semaphore", e); } mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); mMapView = (MapView) findViewById(R.id.myMapView); setupHardwareAcceleration(); mMylocation = new FixedMyLocationOverlay(this, mMapView); mMapView.setBuiltInZoomControls(true); mMapView.setClickable(true); TextView[] speeds = { (TextView) findViewById(R.id.speedview05), (TextView) findViewById(R.id.speedview04), (TextView) findViewById(R.id.speedview03), (TextView) findViewById(R.id.speedview02), (TextView) findViewById(R.id.speedview01), (TextView) findViewById(R.id.speedview00) }; mSpeedtexts = speeds; mLastGPSSpeedView = (TextView) findViewById(R.id.currentSpeed); mLastGPSAltitudeView = (TextView) findViewById(R.id.currentAltitude); mDistanceView = (TextView) findViewById(R.id.currentDistance); mFab = (FloatingActionButton) findViewById(R.id.tracking_control); createListeners(); if (load != null) { onRestoreInstanceState(load); } if (getIntent() != null) { handleIntentData(getIntent()); } }
From source file:org.springframework.integration.ip.tcp.TcpSendingMessageHandlerTests.java
@Test public void testNetSingleUseNoInbound() throws Exception { final int port = SocketUtils.findAvailableServerSocket(); final CountDownLatch latch = new CountDownLatch(1); final Semaphore semaphore = new Semaphore(0); final AtomicBoolean done = new AtomicBoolean(); Executors.newSingleThreadExecutor().execute(new Runnable() { public void run() { try { ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port); latch.countDown();/* ww w . j a v a 2s. c o m*/ for (int i = 0; i < 2; i++) { Socket socket = server.accept(); semaphore.release(); byte[] b = new byte[6]; readFully(socket.getInputStream(), b); semaphore.release(); socket.close(); } server.close(); } catch (Exception e) { if (!done.get()) { e.printStackTrace(); } } } }); AbstractConnectionFactory ccf = new TcpNetClientConnectionFactory("localhost", port); ByteArrayCrLfSerializer serializer = new ByteArrayCrLfSerializer(); ccf.setSerializer(serializer); ccf.setDeserializer(serializer); ccf.setSoTimeout(10000); ccf.start(); ccf.setSingleUse(true); TcpSendingMessageHandler handler = new TcpSendingMessageHandler(); handler.setConnectionFactory(ccf); assertTrue(latch.await(10, TimeUnit.SECONDS)); handler.handleMessage(MessageBuilder.withPayload("Test").build()); handler.handleMessage(MessageBuilder.withPayload("Test").build()); assertTrue(semaphore.tryAcquire(4, 10000, TimeUnit.MILLISECONDS)); done.set(true); ccf.stop(); }
From source file:org.springframework.integration.ip.tcp.TcpSendingMessageHandlerTests.java
@Test public void testNioSingleUseNoInbound() throws Exception { final int port = SocketUtils.findAvailableServerSocket(); final CountDownLatch latch = new CountDownLatch(1); final Semaphore semaphore = new Semaphore(0); final AtomicBoolean done = new AtomicBoolean(); Executors.newSingleThreadExecutor().execute(new Runnable() { public void run() { try { ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port); latch.countDown();/*from w w w . ja v a 2 s .co m*/ for (int i = 0; i < 2; i++) { Socket socket = server.accept(); semaphore.release(); byte[] b = new byte[8]; readFully(socket.getInputStream(), b); semaphore.release(); socket.close(); } server.close(); } catch (Exception e) { if (!done.get()) { e.printStackTrace(); } } } }); AbstractConnectionFactory ccf = new TcpNioClientConnectionFactory("localhost", port); ByteArrayCrLfSerializer serializer = new ByteArrayCrLfSerializer(); ccf.setSerializer(serializer); ccf.setDeserializer(serializer); ccf.setSoTimeout(5000); ccf.start(); ccf.setSingleUse(true); TcpSendingMessageHandler handler = new TcpSendingMessageHandler(); handler.setConnectionFactory(ccf); assertTrue(latch.await(10, TimeUnit.SECONDS)); handler.handleMessage(MessageBuilder.withPayload("Test.1").build()); handler.handleMessage(MessageBuilder.withPayload("Test.2").build()); assertTrue(semaphore.tryAcquire(4, 10000, TimeUnit.MILLISECONDS)); done.set(true); ccf.stop(); }
From source file:org.apache.pulsar.broker.service.BrokerService.java
/** * Create pending topic and on completion it picks the next one until processes all topics in * {@link #pendingTopicLoadingQueue}.<br/> * It also tries to acquire {@link #topicLoadRequestSemaphore} so throttle down newly incoming topics and release * permit if it was successful to acquire it. *///from ww w .j av a 2s.c om private void createPendingLoadTopic() { Pair<String, CompletableFuture<Topic>> pendingTopic = pendingTopicLoadingQueue.poll(); if (pendingTopic == null) { return; } final String topic = pendingTopic.getLeft(); try { checkTopicNsOwnership(topic); CompletableFuture<Topic> pendingFuture = pendingTopic.getRight(); final Semaphore topicLoadSemaphore = topicLoadRequestSemaphore.get(); final boolean acquiredPermit = topicLoadSemaphore.tryAcquire(); createPersistentTopic(topic, pendingFuture); pendingFuture.handle((persistentTopic, ex) -> { // release permit and process next pending topic if (acquiredPermit) { topicLoadSemaphore.release(); } createPendingLoadTopic(); return null; }); } catch (RuntimeException re) { log.error("Failed to create pending topic {} {}", topic, re); pendingTopic.getRight().completeExceptionally(re.getCause()); // schedule to process next pending topic inactivityMonitor.schedule(() -> createPendingLoadTopic(), 100, TimeUnit.MILLISECONDS); } }
From source file:org.springframework.integration.ip.tcp.TcpSendingMessageHandlerTests.java
@Test public void testNetSingleUseWithInbound() throws Exception { final int port = SocketUtils.findAvailableServerSocket(); final CountDownLatch latch = new CountDownLatch(1); final Semaphore semaphore = new Semaphore(0); final AtomicBoolean done = new AtomicBoolean(); Executors.newSingleThreadExecutor().execute(new Runnable() { public void run() { try { ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port); latch.countDown();//from www . j av a 2s.c o m for (int i = 1; i < 3; i++) { Socket socket = server.accept(); semaphore.release(); byte[] b = new byte[6]; readFully(socket.getInputStream(), b); b = ("Reply" + i + "\r\n").getBytes(); socket.getOutputStream().write(b); socket.close(); } server.close(); } catch (Exception e) { if (!done.get()) { e.printStackTrace(); } } } }); AbstractConnectionFactory ccf = new TcpNetClientConnectionFactory("localhost", port); ByteArrayCrLfSerializer serializer = new ByteArrayCrLfSerializer(); ccf.setSerializer(serializer); ccf.setDeserializer(serializer); ccf.setSoTimeout(10000); ccf.start(); ccf.setSingleUse(true); TcpSendingMessageHandler handler = new TcpSendingMessageHandler(); handler.setConnectionFactory(ccf); TcpReceivingChannelAdapter adapter = new TcpReceivingChannelAdapter(); adapter.setConnectionFactory(ccf); QueueChannel channel = new QueueChannel(); adapter.setOutputChannel(channel); assertTrue(latch.await(10, TimeUnit.SECONDS)); handler.handleMessage(MessageBuilder.withPayload("Test").build()); handler.handleMessage(MessageBuilder.withPayload("Test").build()); assertTrue(semaphore.tryAcquire(2, 10000, TimeUnit.MILLISECONDS)); Set<String> replies = new HashSet<String>(); for (int i = 0; i < 2; i++) { Message<?> mOut = channel.receive(10000); assertNotNull(mOut); replies.add(new String((byte[]) mOut.getPayload())); } assertTrue(replies.remove("Reply1")); assertTrue(replies.remove("Reply2")); done.set(true); ccf.stop(); }