List of usage examples for java.util.concurrent.locks ReentrantLock lock
public void lock()
From source file:org.apache.cassandra.concurrent.ContinuationsExecutor.java
/** * If there is a security manager, makes sure caller has permission to shut * down threads in general (see shutdownPerm). If this passes, additionally * makes sure the caller is allowed to interrupt each worker thread. This * might not be true even if first check passed, if the SecurityManager * treats some threads specially.//from ww w . ja v a 2 s. co m */ private void checkShutdownAccess() { SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkPermission(shutdownPerm); final ReentrantLock mainLock = this.mainLock; mainLock.lock(); try { for (Worker w : workers) security.checkAccess(w.thread); } finally { mainLock.unlock(); } } }
From source file:org.apache.cassandra.concurrent.ContinuationsExecutor.java
/** * Interrupts threads that might be waiting for tasks (as indicated by not * being locked) so they can check for termination or configuration changes. * Ignores SecurityExceptions (in which case some threads may remain * uninterrupted)./* w w w .j a v a 2s . c om*/ * * @param onlyOne * If true, interrupt at most one worker. This is called only * from tryTerminate when termination is otherwise enabled but * there are still other workers. In this case, at most one * waiting worker is interrupted to propagate shutdown signals in * case all threads are currently waiting. Interrupting any * arbitrary thread ensures that newly arriving workers since * shutdown began will also eventually exit. To guarantee * eventual termination, it suffices to always interrupt only one * idle worker, but shutdown() interrupts all idle workers so * that redundant workers exit promptly, not waiting for a * straggler task to finish. */ private void interruptIdleWorkers(boolean onlyOne) { final ReentrantLock mainLock = this.mainLock; mainLock.lock(); try { for (Worker w : workers) { Thread t = w.thread; if (!t.isInterrupted() && w.tryLock()) { try { t.interrupt(); } catch (SecurityException ignore) { } finally { w.unlock(); } } if (onlyOne) break; } } finally { mainLock.unlock(); } }
From source file:org.apache.cassandra.concurrent.ContinuationsExecutor.java
/** * Performs cleanup and bookkeeping for a dying worker. Called only from * worker threads. Unless completedAbruptly is set, assumes that workerCount * has already been adjusted to account for exit. This method removes thread * from worker set, and possibly terminates the pool or replaces the worker * if either it exited due to user task exception or if fewer than * corePoolSize workers are running or queue is non-empty but there are no * workers.//w w w . jav a 2s . com * * @param w * the worker * @param completedAbruptly * if the worker died due to user exception */ private void processWorkerExit(Worker w, boolean completedAbruptly) { if (completedAbruptly) // If abrupt, then workerCount wasn't adjusted decrementWorkerCount(); final ReentrantLock mainLock = this.mainLock; mainLock.lock(); try { completedTaskCount += w.completedTasks; workers.remove(w); } finally { mainLock.unlock(); } tryTerminate(); int c = ctl.get(); if (runStateLessThan(c, STOP)) { if (!completedAbruptly) { int min = allowCoreThreadTimeOut ? 0 : corePoolSize; if (min == 0 && !workQueue.isEmpty()) min = 1; if (workerCountOf(c) >= min) return; // replacement not needed } addWorker(null, false); } }
From source file:org.apache.cassandra.concurrent.ContinuationsExecutor.java
/** * Transitions to TERMINATED state if either (SHUTDOWN and pool and queue * empty) or (STOP and pool empty). If otherwise eligible to terminate but * workerCount is nonzero, interrupts an idle worker to ensure that shutdown * signals propagate. This method must be called following any action that * might make termination possible -- reducing worker count or removing * tasks from the queue during shutdown. The method is non-private to allow * access from ScheduledThreadPoolExecutor. *///from www .j a v a2 s. c o m final void tryTerminate() { for (;;) { int c = ctl.get(); if (isRunning(c) || runStateAtLeast(c, TIDYING) || (runStateOf(c) == SHUTDOWN && !workQueue.isEmpty())) return; if (workerCountOf(c) != 0) { // Eligible to terminate interruptIdleWorkers(ONLY_ONE); return; } final ReentrantLock mainLock = this.mainLock; mainLock.lock(); try { if (ctl.compareAndSet(c, ctlOf(TIDYING, 0))) { try { terminated(); } finally { ctl.set(ctlOf(TERMINATED, 0)); termination.signalAll(); } return; } } finally { mainLock.unlock(); } // else retry on failed CAS } }
From source file:org.apache.cassandra.concurrent.ContinuationsExecutor.java
/** * Checks if a new worker can be added with respect to current pool state * and the given bound (either core or maximum). If so, the worker count is * adjusted accordingly, and, if possible, a new worker is created and * started running firstTask as its first task. This method returns false if * the pool is stopped or eligible to shut down. It also returns false if * the thread factory fails to create a thread when asked, which requires a * backout of workerCount, and a recheck for termination, in case the * existence of this worker was holding up termination. * // w w w . j av a2 s. co m * @param firstTask * the task the new thread should run first (or null if none). * Workers are created with an initial first task (in method * execute()) to bypass queuing when there are fewer than * corePoolSize threads (in which case we always start one), or * when the queue is full (in which case we must bypass queue). * Initially idle threads are usually created via * prestartCoreThread or to replace other dying workers. * * @param core * if true use corePoolSize as bound, else maximumPoolSize. (A * boolean indicator is used here rather than a value to ensure * reads of fresh values after checking other pool state). * @return true if successful */ private boolean addWorker(Runnable firstTask, boolean core) { retry: for (;;) { int c = ctl.get(); int rs = runStateOf(c); // Check if queue empty only if necessary. if (rs >= SHUTDOWN && !(rs == SHUTDOWN && firstTask == null && !workQueue.isEmpty())) return false; for (;;) { int wc = workerCountOf(c); if (wc >= CAPACITY || wc >= (core ? corePoolSize : maximumPoolSize)) return false; if (compareAndIncrementWorkerCount(c)) break retry; c = ctl.get(); // Re-read ctl if (runStateOf(c) != rs) continue retry; // else CAS failed due to workerCount change; retry inner loop } } Worker w = new Worker(firstTask); Thread t = w.thread; final ReentrantLock mainLock = this.mainLock; mainLock.lock(); try { // Recheck while holding lock. // Back out on ThreadFactory failure or if // shut down before lock acquired. int c = ctl.get(); int rs = runStateOf(c); if (t == null || (rs >= SHUTDOWN && !(rs == SHUTDOWN && firstTask == null))) { decrementWorkerCount(); tryTerminate(); return false; } workers.add(w); int s = workers.size(); if (s > largestPoolSize) largestPoolSize = s; } finally { mainLock.unlock(); } t.start(); // It is possible (but unlikely) for a thread to have been // added to workers, but not yet started, during transition to // STOP, which could result in a rare missed interrupt, // because Thread.interrupt is not guaranteed to have any effect // on a non-yet-started Thread (see Thread#interrupt). if (runStateOf(ctl.get()) == STOP && !t.isInterrupted()) t.interrupt(); return true; }
From source file:org.openanzo.datasource.nodecentric.internal.NodeCentricDatasource.java
/** * Begin database transaction//from ww w . j a v a 2s .c o m * * Note:Database already in transaction * * @param connection * {@link Connection} to underlying database * @param needsWrite * if true, tables will be locked if needed * @param needsTransaction * TODO * @throws AnzoException * {@link ExceptionConstants.RDB#ALREADY_IN_RDB_TRANSACTION} if this connection is already with a transaction * @throws AnzoException * {@link ExceptionConstants.RDB#FAILED_START_RDB_TRANSACTION} if there was a problem setting autoCommit to false */ public void begin(Connection connection, boolean needsWrite, boolean needsTransaction) throws AnzoException { long start = 0; if (stats.isEnabled()) { start = System.currentTimeMillis(); stats.getBeginUse().increment(); } try { ReentrantLock lock = connectionLocks.get(connection); if (lock == null) { lock = new ReentrantLock(); connectionLocks.put(connection, lock); } if (lock.isLocked()) { throw new AnzoException(ExceptionConstants.RDB.ALREADY_IN_RDB_TRANSACTION); } lock.lock(); if (lock.getHoldCount() == 1 && needsTransaction) { try { connection.setAutoCommit(false); } catch (SQLException e) { lock.unlock(); log.error(LogUtils.RDB_MARKER, "Error starting jdbc transaction", e); throw new AnzoRuntimeException(ExceptionConstants.RDB.FAILED_START_RDB_TRANSACTION, e); } try { lockTable(connection, needsWrite); } catch (AnzoException e) { try { connection.setAutoCommit(false); } catch (SQLException sqle) { log.error(LogUtils.RDB_MARKER, "Error aborting jdbc transaction", sqle); } lock.unlock(); throw e; } } } finally { if (stats.isEnabled()) { stats.getBeginDuration().addTime((System.currentTimeMillis() - start)); } } }
From source file:edu.usu.sdl.openstorefront.service.ComponentServiceImpl.java
@Override public void processComponentUpdates() { ReentrantLock lock = new ReentrantLock(); lock.lock(); try {/* w w w. jav a 2 s. c om*/ ComponentUpdateQueue updateQueueExample = new ComponentUpdateQueue(); updateQueueExample.setNodeId(PropertiesManager.getNodeName()); List<ComponentUpdateQueue> componentUpdateQueues = persistenceService .queryByExample(ComponentUpdateQueue.class, updateQueueExample); if (componentUpdateQueues.isEmpty() == false) { //Get the latest entries Map<String, ComponentUpdateQueue> componentMap = new HashMap<>(); for (ComponentUpdateQueue updateQueue : componentUpdateQueues) { if (componentMap.containsKey(updateQueue.getUpdateId())) { ComponentUpdateQueue existing = componentMap.get(updateQueue.getUpdateId()); if (existing.getUpdateDts().before(updateQueue.getUpdateDts())) { componentMap.put(updateQueue.getUpdateId(), updateQueue); } } else { componentMap.put(updateQueue.getUpdateId(), updateQueue); } } List<Component> componentsToIndex = new ArrayList<>(); for (ComponentUpdateQueue componentUpdate : componentMap.values()) { String componentId = componentUpdate.getComponentId(); Component component = persistenceService.findById(Component.class, componentId); if (component != null) { component.setLastActivityDts(componentUpdate.getUpdateDts()); persistenceService.persist(component); getUserService().checkComponentWatches(component); componentsToIndex.add(component); } else { log.log(Level.FINE, "Component not found to update last Activity. Component may have been removed.", "Check component Id: " + componentId); } } getSearchService().indexComponents(componentsToIndex); //remove processed records for (ComponentUpdateQueue updateQueue : componentUpdateQueues) { ComponentUpdateQueue componentUpdateQueue = persistenceService .findById(ComponentUpdateQueue.class, updateQueue.getUpdateId()); if (componentUpdateQueue != null) { persistenceService.delete(componentUpdateQueue); } } } } finally { lock.unlock(); } }
From source file:org.apache.hadoop.hive.ql.Driver.java
/** * Acquires the compile lock. If the compile lock wait timeout is configured, * it will acquire the lock if it is not held by another thread within the given * waiting time./*from ww w .j a v a2s .co m*/ * @return the ReentrantLock object if the lock was successfully acquired, * or {@code null} if compile lock wait timeout is configured and * either the waiting time elapsed before the lock could be acquired * or if the current thread is interrupted. */ private ReentrantLock tryAcquireCompileLock(boolean isParallelEnabled, String command) { final ReentrantLock compileLock = isParallelEnabled ? SessionState.get().getCompileLock() : globalCompileLock; long maxCompileLockWaitTime = HiveConf.getTimeVar(this.conf, ConfVars.HIVE_SERVER2_COMPILE_LOCK_TIMEOUT, TimeUnit.SECONDS); final String lockAcquiredMsg = "Acquired the compile lock."; // First shot without waiting. try { if (compileLock.tryLock(0, TimeUnit.SECONDS)) { LOG.debug(lockAcquiredMsg); return compileLock; } } catch (InterruptedException e) { Thread.currentThread().interrupt(); if (LOG.isDebugEnabled()) { LOG.debug("Interrupted Exception ignored", e); } return null; } // If the first shot fails, then we log the waiting messages. if (LOG.isDebugEnabled()) { LOG.debug("Waiting to acquire compile lock: " + command); } if (maxCompileLockWaitTime > 0) { try { if (!compileLock.tryLock(maxCompileLockWaitTime, TimeUnit.SECONDS)) { errorMessage = ErrorMsg.COMPILE_LOCK_TIMED_OUT.getErrorCodedMsg(); LOG.error(errorMessage + ": " + command); return null; } } catch (InterruptedException e) { Thread.currentThread().interrupt(); if (LOG.isDebugEnabled()) { LOG.debug("Interrupted Exception ignored", e); } return null; } } else { compileLock.lock(); } LOG.debug(lockAcquiredMsg); return compileLock; }
From source file:la2launcher.MainFrame.java
private void jButton9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton9ActionPerformed final long initTime = new Date().getTime(); ReentrantLock lock = new ReentrantLock(); final String patcherUrl = "http://" + updateHost + "/hf//updater.lst.la2";//new ArrayBlockingQueue<Runnable>(10000) final ThreadPoolExecutor tpe = new ThreadPoolExecutor(5, 5, 1, TimeUnit.HOURS, new ArrayBlockingQueue<Runnable>(10000)); filesProcessed = 0;//from w w w .j av a 2 s . c om tpe.execute(new Runnable() { @Override public void run() { jTextArea2.setText(""); DefaultTableModel model = (DefaultTableModel) jTable2.getModel(); jProgressBar1.setMinimum(0); jProgressBar1.setMaximum(model.getRowCount()); jProgressBar1.setValue(0); jLabel4.setText("0/" + model.getRowCount()); for (int i = 0; i < model.getRowCount(); i++) { boolean checked = (Boolean) model.getValueAt(i, 1); String fileName = (String) model.getValueAt(i, 0); if (checked) { tpe.execute(new Runnable() { @Override public void run() { final String fileUrl = "http://" + updateHost + "/hf/" + fileName.replace("\\", "/") + ".la2"; try { printMsg(" " + fileUrl); File file = new File(gamePath + fileName + ".rar"); File fileExt = new File(gamePath + fileName); file.getParentFile().mkdirs(); FileOutputStream fos = new FileOutputStream(file); CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet(fileUrl); CloseableHttpResponse response1 = httpclient.execute(httpGet); HttpEntity entity1 = response1.getEntity(); copyStream(entity1.getContent(), fos, new CopyListener() { @Override public void transfered(int n) { bytesRecieved += n; bytesRecievedTotal += n; } }); response1.close(); fos.close(); printMsg("?? : " + fileName); lock.lock(); //fixBzip2File(file); //printMsg(" ?"); extractArchive(file.getAbsolutePath()); //BZip2CompressorInputStream bz = new BZip2CompressorInputStream(new FileInputStream(file)); //OutputStream pout = new FileOutputStream(fileExt); //copyStream(archStream, pout, null); //pout.close(); //archStream.close(); //jTextArea2.setText(jTextArea2.getText() + "\r\n? : " + fileName); printMsg("? : " + fileName); //file.delete(); // File tgt = new File(gamePath + fileName); // if (tgt.exists()) { // tgt.delete(); // } //tgt.getParentFile().mkdirs(); //Files.move(fileExt.toPath(), new File(gamePath + fileName).toPath()); //jTextArea2.setText(jTextArea2.getText() + "\r\n ??: " + fileName); printMsg(" ??: " + fileName); jProgressBar1.setIndeterminate(false); jLabel4.setText((++filesProcessed) + "/" + model.getRowCount()); jProgressBar1.setValue((int) filesProcessed); lock.unlock(); } catch (IOException ex) { Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex); } } }); } } } }); jButton5.setEnabled(false); jButton6.setEnabled(false); jButton7.setEnabled(false); jButton8.setEnabled(false); jButton9.setEnabled(false); jButton10.setEnabled(false); jProgressBar1.setIndeterminate(true); new Thread() { @Override public void run() { do { long millis = new Date().getTime(); try { sleep(300); } catch (InterruptedException ex) { Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex); } millis = new Date().getTime() - millis; BigDecimal totBig = new BigDecimal(bytesRecievedTotal / (1024 * 1024.0)); totBig = totBig.setScale(2, BigDecimal.ROUND_CEILING); jLabel5.setText("?: " + (bytesRecieved / millis) + "KB/s. : " + totBig + " MB"); bytesRecieved = 0; } while (tpe.getActiveCount() > 0); tpe.shutdown(); jButton5.setEnabled(true); jButton6.setEnabled(true); jButton7.setEnabled(true); jButton8.setEnabled(true); jButton9.setEnabled(true); jButton10.setEnabled(true); jProgressBar1.setIndeterminate(false); printMsg(" " + (new Date().getTime() - initTime) + " ?."); } }.start(); }