List of usage examples for java.util.concurrent.locks ReentrantLock unlock
public void 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 ww w.ja va2s .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:ir.rasen.charsoo.controller.image_loader.core.LoadAndDisplayImageTask.java
@Override public void run() { if (waitIfPaused()) return;/*from w w w.ja va2s . c om*/ if (delayIfNeed()) return; ReentrantLock loadFromUriLock = imageLoadingInfo.loadFromUriLock; L.d(LOG_START_DISPLAY_IMAGE_TASK, memoryCacheKey); if (loadFromUriLock.isLocked()) { L.d(LOG_WAITING_FOR_IMAGE_LOADED, memoryCacheKey); } loadFromUriLock.lock(); Bitmap bmp; try { checkTaskNotActual(); bmp = configuration.memoryCache.get(memoryCacheKey); if (bmp == null || bmp.isRecycled()) { bmp = tryLoadBitmap(); if (bmp == null) return; // listener callback already was fired checkTaskNotActual(); checkTaskInterrupted(); if (options.shouldPreProcess()) { L.d(LOG_PREPROCESS_IMAGE, memoryCacheKey); bmp = options.getPreProcessor().process(bmp); if (bmp == null) { L.e(ERROR_PRE_PROCESSOR_NULL, memoryCacheKey); } } if (bmp != null && options.isCacheInMemory()) { L.d(LOG_CACHE_IMAGE_IN_MEMORY, memoryCacheKey); configuration.memoryCache.put(memoryCacheKey, bmp); } } else { loadedFrom = LoadedFrom.MEMORY_CACHE; L.d(LOG_GET_IMAGE_FROM_MEMORY_CACHE_AFTER_WAITING, memoryCacheKey); } if (bmp != null && options.shouldPostProcess()) { L.d(LOG_POSTPROCESS_IMAGE, memoryCacheKey); bmp = options.getPostProcessor().process(bmp); if (bmp == null) { L.e(ERROR_POST_PROCESSOR_NULL, memoryCacheKey); } } checkTaskNotActual(); checkTaskInterrupted(); } catch (TaskCancelledException e) { fireCancelEvent(); return; } finally { loadFromUriLock.unlock(); } DisplayBitmapTask displayBitmapTask = new DisplayBitmapTask(bmp, imageLoadingInfo, engine, loadedFrom); runTask(displayBitmapTask, syncLoading, handler, engine); }
From source file:org.apache.openejb.resource.jdbc.dbcp.BasicDataSource.java
protected DataSource createDataSource() throws SQLException { final ReentrantLock l = lock; l.lock();/*from www.j ava 2 s . com*/ try { if (super.dataSource != null) { return super.dataSource; } // check password codec if available if (null != passwordCipher) { final PasswordCipher cipher = PasswordCipherFactory.getPasswordCipher(passwordCipher); final String plainPwd = cipher.decrypt(password.toCharArray()); // override previous password value super.setPassword(plainPwd); } // get the plugin final DataSourcePlugin helper = BasicDataSourceUtil.getDataSourcePlugin(getUrl()); // configure this if (helper != null) { final String currentUrl = getUrl(); final String newUrl = helper.updatedUrl(currentUrl); if (!currentUrl.equals(newUrl)) { super.setUrl(newUrl); } } // create the data source if (helper == null || !helper.enableUserDirHack()) { try { return super.createDataSource(); } catch (final Throwable e) { throw toSQLException(e); } } else { // wrap super call with code that sets user.dir to openejb.base and then resets it final Properties systemProperties = System.getProperties(); final String userDir = systemProperties.getProperty("user.dir"); try { final File base = SystemInstance.get().getBase().getDirectory(); systemProperties.setProperty("user.dir", base.getAbsolutePath()); try { return super.createDataSource(); } catch (final Throwable e) { throw toSQLException(e); } } finally { systemProperties.setProperty("user.dir", userDir); } } } finally { l.unlock(); } }
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()); //// www .ja va 2 s . 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.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. *//* ww w .j a v a 2 s .co 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.openejb.resource.jdbc.dbcp.BasicManagedDataSource.java
protected DataSource createDataSource() throws SQLException { final ReentrantLock l = lock; l.lock();//from ww w. ja v a 2 s . c o m try { if (super.dataSource != null) { return super.dataSource; } // check password codec if available if (null != passwordCipher) { final PasswordCipher cipher = PasswordCipherFactory.getPasswordCipher(passwordCipher); final String plainPwd = cipher.decrypt(password.toCharArray()); // override previous password value super.setPassword(plainPwd); } // get the plugin final DataSourcePlugin helper = BasicDataSourceUtil.getDataSourcePlugin(getUrl()); // configure this if (helper != null) { final String currentUrl = getUrl(); final String newUrl = helper.updatedUrl(currentUrl); if (!currentUrl.equals(newUrl)) { super.setUrl(newUrl); } } wrapTransactionManager(); // create the data source if (helper == null || !helper.enableUserDirHack()) { try { return super.createDataSource(); } catch (final Throwable e) { throw BasicDataSource.toSQLException(e); } } else { // wrap super call with code that sets user.dir to openejb.base and then resets it final Properties systemProperties = System.getProperties(); final String userDir = systemProperties.getProperty("user.dir"); try { final File base = SystemInstance.get().getBase().getDirectory(); systemProperties.setProperty("user.dir", base.getAbsolutePath()); try { return super.createDataSource(); } catch (final Throwable e) { throw BasicDataSource.toSQLException(e); } } finally { systemProperties.setProperty("user.dir", userDir); } } } finally { l.unlock(); } }
From source file:org.openanzo.datasource.nodecentric.internal.NodeCentricDatasource.java
/** * Begin database transaction/*from w w w . j av a 2 s. 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:org.alfresco.repo.workflow.WorkflowReportServiceImpl.java
/** * Gets the root space for tasks - under system node. * * @return the task space initialized lazy */// ww w.j a v a 2 s. 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:me.xiaopan.sketch.download.HttpClientImageDownloader.java
@Override public DownloadResult download(DownloadRequest request) { // ?????/*ww w .j av a2 s. c om*/ request.setRequestStatus(RequestStatus.GET_DOWNLOAD_LOCK); ReentrantLock urlLock = getUrlLock(request.getUri()); urlLock.lock(); request.setRequestStatus(RequestStatus.DOWNLOADING); DownloadResult result = null; int number = 0; while (true) { // ??? if (request.isCanceled()) { if (Sketch.isDebugMode()) { Log.w(Sketch.TAG, SketchUtils.concat(NAME, " - ", "canceled", " - ", "get lock after", " - ", request.getName())); } break; } // ? if (request.isCacheInDisk()) { File cacheFile = request.getSketch().getConfiguration().getDiskCache() .getCacheFile(request.getUri()); if (cacheFile != null && cacheFile.exists()) { result = DownloadResult.createByFile(cacheFile, false); break; } } try { result = realDownload(request); break; } catch (Throwable e) { boolean retry = (e instanceof SocketTimeoutException || e instanceof InterruptedIOException) && number < maxRetryCount; if (retry) { number++; if (Sketch.isDebugMode()) { Log.w(Sketch.TAG, SketchUtils.concat(NAME, " - ", "download failed", " - ", "retry", " - ", request.getName())); } } else { if (Sketch.isDebugMode()) { Log.e(Sketch.TAG, SketchUtils.concat(NAME, " - ", "download failed", " - ", "end", " - ", request.getName())); } } e.printStackTrace(); if (!retry) { break; } } } // ? urlLock.unlock(); return result; }
From source file:org.alfresco.repo.workflow.WorkflowReportServiceImpl.java
@Override public void updateTask(final WorkflowTask updatedTask) { if (!isEnabled()) { return;//from ww w .j a v a2 s.c o m } 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(); } }