List of usage examples for java.util.concurrent Semaphore acquire
public void acquire() throws InterruptedException
From source file:com.adobe.ags.curly.test.ErrorBehaviorTest.java
private void sync() { Semaphore test = new Semaphore(1); test.acquireUninterruptibly();/* ww w. ja v a 2 s . c o m*/ Platform.runLater(test::release); try { test.acquire(); } catch (InterruptedException ex) { Logger.getLogger(ErrorBehaviorTest.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.thoughtworks.go.agent.bootstrapper.AgentBootstrapperTest.java
@Test public void shouldNotDieWhenInvocationOfLauncherRaisesException_butCreationOfLauncherWentThrough() throws InterruptedException { final Semaphore waitForLauncherInvocation = new Semaphore(1); waitForLauncherInvocation.acquire(); final AgentBootstrapper bootstrapper = new AgentBootstrapper() { @Override/*from ww w. j a v a2 s.c o m*/ AgentLauncherCreator getLauncherCreator() { return new AgentLauncherCreator() { public AgentLauncher createLauncher() { return new AgentLauncher() { public int launch(AgentLaunchDescriptor descriptor) { try { throw new RuntimeException("fail!!! i say."); } finally { if (waitForLauncherInvocation.availablePermits() == 0) { waitForLauncherInvocation.release(); } } } }; } @Override public void close() { } }; } }; final AgentBootstrapper spyBootstrapper = stubJVMExit(bootstrapper); Thread stopLoopThd = new Thread(new Runnable() { public void run() { try { waitForLauncherInvocation.acquire(); } catch (InterruptedException e) { throw new RuntimeException(e); } ReflectionUtil.setField(spyBootstrapper, "loop", false); } }); stopLoopThd.start(); try { spyBootstrapper.go(true, new AgentBootstrapperArgs(new URL("http://" + "ghost-name" + ":" + 3518 + "/go"), null, AgentBootstrapperArgs.SslMode.NONE)); stopLoopThd.join(); } catch (Exception e) { fail("should not have propagated exception thrown while invoking the launcher"); } }
From source file:com.thoughtworks.go.agent.bootstrapper.AgentBootstrapperTest.java
@Test public void shouldNotDieWhenCreationOfLauncherRaisesException() throws InterruptedException { final Semaphore waitForLauncherCreation = new Semaphore(1); waitForLauncherCreation.acquire(); final boolean[] reLaunchWaitIsCalled = new boolean[1]; final AgentBootstrapper bootstrapper = new AgentBootstrapper() { @Override/* ww w .j a v a2 s. c o m*/ void waitForRelaunchTime() { assertThat(waitTimeBeforeRelaunch, is(0)); reLaunchWaitIsCalled[0] = true; super.waitForRelaunchTime(); } @Override AgentLauncherCreator getLauncherCreator() { return new AgentLauncherCreator() { public AgentLauncher createLauncher() { try { throw new RuntimeException("i bombed"); } finally { if (waitForLauncherCreation.availablePermits() == 0) { waitForLauncherCreation.release(); } } } @Override public void close() { } }; } }; final AgentBootstrapper spyBootstrapper = stubJVMExit(bootstrapper); Thread stopLoopThd = new Thread(new Runnable() { public void run() { try { waitForLauncherCreation.acquire(); } catch (InterruptedException e) { throw new RuntimeException(e); } ReflectionUtil.setField(spyBootstrapper, "loop", false); } }); stopLoopThd.start(); try { spyBootstrapper.go(true, new AgentBootstrapperArgs(new URL("http://" + "ghost-name" + ":" + 3518 + "/go"), null, AgentBootstrapperArgs.SslMode.NONE)); stopLoopThd.join(); } catch (Exception e) { fail("should not have propagated exception thrown while creating launcher"); } assertThat(reLaunchWaitIsCalled[0], is(true)); }
From source file:org.openengsb.core.services.internal.deployer.connector.ConnectorDeployerService.java
@Override public void update(File artifact) throws Exception { LOGGER.debug("ConnectorDeployer.update(\"{}\")", artifact.getAbsolutePath()); Semaphore semaphore = updateSemaphores.get(artifact); semaphore.acquire(); try {//from w w w.jav a 2 s . com doUpdate(artifact); } finally { semaphore.release(); } }
From source file:com.aionemu.gameserver.model.TribeRelationCheck.java
void checkAttack(final Npc npc, final Player player) { final Semaphore mainLock = lock; try {//www. j ava 2s . c om mainLock.acquire(); } catch (InterruptedException e1) { } time = System.currentTimeMillis(); npc.getObserveController().clear(); npc.getObserveController().addObserver(new ActionObserver(ObserverType.ATTACK) { @Override public void attack(Creature creature) { System.out.println("\t" + npc.getObjectTemplate().getName() + " attacked " + player.getCommonData().getName() + " - " + (System.currentTimeMillis() - time) + " ms"); attacked = true; } }); ThreadPoolManager.getInstance().execute(new Runnable() { @Override public void run() { ((NpcAI2) npc.getAi2()).setStateIfNot(AIState.IDLE); setPositionAsSpawned(player.getPosition()); npc.setPosition(player.getPosition()); player.unsetState(CreatureState.DEAD); player.getLifeStats().setCurrentHpPercent(100); npc.getKnownList().doUpdate(); CreatureEventHandler.onCreatureSee((NpcAI2) npc.getAi2(), player); } }); }
From source file:com.bt.sdk.callcontrol.sip.util.EhCacheCollectionImpl.java
public void remove(String infoId) { if (!semaphoreCache.getKeys().contains(infoId)) return;//from w ww .jav a 2s . co m Semaphore semaphore = (Semaphore) semaphoreCache.get(infoId).getObjectValue(); if (semaphore == null) return; try { semaphore.acquire(); } catch (InterruptedException e) { log.error(String.format(FAILED_TO_REMOVE_OBJECT_MESSAGE, infoId, this.getClass().getSimpleName(), e.getMessage())); throw new CollectionAccessInterruptedException(String.format(FAILED_TO_REMOVE_OBJECT_MESSAGE, infoId, this.getClass().getSimpleName(), e.getMessage()), e); } try { boolean b = cache.remove(infoId); System.out.println(b + ":" + infoId); if (b) { semaphoreCache.remove(infoId); log.info(String.format("Removed info %s", infoId)); } else log.warn(String.format("Failed to find info %s", infoId)); } finally { semaphore.release(); } }
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 *///from ww w .ja v a 2s.co 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:com.castlemock.web.basis.model.RepositoryImpl.java
/** * The save method provides the functionality to save an instance to the file system. * @param type The type that will be saved to the file system. * @return The type that was saved to the file system. The main reason for it is being returned is because * there could be modifications of the object during the save process. For example, if the type does not * have an identifier, then the method will generate a new identifier for the type. */// w w w. j a v a 2 s . co m protected D save(final T type) { I id = type.getId(); if (id == null) { id = (I) generateId(); type.setId(id); } checkType(type); final String filename = getFilename(id); final Semaphore writeLock = getWriteLock(id); try { writeLock.acquire(); fileRepositorySupport.save(type, filename); collection.put(id, type); return mapper.map(type, dtoClass); } catch (InterruptedException e) { throw new IllegalStateException("Unable to acquire the write lock", e); } finally { writeLock.release(); } }
From source file:com.boundlessgeo.geoserver.api.controllers.ThumbnailController.java
/** * Clears any cached thumbnail information (called by {@link ThumbnailInvalidatingCatalogListener} when a layer is removed). * /*w w w .ja v a 2s .c om*/ * @param layer * @throws InterruptedException */ public void clearThumbnail(PublishedInfo layer) { Semaphore s = semaphores.get(layer); try { s.acquire(); } catch (InterruptedException e) { LOG.finer("Unable to clear thumbnail for " + layer.prefixedName() + ":" + e.getMessage()); return; } try { File loRes = config.cacheFile(thumbnailFilename(layer)); if (loRes.exists()) { boolean removed = loRes.delete(); if (!removed) { loRes.deleteOnExit(); } } File hiRes = config.cacheFile(thumbnailFilename(layer, true)); if (hiRes.exists()) { boolean removed = hiRes.delete(); if (!removed) { hiRes.deleteOnExit(); } } } finally { s.release(); } }
From source file:com.impetus.ankush2.utils.LogsManager.java
public String downloadLogsOnServer() throws AnkushException { try {//from ww w. j ava2 s . co m String clusterResourcesLogsDir = AppStoreWrapper.getClusterResourcesPath() + "logs/"; String clusterLogsDirName = "Logs_" + this.clusterConfig.getName() + "_" + System.currentTimeMillis(); String clusterLogsArchiveName = clusterLogsDirName + ".zip"; final String cmpLogsDirPathOnServer = clusterResourcesLogsDir + clusterLogsDirName + "/" + component + "/"; if (!FileUtils.ensureFolder(cmpLogsDirPathOnServer)) { throw (new AnkushException("Could not create log directory for " + this.component + " on server.")); } final Semaphore semaphore = new Semaphore(nodes.size()); try { for (final String host : nodes) { semaphore.acquire(); AppStoreWrapper.getExecutor().execute(new Runnable() { @Override public void run() { NodeConfig nodeConfig = clusterConfig.getNodes().get(host); SSHExec connection = SSHUtils.connectToNode(host, clusterConfig.getAuthConf()); if (connection == null) { // TODO: handle Error LOG.error("Could not fetch log files - Connection not initialized", component, host); } Serviceable serviceableObj = null; try { serviceableObj = ObjectFactory.getServiceObject(component); for (String role : roles) { if (nodeConfig.getRoles().get(component).contains(role)) { String tmpLogsDirOnServer = cmpLogsDirPathOnServer + "/" + role + "/" + host + "/"; if (!FileUtils.ensureFolder(tmpLogsDirOnServer)) { // TODO: handle Error // Log error in operation table and // skip // this role continue; } String nodeLogsDirPath = FileUtils.getSeparatorTerminatedPathEntry( serviceableObj.getLogDirPath(clusterConfig, host, role)); String logFilesRegex = serviceableObj.getLogFilesRegex(clusterConfig, host, role, null); String outputTarArchiveName = role + "_" + +System.currentTimeMillis() + ".tar.gz"; try { List<String> logsFilesList = AnkushUtils.listFilesInDir(connection, host, nodeLogsDirPath, logFilesRegex); AnkushTask ankushTask = new CreateTarArchive(nodeLogsDirPath, nodeLogsDirPath + outputTarArchiveName, logsFilesList); if (connection.exec(ankushTask).rc != 0) { // TODO: handle Error // Log error in operation table // and // skip this // role continue; } connection.downloadFile(nodeLogsDirPath + outputTarArchiveName, tmpLogsDirOnServer + outputTarArchiveName); ankushTask = new Remove(nodeLogsDirPath + outputTarArchiveName); connection.exec(ankushTask); System.out.println("tmpLogsDirOnServer + outputTarArchiveName : " + tmpLogsDirOnServer + outputTarArchiveName); ankushTask = new UnTarArchive(tmpLogsDirOnServer + outputTarArchiveName, tmpLogsDirOnServer); System.out.println( "ankushTask.getCommand() : " + ankushTask.getCommand()); Runtime.getRuntime().exec(ankushTask.getCommand()).waitFor(); ankushTask = new Remove(tmpLogsDirOnServer + outputTarArchiveName); Runtime.getRuntime().exec(ankushTask.getCommand()).waitFor(); } catch (Exception e) { e.printStackTrace(); // TODO: handle exception // Log error in operation table and // skip // this role continue; } } } } catch (Exception e) { // TODO: handle exception return; } finally { if (semaphore != null) { semaphore.release(); } if (connection != null) { connection.disconnect(); } } } }); } semaphore.acquire(nodes.size()); } catch (Exception e) { } ZipUtil.pack(new File(clusterResourcesLogsDir + clusterLogsDirName), new File(clusterResourcesLogsDir + clusterLogsArchiveName), true); org.apache.commons.io.FileUtils.deleteDirectory(new File(clusterResourcesLogsDir + clusterLogsDirName)); // result.put(com.impetus.ankush2.constant.Constant.Keys.DOWNLOADPATH, // clusterResourcesLogsDir + clusterLogsArchiveName); } catch (Exception e) { // this.addAndLogError("Could not download logs for " + component + // "."); LOG.error(e.getMessage(), component, e); } return null; }