List of usage examples for java.util.concurrent.locks ReentrantLock ReentrantLock
public ReentrantLock()
From source file:Test.java
public static void main(String[] args) { final Lock firstLock = new ReentrantLock(); final Lock secondLock = new ReentrantLock(); firstLock.lock();/* ww w . ja va 2 s .co m*/ Thread secondThread = new Thread(new Runnable() { public void run() { secondLock.lock(); firstLock.lock(); } }); secondThread.start(); try { Thread.sleep(250); } catch (InterruptedException e) { e.printStackTrace(); } secondLock.lock(); secondLock.unlock(); firstLock.unlock(); }
From source file:Test.java
public static void main(String[] args) throws Exception { Lock myLock = new ReentrantLock(); Random random = new Random(); myLock.lock();/* ww w . j a v a 2 s. c o m*/ int number = random.nextInt(5); int result = 100 / number; System.out.println("A result is " + result); FileOutputStream file = new FileOutputStream("file.out"); file.write(result); file.close(); }
From source file:netflix.archaius.SampleApplication.java
/** * SampleApplication entrypoint//from w w w .jav a 2 s . c o m * @param args * @throws InterruptedException * @throws IOException */ public static void main(String[] args) throws InterruptedException, IOException { //@SuppressWarnings(value = {"unused" }) new SampleApplication(); // Step 1. // Create a Source of Configuration // Here we use a simple ConcurrentMapConfiguration // You can use your own, or use of the pre built ones including JDBCConfigurationSource // which lets you load properties from any RDBMS AbstractConfiguration myConfiguration = new ConcurrentMapConfiguration(); myConfiguration.setProperty("com.netflix.config.samples.sampleapp.prop1", "value1"); myConfiguration.setProperty("com.netflix.config.samples.SampleApp.SampleBean.name", "A Coffee Bean from Gautemala1"); // STEP 2: Optional. Dynamic Runtime property change option // We would like to utilize the benefits of obtaining dynamic property // changes // initialize the DynamicPropertyFactory with our configuration source DynamicPropertyFactory.initWithConfigurationSource(myConfiguration); // STEP 3: Optional. Option to inspect and modify properties using JConsole // We would like to inspect properties via JMX JConsole and potentially // update // these properties too // Register the MBean // // This can be also achieved automatically by setting "true" to // system property "archaius.dynamicPropertyFactory.registerConfigWithJMX" configMBean = ConfigJMXManager.registerConfigMbean(myConfiguration); // once this application is launched, launch JConsole and navigate to // the // Config MBean (under the MBeans tab) System.out.println("Started SampleApplication. Launch JConsole to inspect and update properties"); System.out.println( "To see how callback work, update property com.netflix.config.samples.SampleApp.SampleBean.sensitiveBeanData from BaseConfigBean in JConsole"); SampleBean sampleBean = new SampleBean(); System.out.println("SampleBean:" + sampleBean); System.out.println(sampleBean.getName()); System.setProperty("archaius.fixedDelayPollingScheduler.initialDelayMills", "100"); System.setProperty("archaius.fixedDelayPollingScheduler.delayMills", "100"); // System.setProperty("archaius.configurationSource.defaultFileName", "log4j.properties"); // ConfigurationManager.loadCascadedPropertiesFromResources("log4j"); FixedDelayPollingScheduler f = new FixedDelayPollingScheduler(100, 100, true); // create a property whose value is type long and use 1000 as the default // if the property is not defined System.setProperty("archaius.fixedDelayPollingScheduler.initialDelayMills", "100"); System.setProperty("archaius.fixedDelayPollingScheduler.delayMills", "100"); System.setProperty("archaius.configurationSource.defaultFileName", "log4j.properties"); ConfigurationManager.loadCascadedPropertiesFromResources("log4j"); // create a property whose value is type long and use 1000 as the default // if the property is not defined DynamicLongProperty timeToWait = DynamicPropertyFactory.getInstance().getLongProperty("lock.waitTime", 1000); ReentrantLock lock = new ReentrantLock(); // ... while (true) { lock.tryLock(timeToWait.get(), TimeUnit.MILLISECONDS); // timeToWait.get() returns up-to-date value of the property System.out.println("??" + timeToWait.get()); Thread.sleep(1000); // AbstractConfiguration myConfiguration = new ConcurrentMapConfiguration(); // myConfiguration.setProperty("lock.waitTime", 11); // DynamicPropertyFactory.initWithConfigurationSource(myConfiguration); // System.out.println( "??"+timeToWait.get()); } }
From source file:com.minoritycode.Application.java
public static void main(String[] args) { System.out.println("Trello Backup Application"); File configFile = new File(workingDir + "\\config.properties"); InputStream input = null;//from ww w.j ava 2 s. co m try { input = new FileInputStream(configFile); config.load(input); input.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // String workingDir = System.getProperty("user.dir"); manualOperation = Boolean.parseBoolean(config.getProperty("manualOperation")); logger.startErrorLogger(); setBackupDir(); try { report.put("backupDate", backupDate); } catch (JSONException e) { e.printStackTrace(); logger.logLine(e.getMessage()); } lock = new ReentrantLock(); lockErrorRep = new ReentrantLock(); lockErrorLog = new ReentrantLock(); Application.key = config.getProperty("trellokey"); Application.token = config.getProperty("trellotoken"); boolean useProxy = Boolean.parseBoolean(config.getProperty("useProxy")); boolean proxySet = true; if (useProxy) { proxySet = setProxy(); } // GUI swingContainerDemo = new GUI(); // swingContainerDemo.showJPanelDemo(); if (proxySet) { Credentials credentials = new Credentials(); if (Application.key.isEmpty()) { Application.key = credentials.getKey(); } else { Application.key = config.getProperty("trellokey"); } if (token.isEmpty()) { Application.token = credentials.getToken(); } else { Application.token = config.getProperty("trellotoken"); } BoardDownloader downloader = new BoardDownloader(); downloader.downloadMyBoard(url); boards = downloader.downloadOrgBoard(url); if (boards != null) { try { report.put("boardNum", boards.size()); } catch (JSONException e) { e.printStackTrace(); logger.logLine(e.getMessage()); } Integer numberOfThreads = Integer.parseInt(config.getProperty("numberOfThreads")); if (numberOfThreads == null) { logger.logLine("error number of threads not set in config file"); if (manualOperation) { String message = "How many threads do you want to use (10) is average"; numberOfThreads = Integer.parseInt(Credentials.getInput(message)); Credentials.saveProperty("numberOfThreads", numberOfThreads.toString()); } else { if (Boolean.parseBoolean(config.getProperty("useMailer"))) { Mailer mailer = new Mailer(); mailer.SendMail(); } System.exit(-1); } } ArrayList<Thread> threadList = new ArrayList<Thread>(); for (int i = 0; i < numberOfThreads; i++) { Thread thread = new Thread(new Application(), "BoardDownloadThread"); threadList.add(thread); thread.start(); } } else { //create empty report try { report.put("boardsNotDownloaded", "99999"); report.put("boardNum", 0); report.put("boardNumSuccessful", 0); } catch (JSONException e) { e.printStackTrace(); logger.logLine(e.getMessage()); } if (Boolean.parseBoolean(config.getProperty("useMailer"))) { Mailer mailer = new Mailer(); mailer.SendMail(); } logger.logger(report); } } else { //create empty report try { report.put("boardsNotDownloaded", "99999"); report.put("boardNum", 0); report.put("boardNumSuccessful", 0); } catch (JSONException e) { e.printStackTrace(); logger.logLine(e.getMessage()); } if (Boolean.parseBoolean(config.getProperty("useMailer"))) { Mailer mailer = new Mailer(); mailer.SendMail(); } } }
From source file:org.openbaton.clients.interfaces.client.openstack.OpenstackClient.java
public static void main(String[] args) throws NoSuchMethodException, IOException, InstantiationException, TimeoutException, IllegalAccessException, InvocationTargetException { OpenstackClient.lock = new ReentrantLock(); if (args.length == 6) { PluginStarter.registerPlugin(OpenstackClient.class, args[0], args[1], Integer.parseInt(args[2]), Integer.parseInt(args[3]), args[4], args[5]); } else if (args.length == 4) { PluginStarter.registerPlugin(OpenstackClient.class, args[0], args[1], Integer.parseInt(args[2]), Integer.parseInt(args[3])); } else {/*from w w w . j a v a 2 s .c o m*/ PluginStarter.registerPlugin(OpenstackClient.class, "openstack", "localhost", 5672, 10); } /*OpenstackClient client = new OpenstackClient(); client.init(); VimInstance vimInstance = new VimInstance(); vimInstance.setUsername("openbaton"); vimInstance.setPassword("openbaton"); vimInstance.setTenant("slice-low-latency"); vimInstance.setAuthUrl("http://172.27.101.16:5000/v2.0"); vimInstance.setName("orange-box"); try { System.out.println(client.listFreeFloatingIps(vimInstance)); } catch (VimDriverException e) { e.printStackTrace(); }*/ }
From source file:Main.java
/** * This methods blocks until the worker is done and returns the result value of the worker. * If the worker was canceled an exception will be thrown. * * @param worker The worker/*from w w w. j a v a 2s .c o m*/ * @param <T> result type of the worker * @return the result * @throws InterruptedException if the worker was canceled */ public static <T> T waitFor(Worker<T> worker) throws InterruptedException { Lock lock = new ReentrantLock(); Condition condition = lock.newCondition(); lock.lock(); try { ReadOnlyBooleanProperty doneProperty = createIsDoneProperty(worker); if (doneProperty.get()) { return worker.getValue(); } else { doneProperty.addListener(e -> { boolean locked = lock.tryLock(); if (locked) { try { condition.signal(); } finally { lock.unlock(); } } else { throw new RuntimeException("Concurreny Error"); } }); condition.await(); return worker.getValue(); } } finally { lock.unlock(); } }
From source file:Main.java
/** * like Platform.runLater but waits until the thread has finished * based on: http://www.guigarage.com/2013/01/invokeandwait-for-javafx/ * @param r the runnable to run in a JavaFX thread *//* ww w . j a v a 2 s.c o m*/ public static void platformRunAndWait(final Runnable r) throws Throwable { if (Platform.isFxApplicationThread()) { try { r.run(); } catch (Exception e) { throw new ExecutionException(e); } } else { final Lock lock = new ReentrantLock(); final Condition condition = lock.newCondition(); final boolean[] done = { false }; // to get around the requirement for final final Throwable[] ex = { null }; lock.lock(); try { Platform.runLater(() -> { lock.lock(); try { r.run(); } catch (Throwable e) { ex[0] = e; } finally { try { done[0] = true; condition.signal(); } finally { lock.unlock(); } } }); while (!done[0]) condition.await(); if (ex[0] != null) { // re-throw exception from the runLater thread throw ex[0]; } } finally { lock.unlock(); } } }
From source file:io.nuclei.splice.internal.FileManager.java
public static ReentrantLock lock(FileRef ref) { ReentrantLock lock;/*from ww w . ja v a 2 s . co m*/ boolean locked; synchronized (sLocks) { lock = sLocks.get(ref); if (lock == null) { lock = new ReentrantLock(); sLocks.put(ref, lock); } locked = lock.tryLock(); } if (!locked) { while (true) { synchronized (sLocks) { try { sLocks.wait(); } catch (InterruptedException ignore) { } if (lock.tryLock()) { ReentrantLock newLock = sLocks.get(ref); if (newLock == null) { sLocks.put(ref, lock); break; } else if (newLock != lock) { lock.unlock(); lock = newLock; if (lock.tryLock()) { break; } } else { break; } } } } } return lock; }
From source file:CoarseHashSet.java
CoarseHashSet(int capacity) { super(capacity); lock = new ReentrantLock(); }
From source file:org.geoserver.platform.resource.MemoryLockProvider.java
public MemoryLockProvider(int concurrency) { locks = new java.util.concurrent.locks.Lock[concurrency]; for (int i = 0; i < locks.length; i++) { locks[i] = new ReentrantLock(); }/*from w w w .j ava 2 s. c om*/ }