List of usage examples for java.util.concurrent.locks ReentrantLock lock
public void lock()
From source file:org.alfresco.repo.workflow.WorkflowReportServiceImpl.java
/** * Invoked on delete event. Not implemented yet * * @param workflowId//from w ww .ja va 2 s. c o m * is the workflow id */ @Override public void deleteWorkflow(final String workflowId) { if (!isEnabled()) { return; } ReentrantLock acquiredLock = acquireLock(CMFService.getTenantId()); acquiredLock.lock(); try { AuthenticationUtil.runAs(new RunAsWork<Void>() { @Override public Void doWork() throws Exception { try { List<WorkflowPath> workflowById = workflowService.getWorkflowPaths(workflowId); for (WorkflowPath workflowPath : workflowById) { List<WorkflowTask> tasksForWorkflowPath = workflowService .getTasksForWorkflowPath(workflowPath.getId()); for (WorkflowTask workflowTask : tasksForWorkflowPath) { deleteTask(workflowTask); } } } catch (Exception e) { // just print and skip so not to break alfresco code LOGGER.error(e); } return null; } }, CMFService.getSystemUser()); } catch (Exception e) { LOGGER.error(e); } finally { acquiredLock.unlock(); } }
From source file:org.apache.hadoop.net.unix.TestDomainSocketWatcher.java
@Test(timeout = 300000) public void testStressInterruption() throws Exception { final int SOCKET_NUM = 250; final ReentrantLock lock = new ReentrantLock(); final DomainSocketWatcher watcher = newDomainSocketWatcher(10); final ArrayList<DomainSocket[]> pairs = new ArrayList<DomainSocket[]>(); final AtomicInteger handled = new AtomicInteger(0); final Thread adderThread = new Thread(new Runnable() { @Override/* w ww . j a v a 2s.c om*/ public void run() { try { for (int i = 0; i < SOCKET_NUM; i++) { DomainSocket pair[] = DomainSocket.socketpair(); watcher.add(pair[1], new DomainSocketWatcher.Handler() { @Override public boolean handle(DomainSocket sock) { handled.incrementAndGet(); return true; } }); lock.lock(); try { pairs.add(pair); } finally { lock.unlock(); } TimeUnit.MILLISECONDS.sleep(1); } } catch (Throwable e) { LOG.error(e); throw new RuntimeException(e); } } }); final Thread removerThread = new Thread(new Runnable() { @Override public void run() { final Random random = new Random(); try { while (handled.get() != SOCKET_NUM) { lock.lock(); try { if (!pairs.isEmpty()) { int idx = random.nextInt(pairs.size()); DomainSocket pair[] = pairs.remove(idx); if (random.nextBoolean()) { pair[0].close(); } else { watcher.remove(pair[1]); } TimeUnit.MILLISECONDS.sleep(1); } } finally { lock.unlock(); } } } catch (Throwable e) { LOG.error(e); throw new RuntimeException(e); } } }); adderThread.start(); removerThread.start(); TimeUnit.MILLISECONDS.sleep(100); watcher.watcherThread.interrupt(); Uninterruptibles.joinUninterruptibly(adderThread); Uninterruptibles.joinUninterruptibly(removerThread); Uninterruptibles.joinUninterruptibly(watcher.watcherThread); }
From source file:org.alfresco.repo.workflow.WorkflowReportServiceImpl.java
/** * Gets the root space for tasks - under system node. * * @return the task space initialized lazy *///from w w w . ja v a 2s. c o m private NodeRef getTaskSpace() { String tenantId = CMFService.getTenantId(); NodeRef taskSpaceNode = taskSpaceNodes.get(tenantId); if (taskSpaceNode != null) { return taskSpaceNode; } ReentrantLock acquiredLock = acquireLock(CMFService.getTenantId()); acquiredLock.lock(); try { // for optimization lock here and check the node again taskSpaceNode = taskSpaceNodes.get(tenantId); if (taskSpaceNode != null) { return taskSpaceNode; } List<ChildAssociationRef> childAssocs = nodeService.getChildAssocs(repository.getRootHome()); NodeRef systemNode = null; for (ChildAssociationRef childAssociationRef : childAssocs) { if (CMFModel.SYSTEM_QNAME.equals(childAssociationRef.getQName())) { systemNode = childAssociationRef.getChildRef(); break; } } taskSpaceNode = getChildContainerByName(systemNode, WorkflowReportConstants.TASK_SPACE_ID); if (taskSpaceNode == null) { taskSpaceNode = createNode(systemNode, QName.createQName(CMFModel.CMF_WORKFLOW_MODEL_1_0_URI, WorkflowReportConstants.TASK_SPACE_ID), ContentModel.ASSOC_CHILDREN, ContentModel.TYPE_FOLDER); } taskSpaceNodes.put(tenantId, taskSpaceNode); return taskSpaceNode; } catch (Exception e) { LOGGER.error(e); } finally { acquiredLock.unlock(); } return null; }
From source file:org.apache.hadoop.net.unix.TestDomainSocketWatcher.java
@Test(timeout = 300000) public void testStress() throws Exception { final int SOCKET_NUM = 250; final ReentrantLock lock = new ReentrantLock(); final DomainSocketWatcher watcher = newDomainSocketWatcher(10000000); final ArrayList<DomainSocket[]> pairs = new ArrayList<DomainSocket[]>(); final AtomicInteger handled = new AtomicInteger(0); final Thread adderThread = new Thread(new Runnable() { @Override/*from w ww . j a v a2 s. co m*/ public void run() { try { for (int i = 0; i < SOCKET_NUM; i++) { DomainSocket pair[] = DomainSocket.socketpair(); watcher.add(pair[1], new DomainSocketWatcher.Handler() { @Override public boolean handle(DomainSocket sock) { handled.incrementAndGet(); return true; } }); lock.lock(); try { pairs.add(pair); } finally { lock.unlock(); } } } catch (Throwable e) { LOG.error(e); throw new RuntimeException(e); } } }); final Thread removerThread = new Thread(new Runnable() { @Override public void run() { final Random random = new Random(); try { while (handled.get() != SOCKET_NUM) { lock.lock(); try { if (!pairs.isEmpty()) { int idx = random.nextInt(pairs.size()); DomainSocket pair[] = pairs.remove(idx); if (random.nextBoolean()) { pair[0].close(); } else { watcher.remove(pair[1]); } } } finally { lock.unlock(); } } } catch (Throwable e) { LOG.error(e); throw new RuntimeException(e); } } }); adderThread.start(); removerThread.start(); Uninterruptibles.joinUninterruptibly(adderThread); Uninterruptibles.joinUninterruptibly(removerThread); watcher.close(); }
From source file:org.alfresco.repo.workflow.WorkflowReportServiceImpl.java
@Override public void updateTask(final WorkflowTask updatedTask) { if (!isEnabled()) { return;/* www . j a v a2 s .c om*/ } if (DEBUG_ENABLED) { LOGGER.debug("UPDATE TASK (task) " + updatedTask.getId()); } ReentrantLock acquiredLock = acquireLock(CMFService.getTenantId()); acquiredLock.lock(); try { AuthenticationUtil.runAs(new RunAsWork<Void>() { @Override public Void doWork() throws Exception { final String id = updatedTask.getId(); if (!taskCache.contains(id)) { ResultSet query = registry.getSearchService().query( StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, SearchService.LANGUAGE_SOLR_FTS_ALFRESCO, buildTaskQuery(updatedTask)); List<NodeRef> nodeRefs = query.getNodeRefs(); if ((nodeRefs == null) || nodeRefs.isEmpty()) { addTaskInternal(updatedTask); } else { nodeService.addProperties(nodeRefs.get(0), extractTaskProperties(updatedTask)); } query = null; } else { nodeService.addProperties(taskCache.get(id), extractTaskProperties(updatedTask)); } return null; } }, CMFService.getSystemUser()); } catch (Exception e) { // just print and skip LOGGER.error(e); } finally { acquiredLock.unlock(); } }
From source file:org.alfresco.repo.workflow.WorkflowReportServiceImpl.java
/** * Creates new task if not exists - this method will process work only as * last resort./*from w ww . j a v a 2 s . co m*/ * * @param createdTask * is the task to process */ @Override public void createIfNotExists(final WorkflowTask createdTask) { if (!isEnabled()) { return; } if (checkTaskIfExists(createdTask)) { return; } ReentrantLock acquiredLock = acquireLock(CMFService.getTenantId()); // use the same lock as in write mode acquiredLock.lock(); try { // check again after lock of this node because of thread issues if (checkTaskIfExists(createdTask)) { return; } if (DEBUG_ENABLED) { LOGGER.debug("WILL CREATE TASK (task) " + createdTask.getId()); } AuthenticationUtil.runAs(new RunAsWork<Void>() { @Override public Void doWork() throws Exception { ResultSet query = registry.getSearchService().query(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, SearchService.LANGUAGE_SOLR_FTS_ALFRESCO, buildTaskQuery(createdTask)); List<NodeRef> nodeRefs = query.getNodeRefs(); if ((nodeRefs == null) || nodeRefs.isEmpty()) { addTaskInternal(createdTask); } query = null; return null; } }, CMFService.getSystemUser()); } catch (Exception e) { LOGGER.error(e); } finally { acquiredLock.unlock(); } }
From source file:de.dkfz.roddy.client.fxuiclient.RoddyUIController.java
/** * Check and (re-)open / get an (active) rmi server + connection * * @return/*w ww . ja v a 2 s . com*/ */ public RoddyRMIClientConnection getRMIConnection(String analysis) { if (RoddyConversionHelperMethods.isNullOrEmpty(analysis) && !analysis.contains("::")) System.err.println( "Malformed analysis " + analysis + " for getRMIConnection(), needs to be fully specified."); List<String> dissected = ProjectFactory.dissectFullAnalysisID(analysis); String pluginID = dissected.get(0); String shortAnalysisId = analysis.split("[:][:]")[0]; ReentrantLock myLock = null; synchronized (rmiLocks) { if (!rmiLocks.containsKey(pluginID)) { rmiLocks.put(pluginID, new ReentrantLock()); } myLock = rmiLocks.get(pluginID); } RoddyRMIClientConnection connection = null; logger.postAlwaysInfo("Locking for " + analysis); myLock.lock(); try { if (!rmiConnectionPool.containsKey(pluginID) || !rmiConnectionPool.get(pluginID).pingServer()) { logger.postAlwaysInfo("Creating connection for " + analysis); RoddyRMIClientConnection clientConnection = new RoddyRMIClientConnection(); clientConnection.startLocalRoddyRMIServerAndConnect(currentIniFile.getAbsolutePath(), currentProjectWrapper.getName(), shortAnalysisId); rmiConnectionPool.put(pluginID, clientConnection); } logger.postAlwaysInfo("Retrieving connection for " + analysis); connection = rmiConnectionPool.get(pluginID); } finally { myLock.unlock(); } return connection; }
From source file:org.exoplatform.social.core.storage.impl.ActivityStreamStorageImpl.java
private void manageRefList(UpdateContext context, ActivityEntity activityEntity, ActivityRefType type, boolean mustCheck) throws NodeNotFoundException { AtomicBoolean newYearMonthday = new AtomicBoolean(false); if (context.getAdded() != null) { for (Identity identity : context.getAdded()) { IdentityEntity identityEntity = identityStorage._findIdentityEntity(identity.getProviderId(), identity.getRemoteId()); ///* ww w. j a va 2s.c o m*/ if (mustCheck) { //to avoid add back activity to given stream what has already existing if (isExistingActivityRef(identityEntity, activityEntity)) continue; } ActivityRefListEntity listRef = type.refsOf(identityEntity); //keep number Integer oldNumberOfStream = listRef.getNumber(); newYearMonthday.set(false); ActivityRef ref = null; //Take care the YearMonthDay path don't throw ADD_PROPERTY exception. final ReentrantLock lock = new ReentrantLock(); try { lock.lock(); newYearMonthday.set(false); ref = listRef.getOrCreated(activityEntity, newYearMonthday); if (newYearMonthday.get()) { StorageUtils.persist(); } } catch (ChromatticException ex) { Throwable throwable = ex.getCause(); if (throwable instanceof ItemExistsException || throwable instanceof InvalidItemStateException || throwable instanceof PathNotFoundException) { LOG.warn("Probably YearMonthDay path was created by another session"); LOG.debug(ex.getMessage(), ex); } else { LOG.warn("Probably YearMonthDay path was created by another session", ex); LOG.debug(ex.getMessage(), ex); } return; } finally { lock.unlock(); } //LOG.info("manageRefList()::BEFORE"); //printDebug(listRef, activityEntity.getLastUpdated()); if (ref.getName() == null) { ref.setName(activityEntity.getName()); } if (ref.getLastUpdated() == null) { ref.setLastUpdated(activityEntity.getLastUpdated()); } ref.setActivityEntity(activityEntity); Integer newNumberOfStream = listRef.getNumber(); //If activity is hidden, we must decrease the number of activity references HidableEntity hidableActivity = _getMixin(activityEntity, HidableEntity.class, true); if (hidableActivity.getHidden() && (newNumberOfStream > oldNumberOfStream)) { ref.getDay().desc(); } //LOG.info("manageRefList()::AFTER"); //printDebug(listRef, activityEntity.getLastUpdated()); } } if (context.getRemoved() != null) { for (Identity identity : context.getRemoved()) { IdentityEntity identityEntity = identityStorage._findIdentityEntity(identity.getProviderId(), identity.getRemoteId()); ActivityRefListEntity listRef = type.refsOf(identityEntity); listRef.remove(activityEntity); } } }
From source file:org.apache.hadoop.hbase.master.procedure.MasterProcedureScheduler.java
/** * Tries to remove the queue and the table-lock of the specified table. * If there are new operations pending (e.g. a new create), * the remove will not be performed./*from www. jav a2 s. c o m*/ * @param table the name of the table that should be marked as deleted * @return true if deletion succeeded, false otherwise meaning that there are * other new operations pending for that table (e.g. a new create). */ protected boolean markTableAsDeleted(final TableName table) { final ReentrantLock l = schedLock; l.lock(); try { TableQueue queue = getTableQueue(table); if (queue == null) return true; if (queue.isEmpty() && queue.tryExclusiveLock(0)) { // remove the table from the run-queue and the map if (IterableList.isLinked(queue)) { tableRunQueue.remove(queue); } // Remove the table lock try { lockManager.tableDeleted(table); } catch (IOException e) { LOG.warn("Received exception from TableLockManager.tableDeleted:", e); //not critical } removeTableQueue(table); } else { // TODO: If there are no create, we can drop all the other ops return false; } } finally { l.unlock(); } return true; }
From source file:smanilov.mandelbrot.compute.Computer.java
/** * Creates a thread that draws points from the toDoList. * @param width The maximum x coordinate. * @param height The maximum y coordinate. * @return/*w w w . j av a2 s. c om*/ */ private static Thread createShaderThread(final Image drawing, final Color foregroundColor, final Color backgroundColor, final ReentrantLock drawingLock, final int scale, final Point2D center) { Thread shaderThread = new Thread() { @Override public void run() { System.out.println("Shader: [START]"); int id = currentDrawingId; int currentIterations = iterations; super.run(); int width = drawing.getWidth(null); int height = drawing.getHeight(null); Point pixelCenter = new Point(width / 2, height / 2); while (active) { // TODO: remove busy-wait while (true) { queueLock.lock(); if (toDoList.size() == 0) { queueLock.unlock(); break; } Point p = toDoList.poll(); int i = p.x; int j = p.y; queueLock.unlock(); double k = 0; double aliasInterval = 1.0 / antiAliasing; for (int aliasx = 0; aliasx < antiAliasing; ++aliasx) { for (int aliasy = 0; aliasy < antiAliasing; ++aliasy) { double x = i - 0.5 + aliasInterval / 2 + aliasInterval * aliasx; double y = j - 0.5 + aliasInterval / 2 + aliasInterval * aliasy; Complex c = toComplex(x, y, pixelCenter, scale, center); Complex z = new Complex(c.getReal(), c.getImaginary()); k += 1.0; for (int aliask = 1; aliask < currentIterations; ++aliask, k += 1.0) { if (id != currentDrawingId) return; z = z.multiply(z).add(c); if (z.abs() > 2) break; } } } k /= antiAliasing * antiAliasing; if (Math.ceil(k) == currentIterations) { drawingLock.lock(); Graphics g = drawing.getGraphics(); Color color = mixColors(foregroundColor, backgroundColor, k + 1 - currentIterations); g.setColor(color); g.fillRect(i, j, 1, 1); drawingLock.unlock(); } else { drawingLock.lock(); Graphics g = drawing.getGraphics(); Color color = mixColors(backgroundColor, foregroundColor, (double) k / currentIterations); g.setColor(color); g.fillRect(i, j, 1, 1); drawingLock.unlock(); } nDrawnLock.lock(); ++nDrawn; nDrawnLock.unlock(); } } long interval = System.currentTimeMillis() - startTime; System.out.println("Shader: [END after " + interval + " ms]"); saveImage(drawing, drawingLock); } }; return shaderThread; }