List of usage examples for java.util.concurrent TimeUnit NANOSECONDS
TimeUnit NANOSECONDS
To view the source code for java.util.concurrent TimeUnit NANOSECONDS.
Click Source Link
From source file:au.com.jwatmuff.eventmanager.Main.java
/** * Main method./*from ww w . j a va2 s .c o m*/ */ public static void main(String args[]) { LogUtils.setupUncaughtExceptionHandler(); /* Set timeout for RMI connections - TODO: move to external file */ System.setProperty("sun.rmi.transport.tcp.handshakeTimeout", "2000"); updateRmiHostName(); /* * Set up menu bar for Mac */ System.setProperty("apple.laf.useScreenMenuBar", "true"); System.setProperty("com.apple.mrj.application.apple.menu.about.name", "Event Manager"); /* * Set look and feel to 'system' style */ try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { log.info("Failed to set system look and feel"); } /* * Set workingDir to a writable folder for storing competitions, settings etc. */ String applicationData = System.getenv("APPDATA"); if (applicationData != null) { workingDir = new File(applicationData, "EventManager"); if (workingDir.exists() || workingDir.mkdirs()) { // redirect logging to writable folder LogUtils.reconfigureFileAppenders("log4j.properties", workingDir); } else { workingDir = new File("."); } } // log version for debugging log.info("Running version: " + VISIBLE_VERSION + " (Internal: " + VERSION + ")"); /* * Copy license if necessary */ File license1 = new File("license.lic"); File license2 = new File(workingDir, "license.lic"); if (license1.exists() && !license2.exists()) { try { FileUtils.copyFile(license1, license2); } catch (IOException e) { log.warn("Failed to copy license from " + license1 + " to " + license2, e); } } if (license1.exists() && license2.exists()) { if (license1.lastModified() > license2.lastModified()) { try { FileUtils.copyFile(license1, license2); } catch (IOException e) { log.warn("Failed to copy license from " + license1 + " to " + license2, e); } } } /* * Check if run lock exists, if so ask user if it is ok to continue */ if (!obtainRunLock(false)) { int response = JOptionPane.showConfirmDialog(null, "Unable to obtain run-lock.\nPlease ensure that no other instances of EventManager are running before continuing.\nDo you wish to continue?", "Run-lock detected", JOptionPane.YES_NO_OPTION); if (response == JOptionPane.YES_OPTION) obtainRunLock(true); else System.exit(0); } try { LoadWindow loadWindow = new LoadWindow(); loadWindow.setVisible(true); loadWindow.addMessage("Reading settings.."); /* * Read properties from file */ final Properties props = new Properties(); try { Properties defaultProps = PropertiesLoaderUtils .loadProperties(new ClassPathResource("eventmanager.properties")); props.putAll(defaultProps); } catch (IOException ex) { log.error(ex); } props.putAll(System.getProperties()); File databaseStore = new File(workingDir, "comps"); int rmiPort = Integer.parseInt(props.getProperty("eventmanager.rmi.port")); loadWindow.addMessage("Loading Peer Manager.."); log.info("Loading Peer Manager"); ManualDiscoveryService manualDiscoveryService = new ManualDiscoveryService(); JmDNSRMIPeerManager peerManager = new JmDNSRMIPeerManager(rmiPort, new File(workingDir, "peerid.dat")); peerManager.addDiscoveryService(manualDiscoveryService); monitorNetworkInterfaceChanges(peerManager); loadWindow.addMessage("Loading Database Manager.."); log.info("Loading Database Manager"); DatabaseManager databaseManager = new SQLiteDatabaseManager(databaseStore, peerManager); LicenseManager licenseManager = new LicenseManager(workingDir); loadWindow.addMessage("Loading Load Competition Dialog.."); log.info("Loading Load Competition Dialog"); LoadCompetitionWindow loadCompetitionWindow = new LoadCompetitionWindow(databaseManager, licenseManager, peerManager); loadCompetitionWindow.setTitle(WINDOW_TITLE); loadWindow.dispose(); log.info("Starting Load Competition Dialog"); while (true) { // reset permission checker to use our license licenseManager.updatePermissionChecker(); GUIUtils.runModalJFrame(loadCompetitionWindow); if (loadCompetitionWindow.getSuccess()) { DatabaseInfo info = loadCompetitionWindow.getSelectedDatabaseInfo(); if (!databaseManager.checkLock(info.id)) { String message = "EventManager did not shut down correctly the last time this competition was open. To avoid potential data corruption, you are advised to take the following steps:\n" + "1) Do NOT open this competition\n" + "2) Create a backup of this competition\n" + "3) Delete the competition from this computer\n" + "4) If possible, reload this competition from another computer on the network\n" + "5) Alternatively, you may manually load the backup onto all computers on the network, ensuring the 'Preserve competition ID' option is checked."; String title = "WARNING: Potential Data Corruption Detected"; int status = JOptionPane.showOptionDialog(null, message, title, JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE, null, new Object[] { "Cancel (recommended)", "Open anyway" }, "Cancel (recommended)"); if (status == 0) continue; // return to load competition window } SynchronizingWindow syncWindow = new SynchronizingWindow(); syncWindow.setVisible(true); long t = System.nanoTime(); DistributedDatabase database = databaseManager.activateDatabase(info.id, info.passwordHash); long dt = System.nanoTime() - t; log.debug(String.format("Initial sync in %dms", TimeUnit.MILLISECONDS.convert(dt, TimeUnit.NANOSECONDS))); syncWindow.dispose(); if (loadCompetitionWindow.isNewDatabase()) { GregorianCalendar calendar = new GregorianCalendar(); Date today = calendar.getTime(); calendar.set(Calendar.MONTH, Calendar.DECEMBER); calendar.set(Calendar.DAY_OF_MONTH, 31); Date endOfYear = new java.sql.Date(calendar.getTimeInMillis()); CompetitionInfo ci = new CompetitionInfo(); ci.setName(info.name); ci.setStartDate(today); ci.setEndDate(today); ci.setAgeThresholdDate(endOfYear); //ci.setPasswordHash(info.passwordHash); License license = licenseManager.getLicense(); if (license != null) { ci.setLicenseName(license.getName()); ci.setLicenseType(license.getType().toString()); ci.setLicenseContact(license.getContactPhoneNumber()); } database.add(ci); } // Set PermissionChecker to use database's license type String competitionLicenseType = database.get(CompetitionInfo.class, null).getLicenseType(); PermissionChecker.setLicenseType(LicenseType.valueOf(competitionLicenseType)); TransactionNotifier notifier = new TransactionNotifier(); database.setListener(notifier); MainWindow mainWindow = new MainWindow(); mainWindow.setDatabase(database); mainWindow.setNotifier(notifier); mainWindow.setPeerManager(peerManager); mainWindow.setLicenseManager(licenseManager); mainWindow.setManualDiscoveryService(manualDiscoveryService); mainWindow.setTitle(WINDOW_TITLE); mainWindow.afterPropertiesSet(); TestUtil.setActivatedDatabase(database); // show main window (modally) GUIUtils.runModalJFrame(mainWindow); // shutdown procedures // System.exit(); database.shutdown(); databaseManager.deactivateDatabase(1500); if (mainWindow.getDeleteOnExit()) { for (File file : info.localDirectory.listFiles()) if (!file.isDirectory()) file.delete(); info.localDirectory.deleteOnExit(); } } else { // This can cause an RuntimeException - Peer is disconnected peerManager.stop(); System.exit(0); } } } catch (Throwable e) { log.error("Error in main function", e); String message = e.getMessage(); if (message == null) message = ""; if (message.length() > 100) message = message.substring(0, 97) + "..."; GUIUtils.displayError(null, "An unexpected error has occured.\n\n" + e.getClass().getSimpleName() + "\n" + message); System.exit(0); } }
From source file:Main.java
/** * Drains the queue as {@link BlockingQueue#drainTo(Collection, int)}, but if the requested * {@code numElements} elements are not available, it will wait for them up to the specified * timeout./*from w w w . j a va 2s.com*/ * * Taken from Google Guava 18.0 Queues * * @param q the blocking queue to be drained * @param buffer where to add the transferred elements * @param numElements the number of elements to be waited for * @param timeout how long to wait before giving up, in units of {@code unit} * @param unit a {@code TimeUnit} determining how to interpret the timeout parameter * @param <E> the type of the queue * @return the number of elements transferred * @throws InterruptedException if interrupted while waiting */ public static <E> int drain(BlockingQueue<E> q, Collection<? super E> buffer, int numElements, long timeout, TimeUnit unit) throws InterruptedException { buffer = Objects.requireNonNull(buffer); /* * This code performs one System.nanoTime() more than necessary, and in return, the time to * execute Queue#drainTo is not added *on top* of waiting for the timeout (which could make * the timeout arbitrarily inaccurate, given a queue that is slow to drain). */ long deadline = System.nanoTime() + unit.toNanos(timeout); int added = 0; while (added < numElements) { // we could rely solely on #poll, but #drainTo might be more efficient when there are multiple // elements already available (e.g. LinkedBlockingQueue#drainTo locks only once) added += q.drainTo(buffer, numElements - added); if (added < numElements) { // not enough elements immediately available; will have to poll E e = q.poll(deadline - System.nanoTime(), TimeUnit.NANOSECONDS); if (e == null) { break; // we already waited enough, and there are no more elements in sight } buffer.add(e); added++; } } return added; }
From source file:Main.java
@Override public String call() throws Exception { while (timeToLive <= System.nanoTime()) { // simulate work here Thread.sleep(500);/*from w ww.ja va 2 s.c om*/ } final long end = System.nanoTime(); return String.format("Finished Elapsed Time = %d, scheduled for %d", TimeUnit.NANOSECONDS.toMillis(timeToLive - end), this.duration); }
From source file:example.rhino.DynamicScopesWithHandlebars.java
private static void runScripts(Context cx, Script script, ExecutorService executor) { ScriptableObject sharedScope = cx.initStandardObjects(null, true); script.exec(cx, sharedScope);// w w w. j av a2 s. co m Runnable[] run = new Runnable[NUM_THREAD]; for (int i = 0; i < NUM_THREAD; i++) { String source2 = "Handlebars.precompile(template)"; run[i] = new PerThread(sharedScope, source2, i); } for (int i = 0; i < NUM_THREAD; i++) { executor.execute(run[i]); } executor.shutdown(); try { executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); } catch (InterruptedException e) { e.printStackTrace(); } }
From source file:org.apache.htrace.impl.RateLimitedLogger.java
public void error(String what) { long now = TimeUnit.MILLISECONDS.convert(System.nanoTime(), TimeUnit.NANOSECONDS); synchronized (this) { if (now >= lastLogTimeMs + timeoutMs) { log.error(what);/*w w w .ja va 2s . co m*/ lastLogTimeMs = now; } } }
From source file:com.tonyodev.fetch.Utils.java
static boolean hasTwoSecondsPassed(long startTime, long stopTime) { if (TimeUnit.NANOSECONDS.toSeconds(stopTime - startTime) >= 2) { return true; }/* ww w. j av a2s. c o m*/ return false; }
From source file:dk.ekot.misc.SynchronizedCache.java
public void add(Path fullSourcePath, Path fullCachePath) throws IOException { long start = System.nanoTime(); synchronized (fileCopyLockSet) { while (fileCopyLockSet.contains(fullCachePath.toString())) { log.trace("Waiting for " + fullCachePath + " to be removed from lock set"); try { fileCopyLockSet.wait(1000); } catch (InterruptedException e) { log.debug("Interrupted or timed out while waiting for changes in fileCopyLockSet, looking for " + fullCachePath); }// ww w . j a v a 2s .c o m log.trace("Interrupted waiting for " + fullCachePath + " after " + TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start) + "ms"); } log.trace("Adding to lock set: " + fullCachePath); fileCopyLockSet.add(fullCachePath.toString()); } try { long elapsed = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start); if (elapsed > 250) { log.warn(String.format("File copy of '%s' delayed %d ms. Possible DDOS.", fullCachePath.toString(), elapsed)); } copy(fullSourcePath, fullCachePath); } finally { log.trace("Removing " + fullCachePath + " from lock set"); // https://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html synchronized (fileCopyLockSet) { fileCopyLockSet.remove(fullCachePath.toString()); fileCopyLockSet.notifyAll(); // Notify waiters } } Path extractedPath = fullSourcePath; cache.put(extractedPath.toString(), fullCachePath); }
From source file:com.civprod.util.concurrent.locks.CompositeLock.java
@Override public boolean tryLock(long time, TimeUnit unit) throws InterruptedException { long timeInNanos = unit.convert(time, TimeUnit.NANOSECONDS); long startTime = System.nanoTime(); int currentLockNumber = 0; boolean locked = true; try {// w ww . ja v a 2 s . c o m while (locked && (currentLockNumber < interLocks.size())) { long currentWaitTime = timeInNanos - (System.nanoTime() - startTime); if (interLocks.get(currentLockNumber).tryLock(currentWaitTime, TimeUnit.NANOSECONDS)) { currentLockNumber++; } else { locked = false; } } } catch (Exception ex) { locked = false; throw (ex); } finally { if (!locked) { while (currentLockNumber >= 1) { currentLockNumber--; interLocks.get(currentLockNumber).unlock(); } } } return locked; }
From source file:org.apache.htrace.impl.RateLimitedLogger.java
public void error(String what, Throwable e) { long now = TimeUnit.MILLISECONDS.convert(System.nanoTime(), TimeUnit.NANOSECONDS); synchronized (this) { if (now >= lastLogTimeMs + timeoutMs) { log.error(what, e);//from ww w . j a va 2 s. c o m lastLogTimeMs = now; } } }
From source file:org.apache.camel.component.zeromq.ZeroMQConsumer.java
@Override protected void doStart() { try {/*from www .j a v a2 s .c o m*/ LOG.trace("Begin ZeroMQConsumer.doStart"); super.doStart(); for (int i = 0; i < concurrentConsumers; ++i) { tasks[i] = new Task(getEndpoint(), getProcessor()); executor.scheduleWithFixedDelay(tasks[i], 0, 1, TimeUnit.NANOSECONDS); } } catch (Exception ex) { LOG.fatal(ex, ex); throw new RuntimeCamelException(ex); } finally { LOG.trace("End ZeroMQConsumer.doStart"); } }