List of usage examples for java.util.concurrent.locks Lock unlock
void unlock();
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 . ja v a 2s . c om * @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:och.util.Util.java
public static void inLock(Lock lock, CallableVoid body) throws Exception { lock.lock();/* w w w. ja va 2s .c o m*/ try { body.call(); } finally { lock.unlock(); } }
From source file:och.util.Util.java
public static <T> T inLock(Lock lock, Callable<T> body) throws Exception { lock.lock();/*from w w w . j ava 2 s . c om*/ try { return body.call(); } finally { lock.unlock(); } }
From source file:com.cloudera.oryx.als.serving.generation.Generation.java
private static Solver recomputeSolver(LongObjectMap<float[]> M, Lock readLock) { readLock.lock();/*from ww w. jav a2 s . com*/ try { if (M == null || M.isEmpty()) { return null; } RealMatrix MTM = MatrixUtils.transposeTimesSelf(M); double infNorm = MTM.getNorm(); if (infNorm < 1.0) { log.warn("X'*X or Y'*Y has small inf norm ({}); try decreasing model.lambda", infNorm); throw new IllConditionedSolverException("infNorm: " + infNorm); } return MatrixUtils.getSolver(MTM); } finally { readLock.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 *///from w w w.j av a 2 s . co 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:net.myrrix.online.generation.Generation.java
private static Solver recomputeSolver(FastByIDMap<float[]> M, Lock readLock) { readLock.lock();//from w w w . j a v a2 s . co m try { if (M == null || M.isEmpty()) { return null; } RealMatrix MTM = MatrixUtils.transposeTimesSelf(M); double infNorm = MTM.getNorm(); if (infNorm < 1.0) { log.warn("X'*X or Y'*Y has small inf norm ({}); try decreasing model.als.lambda", infNorm); throw new IllConditionedSolverException("infNorm: " + infNorm); } return MatrixUtils.getSolver(MTM); } finally { readLock.unlock(); } }
From source file:org.orbisgis.corejdbc.ReadTable.java
public static Collection<Integer> getSortedColumnRowIndex(Connection connection, ReadRowSet originalOrder, String table, String originalColumnName, boolean ascending, ProgressMonitor progressMonitor) throws SQLException { String quoteIdentifier = TableLocation.quoteIdentifier(originalColumnName); TableLocation tableLocation = TableLocation.parse(table); Collection<Integer> columnValues; try (Statement st = connection.createStatement()) { int rowCount = 0; try (ResultSet rs = st.executeQuery("SELECT COUNT(*) cpt from " + tableLocation.toString())) { if (rs.next()) { rowCount = rs.getInt(1); }//from w w w . ja v a2 s . c o m } columnValues = new ArrayList<>(rowCount); PropertyChangeListener listener = EventHandler.create(PropertyChangeListener.class, st, "cancel"); progressMonitor.addPropertyChangeListener(ProgressMonitor.PROP_CANCEL, listener); try { int pkIndex = JDBCUtilities.getIntegerPrimaryKey(connection, tableLocation.toString()); if (pkIndex > 0) { ProgressMonitor jobProgress = progressMonitor.startTask(2); // Do not cache values // Use SQL sort DatabaseMetaData meta = connection.getMetaData(); String pkFieldName = TableLocation .quoteIdentifier(JDBCUtilities.getFieldName(meta, table, pkIndex)); String desc = ""; if (!ascending) { desc = " DESC"; } // Create a map of Row Id to Pk Value ProgressMonitor cacheProgress = jobProgress.startTask(I18N.tr("Cache primary key values"), rowCount); Map<Long, Integer> pkValueToRowId = new HashMap<>(rowCount); int rowId = 0; Lock lock = originalOrder.getReadLock(); lock.tryLock(); try { originalOrder.beforeFirst(); while (originalOrder.next()) { rowId++; pkValueToRowId.put(originalOrder.getPk(), rowId); cacheProgress.endTask(); } } finally { lock.unlock(); } // Read ordered pk values ProgressMonitor sortProgress = jobProgress.startTask(I18N.tr("Read sorted keys"), rowCount); try (ResultSet rs = st.executeQuery( "select " + pkFieldName + " from " + table + " ORDER BY " + quoteIdentifier + desc)) { while (rs.next()) { columnValues.add(pkValueToRowId.get(rs.getLong(1))); sortProgress.endTask(); } } } else { ProgressMonitor jobProgress = progressMonitor.startTask(2); //Cache values ProgressMonitor cacheProgress = jobProgress.startTask(I18N.tr("Cache table values"), rowCount); Comparable[] cache = new Comparable[rowCount]; Lock lock = originalOrder.getReadLock(); lock.tryLock(); try { originalOrder.beforeFirst(); int i = 0; final int fieldIndex = originalOrder.findColumn(originalColumnName); long time1 = 0, time2 = 0, time3 = 0, time4 = 0, time5 = 0; time5 -= System.currentTimeMillis(); while (originalOrder.next()) { time5 += System.currentTimeMillis(); time1 -= System.currentTimeMillis(); Object obj = originalOrder.getObject(fieldIndex); time1 += System.currentTimeMillis(); time2 -= System.currentTimeMillis(); if (obj != null && !(obj instanceof Comparable)) { throw new SQLException(I18N.tr("Could only sort comparable database object type")); } time2 += System.currentTimeMillis(); time3 -= System.currentTimeMillis(); cache[i++] = (Comparable) obj; time3 += System.currentTimeMillis(); time4 -= System.currentTimeMillis(); cacheProgress.endTask(); time4 += System.currentTimeMillis(); time5 -= System.currentTimeMillis(); } time5 += System.currentTimeMillis(); System.out.println("time 1:" + time1 + ";" + "time 2:" + time2 + ";" + "time 3:" + time3 + ";" + "time 4:" + time4 + ";" + "time 5:" + time5 + ";"); } finally { lock.unlock(); } ProgressMonitor sortProgress = jobProgress.startTask(I18N.tr("Sort table values"), rowCount); Comparator<Integer> comparator = new SortValueCachedComparator(cache); if (!ascending) { comparator = Collections.reverseOrder(comparator); } columnValues = new TreeSet<>(comparator); for (int i = 1; i <= rowCount; i++) { columnValues.add(i); sortProgress.endTask(); } } } finally { progressMonitor.removePropertyChangeListener(listener); } return columnValues; } }
From source file:fm.last.moji.impl.FileDownloadInputStream.java
private void unlockQuietly(Lock lock) { try {// w w w.j a v a 2s. co m lock.unlock(); } catch (IllegalMonitorStateException e) { } }
From source file:example.pki.VaultPkiConfiguration.java
/** * Obtain SSL certificate (cached/request new certificate) with startup locking. * * @param vaultProperties/*from www . j a v a2 s.c o m*/ * @param vaultOperations * @param pkiProperties * @param serverProperties * @param synchronizationProvider * @return * @throws Exception */ @Bean @ConditionalOnProperty(prefix = "server.ssl", name = "enabled", havingValue = "true") public static SslCertificateEmbeddedServletContainerCustomizer sslCertificateRequestingPostProcessor( VaultProperties vaultProperties, VaultOperations vaultOperations, VaultPkiProperties pkiProperties, ServerProperties serverProperties, SynchronizationProvider synchronizationProvider) throws Exception { Lock lock = synchronizationProvider.getLock(); CertificateBundle certificateBundle = CertificateUtil.findValidCertificate(vaultProperties, vaultOperations, pkiProperties); if (certificateBundle != null) { return createCustomizer(serverProperties, certificateBundle); } boolean locked = lock.tryLock(pkiProperties.getStartupLockTimeout(), TimeUnit.MILLISECONDS); if (!locked) { throw new IllegalStateException(String.format("Could not obtain SSL synchronization lock within %d %s", pkiProperties.getStartupLockTimeout(), TimeUnit.MILLISECONDS)); } try { certificateBundle = CertificateUtil.getOrRequestCertificate(vaultProperties, vaultOperations, pkiProperties); return createCustomizer(serverProperties, certificateBundle); } finally { lock.unlock(); } }
From source file:com.civprod.util.concurrent.locks.CompositeLock.java
@Override public void unlock() { for (Lock curLock : interLocks) { curLock.unlock(); } }