List of usage examples for java.util.concurrent Semaphore release
public void release()
From source file:org.apache.kylin.storage.hbase.util.HbaseStreamingInput.java
private static void scheduleJob(Semaphore semaphore, int interval) { while (true) { semaphore.release(); try {/*from w ww . j a va 2 s. c o m*/ Thread.sleep(interval); } catch (InterruptedException e) { e.printStackTrace(); } } }
From source file:com.all.app.ApplicationUtils.java
public static void showFrameAndWaitForClose(Window window) { try {/* ww w .jav a 2 s .c om*/ final Semaphore lock = new Semaphore(0); window.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { lock.release(); } }); window.setVisible(true); lock.acquire(); } catch (Exception e) { LOG.error(e, e); } }
From source file:hudson.plugins.android_emulator.SdkInstaller.java
/** * Downloads and installs the Android SDK on the machine we're executing on. * * @return An {@code AndroidSdk} object for the newly-installed SDK. *//*ww w . j a v a 2 s. c o m*/ public static AndroidSdk install(Launcher launcher, BuildListener listener, String androidSdkHome) throws SdkInstallationException, IOException, InterruptedException { Semaphore semaphore = acquireLock(); try { return doInstall(launcher, listener, androidSdkHome); } finally { semaphore.release(); } }
From source file:hudson.plugins.android_emulator.SdkInstaller.java
/** * Installs the given platform and its dependencies into the given installation, if necessary. * * @param logger Logs things./*ww w .j a va2 s .c o m*/ * @param launcher Used to launch tasks on the remote node. * @param sdk SDK installation to install components for. * @param platform Specifies the platform to be installed. * @param abi Specifies the ABI to be installed; may be {@code null}. */ public static void installPlatform(PrintStream logger, Launcher launcher, AndroidSdk sdk, String platform, String abi) throws IOException, InterruptedException { // Check whether this platform is already installed if (isPlatformInstalled(logger, launcher, sdk, platform, abi)) { return; } // Check whether we are capable of installing individual components log(logger, Messages.PLATFORM_INSTALL_REQUIRED(platform)); if (!launcher.isUnix() && platform.contains(":") && sdk.getSdkToolsMajorVersion() < 16) { // SDK add-ons can't be installed on Windows until r16 due to http://b.android.com/18868 log(logger, Messages.SDK_ADDON_INSTALLATION_UNSUPPORTED()); return; } if (!sdk.supportsComponentInstallation()) { log(logger, Messages.SDK_COMPONENT_INSTALLATION_UNSUPPORTED()); return; } // Automated installation of ABIs (required for android-14+) is not possible until r17, so // we should warn the user that we can't automatically set up an AVD with older SDK Tools. // See http://b.android.com/21880 if ((platform.endsWith("14") || platform.endsWith("15")) && !sdk.supportsSystemImageInstallation()) { log(logger, Messages.ABI_INSTALLATION_UNSUPPORTED(), true); } // Determine which individual component(s) need to be installed for this platform List<String> components = getSdkComponentsForPlatform(logger, sdk, platform, abi); if (components == null || components.size() == 0) { return; } // If a platform expanded to multiple dependencies (e.g. "GoogleMaps:7" -> android-7 + Maps) // then check whether we really need to install android-7, as it may already be installed if (components.size() > 1) { for (Iterator<String> it = components.iterator(); it.hasNext();) { String component = it.next(); if (isPlatformInstalled(logger, launcher, sdk, component, null)) { it.remove(); } } } // Grab the lock and attempt installation Semaphore semaphore = acquireLock(); try { installComponent(logger, launcher, sdk, components.toArray(new String[0])); } finally { semaphore.release(); } }
From source file:org.marketcetera.saclient.SAClientWSTest.java
private static <R> void verifyInvocationCannotBeInterrupted(final WSTester<R> inTester) throws Exception { resetServiceParameters();/*w w w . j a v a2s . c om*/ getMockSAService().setSleep(true); inTester.setReturnValue(false); final Semaphore sema = new Semaphore(0); final AtomicReference<Exception> interruptFailure = new AtomicReference<Exception>(); Thread t = new Thread() { @Override public void run() { sema.release(); try { inTester.invokeApi(false); } catch (Exception ex) { interruptFailure.set(ex); } } }; t.start(); //Wait for the thread to be started sema.acquire(); //Interrupt it as soon as it is found started t.interrupt(); //wait for it to end t.join(); //verify that we are not able to interrupt it assertNull("API invocation got interrupted!", interruptFailure.get()); }
From source file:net.sourceforge.fullsync.cli.Main.java
public static void startup(String[] args, Launcher launcher) throws Exception { initOptions();/*from w ww . j a v a 2 s. com*/ String configDir = getConfigDir(); CommandLineParser parser = new DefaultParser(); CommandLine line = null; try { line = parser.parse(options, args); } catch (ParseException ex) { System.err.println(ex.getMessage()); printHelp(); System.exit(1); } if (line.hasOption('V')) { System.out.println(String.format("FullSync version %s", Util.getFullSyncVersion())); //$NON-NLS-1$ System.exit(0); } // Apply modifying options if (!line.hasOption("v")) { //$NON-NLS-1$ System.setErr(new PrintStream(new FileOutputStream(getLogFileName()))); } if (line.hasOption("h")) { //$NON-NLS-1$ printHelp(); System.exit(0); } upgradeLegacyPreferencesLocation(configDir); String profilesFile; if (line.hasOption("P")) { //$NON-NLS-1$ profilesFile = line.getOptionValue("P"); //$NON-NLS-1$ } else { profilesFile = configDir + FullSync.PROFILES_XML; upgradeLegacyProfilesXmlLocation(profilesFile); } final String prefrencesFile = configDir + FullSync.PREFERENCES_PROPERTIES; final Injector injector = Guice.createInjector(new FullSyncModule(line, prefrencesFile)); final RuntimeConfiguration rtConfig = injector.getInstance(RuntimeConfiguration.class); injector.getInstance(ProfileManager.class).setProfilesFileName(profilesFile); final ScheduledExecutorService scheduledExecutorService = injector .getInstance(ScheduledExecutorService.class); final EventListener deadEventListener = new EventListener() { private final Logger logger = LoggerFactory.getLogger("DeadEventLogger"); //$NON-NLS-1$ @Subscribe private void onDeadEvent(DeadEvent deadEvent) { if (!(deadEvent.getEvent() instanceof ShutdownEvent)) { logger.warn("Dead event triggered: {}", deadEvent); //$NON-NLS-1$ } } }; final EventBus eventBus = injector.getInstance(EventBus.class); eventBus.register(deadEventListener); final Semaphore sem = new Semaphore(0); Runtime.getRuntime().addShutdownHook(new Thread(() -> { Logger logger = LoggerFactory.getLogger(Main.class); logger.debug("shutdown hook called, starting orderly shutdown"); //$NON-NLS-1$ eventBus.post(new ShutdownEvent()); scheduledExecutorService.shutdown(); try { scheduledExecutorService.awaitTermination(5, TimeUnit.MINUTES); } catch (InterruptedException e) { // not relevant } logger.debug("shutdown hook finished, releaseing main thread semaphore"); //$NON-NLS-1$ sem.release(); })); if (rtConfig.isDaemon().orElse(false).booleanValue() || rtConfig.getProfileToRun().isPresent()) { finishStartup(injector); sem.acquireUninterruptibly(); System.exit(0); } else { launcher.launchGui(injector); System.exit(0); } }
From source file:Main.java
public void runTest() throws Exception { ThreadPoolExecutor tp = new ThreadPoolExecutor(1, 1, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>()); tp.setRejectedExecutionHandler(//from www . j ava2s.co m (Runnable r, ThreadPoolExecutor executor) -> System.out.println("Task rejected: " + r)); Semaphore oneTaskDone = new Semaphore(0); tp.execute(() -> { System.out.println("Sleeping"); try { Thread.sleep(300); } catch (Exception e) { e.printStackTrace(); } System.out.println("Done sleeping"); oneTaskDone.release(); }); tp.execute(new Runnable() { @Override public void run() { System.out.println("Never happends"); } @Override public String toString() { return "Rejected Runnable"; } }); oneTaskDone.acquire(); tp.execute(() -> System.out.println("Running")); tp.shutdown(); tp.awaitTermination(100, TimeUnit.MILLISECONDS); System.out.println("Finished"); }
From source file:org.openhab.io.mqttembeddedbroker.internal.MqttEmbeddedBrokerServiceTest.java
public void waitForConnectionChange(MqttBrokerConnection c, MqttConnectionState expectedState) throws InterruptedException { Semaphore semaphore = new Semaphore(1); semaphore.acquire();//from w w w . ja v a2s. c om MqttConnectionObserver mqttConnectionObserver = (state, error) -> { if (state == expectedState) { semaphore.release(); } }; c.addConnectionObserver(mqttConnectionObserver); if (c.connectionState() == expectedState) { semaphore.release(); } // Start the connection and wait until timeout or connected callback returns. semaphore.tryAcquire(3000, TimeUnit.MILLISECONDS); c.removeConnectionObserver(mqttConnectionObserver); }
From source file:org.onosproject.loadtest.DistributedConsensusLoadTest.java
private void startTest() { stopped.set(false);/*from w w w . ja v a 2s . c o m*/ RateLimiter limiter = RateLimiter.create(rate); Semaphore s = new Semaphore(100); while (!stopped.get()) { limiter.acquire(); s.acquireUninterruptibly(); counters.get(RandomUtils.nextInt(TOTAL_COUNTERS)).incrementAndGet().whenComplete((r, e) -> { s.release(); if (e == null) { increments.incrementAndGet(); } }); } }
From source file:com.kurento.kmf.media.HttpGetEndpointAsyncTest.java
@Before public void setup() throws InterruptedException { final Semaphore sem = new Semaphore(0); pipeline.newHttpGetEndpoint().buildAsync(new Continuation<HttpGetEndpoint>() { @Override/*from w ww . ja va 2s .c om*/ public void onSuccess(HttpGetEndpoint result) { httpEp = result; sem.release(); } @Override public void onError(Throwable cause) { throw new KurentoMediaFrameworkException(cause); } }); Assert.assertTrue(sem.tryAcquire(500, MILLISECONDS)); }