List of usage examples for java.util.concurrent.locks ReentrantLock unlock
public void 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//from w w w. ja v a 2 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(); } 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.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// w w w . j a v a2s . 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(); } } } 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:me.xiaopan.android.gohttp.HttpRequestHandler.java
@Override public void run() { if (httpRequest.isCanceled()) { httpRequest.finish();/*from www .j a v a2 s. com*/ new CancelRunnable(httpRequest).execute(); if (httpRequest.getGoHttp().isDebugMode()) Log.w(GoHttp.LOG_TAG, httpRequest.getName() + "; " + "Canceled : " + "; " + httpRequest.getUrl()); return; } if (httpRequest.getGoHttp().isDebugMode()) Log.d(GoHttp.LOG_TAG, httpRequest.getName() + "; " + "Started : " + "; " + httpRequest.getUrl()); boolean isCache = httpRequest.getCacheConfig() != null; ReentrantLock reentrantLock = null; if (isCache) { reentrantLock = httpRequest.getGoHttp().getSyncManager() .getLockByCacheId(httpRequest.getCacheConfig().getId()); reentrantLock.lock(); if (httpRequest.isCanceled()) { httpRequest.finish(); new CancelRunnable(httpRequest).execute(); if (httpRequest.getGoHttp().isDebugMode()) Log.w(GoHttp.LOG_TAG, httpRequest.getName() + "; " + "Canceled : ??" + "; " + httpRequest.getUrl()); reentrantLock.unlock(); return; } } boolean isRefreshCache = isCache && httpRequest.getCacheConfig().isRefreshCache(); boolean isContinueCallback = true; HttpResponse httpResponse = null; // ?? if (isCache && httpRequest.getGoHttp().getCacheManager().isHasAvailableCache(httpRequest)) { if (httpRequest.isCanceled()) { httpRequest.finish(); new CancelRunnable(httpRequest).execute(); if (httpRequest.getGoHttp().isDebugMode()) Log.w(GoHttp.LOG_TAG, httpRequest.getName() + "; " + "Canceled : ?" + "; " + httpRequest.getUrl()); reentrantLock.unlock(); return; } if (httpRequest.getGoHttp().isDebugMode()) Log.d(GoHttp.LOG_TAG, httpRequest.getName() + "; " + "Cache : ?" + "; " + httpRequest.getUrl()); // ?Http? httpResponse = httpRequest.getGoHttp().getCacheManager().readHttpResponseFromCache(httpRequest); if (httpRequest.isCanceled()) { httpRequest.finish(); new CancelRunnable(httpRequest).execute(); if (httpRequest.getGoHttp().isDebugMode()) Log.w(GoHttp.LOG_TAG, httpRequest.getName() + "; " + "Canceled : ?" + "; " + httpRequest.getUrl()); reentrantLock.unlock(); return; } if (httpResponse != null) { try { Object responseObject = httpRequest.getResponseHandler().handleResponse(httpRequest, httpResponse); if (responseObject == null) { throw new Exception("response object is null"); } // ??? isContinueCallback = isRefreshCache && httpRequest.getCacheConfig().isRefreshCallback(); if (!(responseObject instanceof HttpRequest.Failure) && httpRequest.getResponseHandleCompletedAfterListener() != null) { //noinspection unchecked Object response = httpRequest.getResponseHandleCompletedAfterListener() .onResponseHandleAfter(httpRequest, httpResponse, responseObject, true, isContinueCallback); if (response != null) { responseObject = response; } } if (httpRequest.isCanceled()) { httpRequest.finish(); new CancelRunnable(httpRequest).execute(); if (httpRequest.getGoHttp().isDebugMode()) Log.w(GoHttp.LOG_TAG, httpRequest.getName() + "; " + "Canceled : ??" + "; " + httpRequest.getUrl()); reentrantLock.unlock(); return; } // ????? if (!isRefreshCache) { httpRequest.finish(); } if (responseObject instanceof HttpRequest.Failure) { new FailedRunnable(httpRequest, httpResponse, (HttpRequest.Failure) responseObject, true, isContinueCallback).execute(); } else { new CompletedRunnable(httpRequest, httpResponse, responseObject, true, isContinueCallback) .execute(); } // ????? if (!isRefreshCache) { if (httpRequest.getGoHttp().isDebugMode()) Log.d(GoHttp.LOG_TAG, httpRequest.getName() + "; " + "Completed : ???" + "; " + httpRequest.getUrl()); reentrantLock.unlock(); return; } if (httpRequest.getGoHttp().isDebugMode()) Log.d(GoHttp.LOG_TAG, httpRequest.getName() + "; " + "Cache : ??" + "; " + httpRequest.getUrl()); } catch (Throwable e) { e.printStackTrace(); if (httpRequest.isCanceled()) { httpRequest.finish(); new CancelRunnable(httpRequest).execute(); if (httpRequest.getGoHttp().isDebugMode()) Log.w(GoHttp.LOG_TAG, httpRequest.getName() + "; " + "Canceled : ?Http??" + "; " + httpRequest.getUrl()); reentrantLock.unlock(); return; } if (httpRequest.getGoHttp().isDebugMode()) Log.e(GoHttp.LOG_TAG, httpRequest.getName() + "; " + "Failed : ?Http??" + "; " + httpRequest.getUrl()); new FailedRunnable(httpRequest, httpResponse, new HttpRequest.Failure(e), true, isContinueCallback).execute(); } } } // ?? try { httpResponse = httpRequest.getGoHttp().getNetManager().getHttpResponse(httpRequest); } catch (Throwable e) { e.printStackTrace(); releaseConnect(httpResponse); httpRequest.finish(); if (httpRequest.isCanceled()) { if (isContinueCallback) { new CancelRunnable(httpRequest).execute(); } if (httpRequest.getGoHttp().isDebugMode()) Log.w(GoHttp.LOG_TAG, httpRequest.getName() + "; " + "Canceled : ?Http??" + "; " + httpRequest.getUrl()); if (reentrantLock != null) reentrantLock.unlock(); return; } if (httpRequest.getGoHttp().isDebugMode()) Log.e(GoHttp.LOG_TAG, httpRequest.getName() + "; " + "Failed : ?Http??" + "; " + httpRequest.getUrl()); if (isContinueCallback) { new FailedRunnable(httpRequest, httpResponse, new HttpRequest.Failure(e), false, false).execute(); } if (reentrantLock != null) reentrantLock.unlock(); return; } if (httpRequest.isCanceled()) { releaseConnect(httpResponse); httpRequest.finish(); new CancelRunnable(httpRequest).execute(); if (httpRequest.getGoHttp().isDebugMode()) Log.w(GoHttp.LOG_TAG, httpRequest.getName() + "; " + "Canceled : ?Http?" + "; " + httpRequest.getUrl()); if (reentrantLock != null) reentrantLock.unlock(); return; } if (httpRequest.getGoHttp().isDebugMode()) Log.d(GoHttp.LOG_TAG, httpRequest.getName() + "; " + "Net : ?Http??" + "; " + httpRequest.getUrl()); // Http? if (isCache && httpRequest.getResponseHandler().canCache(httpResponse)) { try { httpRequest.getGoHttp().getCacheManager().saveHttpResponseToCache(httpRequest, httpResponse); } catch (IOException e) { e.printStackTrace(); releaseConnect(httpResponse); httpRequest.finish(); if (httpRequest.isCanceled()) { if (isContinueCallback) { new CancelRunnable(httpRequest).execute(); } if (httpRequest.getGoHttp().isDebugMode()) Log.w(GoHttp.LOG_TAG, httpRequest.getName() + "; " + "Canceled : Http??" + "; " + httpRequest.getUrl()); reentrantLock.unlock(); return; } if (httpRequest.getGoHttp().isDebugMode()) Log.d(GoHttp.LOG_TAG, httpRequest.getName() + "; " + "Failed : Http??" + "; " + httpRequest.getUrl()); if (isContinueCallback) { new FailedRunnable(httpRequest, httpResponse, new HttpRequest.Failure(e), false, false) .execute(); } reentrantLock.unlock(); return; } if (httpRequest.isCanceled()) { httpRequest.finish(); new CancelRunnable(httpRequest).execute(); if (httpRequest.getGoHttp().isDebugMode()) Log.w(GoHttp.LOG_TAG, httpRequest.getName() + "; " + "Canceled : Http?" + "; " + httpRequest.getUrl()); reentrantLock.unlock(); return; } if (httpRequest.getGoHttp().isDebugMode()) Log.d(GoHttp.LOG_TAG, httpRequest.getName() + "; " + "Cache : Http??" + "; " + httpRequest.getUrl()); } // ??? if (!isContinueCallback) { httpRequest.finish(); if (httpRequest.getGoHttp().isDebugMode()) Log.d(GoHttp.LOG_TAG, httpRequest.getName() + "; " + "Completed : ??" + "; " + httpRequest.getUrl()); reentrantLock.unlock(); return; } // ?? Object responseObject; try { responseObject = httpRequest.getResponseHandler().handleResponse(httpRequest, httpResponse); if (responseObject == null) { throw new Exception("response object is null"); } // ??? if (!(responseObject instanceof HttpRequest.Failure) && httpRequest.getResponseHandleCompletedAfterListener() != null) { //noinspection unchecked Object response = httpRequest.getResponseHandleCompletedAfterListener() .onResponseHandleAfter(httpRequest, httpResponse, responseObject, false, false); if (response != null) { responseObject = response; } } } catch (Throwable e) { e.printStackTrace(); releaseConnect(httpResponse); httpRequest.finish(); if (httpRequest.isCanceled()) { new CancelRunnable(httpRequest).execute(); if (httpRequest.getGoHttp().isDebugMode()) Log.w(GoHttp.LOG_TAG, httpRequest.getName() + "; " + "Canceled : ??Http??" + "; " + httpRequest.getUrl()); if (reentrantLock != null) reentrantLock.unlock(); return; } if (httpRequest.getGoHttp().isDebugMode()) Log.e(GoHttp.LOG_TAG, httpRequest.getName() + "; " + "Failed : ??Http??" + "; " + httpRequest.getUrl()); new FailedRunnable(httpRequest, httpResponse, new HttpRequest.Failure(e), false, false).execute(); if (reentrantLock != null) reentrantLock.unlock(); return; } if (httpRequest.isCanceled()) { releaseConnect(httpResponse); httpRequest.finish(); new CancelRunnable(httpRequest).execute(); if (httpRequest.getGoHttp().isDebugMode()) Log.w(GoHttp.LOG_TAG, httpRequest.getName() + "; " + "Canceled : ?Http?" + "; " + httpRequest.getUrl()); if (reentrantLock != null) reentrantLock.unlock(); return; } if (httpRequest.getGoHttp().isDebugMode()) Log.d(GoHttp.LOG_TAG, httpRequest.getName() + "; " + "Net : ?Http?" + "; " + httpRequest.getUrl()); // if (responseObject instanceof HttpRequest.Failure) { HttpRequest.Failure failure = (HttpRequest.Failure) responseObject; new FailedRunnable(httpRequest, httpResponse, failure, false, false).execute(); if (httpRequest.getGoHttp().isDebugMode()) Log.e(GoHttp.LOG_TAG, httpRequest.getName() + "; " + "Failed : " + failure.toString() + "; " + httpRequest.getUrl()); } else { new CompletedRunnable(httpRequest, httpResponse, responseObject, false, false).execute(); if (httpRequest.getGoHttp().isDebugMode()) Log.d(GoHttp.LOG_TAG, httpRequest.getName() + "; " + "Completed : ?" + "; " + httpRequest.getUrl()); } httpRequest.finish(); if (reentrantLock != null) reentrantLock.unlock(); }
From source file:net.ymate.platform.webmvc.support.WebCacheProcessor.java
private PageMeta __doPutCacheElement(GenericResponseWrapper response, ICaches caches, ResponseCache responseCache, String cacheKey, IView resultView) throws Exception { ReentrantLock _locker = __doGetCacheLocker(cacheKey); _locker.lock();// w w w. j a va2s . c o m // PageMeta _element = null; try { // ?? _element = (PageMeta) caches.get(responseCache.cacheName(), cacheKey); // ? if (_element == null || _element.isExpired()) { // ?? ByteArrayOutputStream _output = new ByteArrayOutputStream(); resultView.render(_output); _element = new PageMeta(response.getContentType(), response.getHeaders(), _output.toByteArray(), responseCache.useGZip()); // int _timeout = responseCache.timeout() > 0 ? responseCache.timeout() : caches.getModuleCfg().getDefaultCacheTimeout(); if (_timeout > 0) { _element.setTimeout(_timeout); } // caches.put(responseCache.cacheName(), cacheKey, _element); } } catch (UnsupportedOperationException e) { _LOG.warn( resultView.getClass().getName() + " Unsupported Render To OutputStream Operation, Skip Cache."); } finally { _locker.unlock(); } return _element; }
From source file:com.googlecode.msidor.springframework.integration.channel.ConcurentOrderedMultiQueueChannel.java
/** * Adds message to the queue.//from www. j a v a 2 s . co m * This method blocks if there is no space. * @param message to be added * @param timeout after which the method awakes from waiting for free space (0 for no timeout) * @return true if message was successfully added to queue */ @Override protected boolean doSend(Message<?> message, long timeout) { Assert.notNull(message, "'message' must not be null"); log.trace("Sending message " + message); long nanos = TimeUnit.MILLISECONDS.toNanos(timeout); int c = -1; final ReentrantLock lock = this.objectLock; final AtomicInteger count = this.count; try { //lock the object exclusively lock.lockInterruptibly(); while (count.get() == totalCapacity) { //if timeout was set and has elapsed if (nanos <= 0 && timeout > 0) return false; //wait for notification when any message has been handled if (timeout > 0) { nanos = notFull.awaitNanos(nanos); } else { notFull.await(); } } //add message to the queue addMessage(message); c = count.getAndIncrement(); //if there is still some space notify any other potentially dormant producer thread if (c + 1 < totalCapacity) notFull.signal(); } catch (InterruptedException e) { log.trace("Lock interrupted by other thread"); } finally { //notify potentially dormant consumer thread that there is a message to handle newMessagesToCheck.signal(); lock.unlock(); } return true; }
From source file:org.alfresco.repo.workflow.WorkflowReportServiceImpl.java
@Override public NodeRef addTask(final WorkflowTask task) { if (!isEnabled()) { return null; }/* w ww.j av a 2 s . c om*/ if (DEBUG_ENABLED) { LOGGER.debug("ADD TASK " + task.getId()); } ReentrantLock acquiredLock = acquireLock(CMFService.getTenantId()); acquiredLock.lock(); try { final List<WorkflowTask> queryTasks = listTasks(task.getId(), null); return AuthenticationUtil.runAs(new RunAsWork<NodeRef>() { @Override public NodeRef doWork() throws Exception { WorkflowTask task = queryTasks.get(0); return addTaskInternal(task); } }, CMFService.getSystemUser()); } catch (Exception e) { LOGGER.error(e); } finally { acquiredLock.unlock(); } return null; }
From source file:org.alfresco.repo.workflow.WorkflowReportServiceImpl.java
@Override public void cancelWorkflow(final WorkflowInstance workflowInstance) { if (!isEnabled()) { return;/*from w ww. jav a2 s. c om*/ } if (DEBUG_ENABLED) { LOGGER.debug("CANCEL WORKFLOW (task) " + workflowInstance.getId()); } ReentrantLock acquiredLock = acquireLock(CMFService.getTenantId()); acquiredLock.lock(); try { AuthenticationUtil.runAs(new RunAsWork<Void>() { @Override public Void doWork() throws Exception { fixWorkflowMetadata(null, workflowInstance, CANCELLED, getWorkflowItems(workflowInstance.getWorkflowPackage(), CMFModel.PROP_TYPE)); return null; } }, CMFService.getSystemUser()); } catch (Exception e) { LOGGER.error(e); // just print and skip } finally { acquiredLock.unlock(); } }
From source file:org.alfresco.repo.workflow.WorkflowReportServiceImpl.java
@Override public NodeRef addStandaloneTask(final String taskId, final Map<QName, Serializable> props) { if (!isEnabled()) { return null; }/*w w w . j av a 2 s . c om*/ if (DEBUG_ENABLED) { LOGGER.debug("ADD TASK FOR STANDALONE " + taskId); } ReentrantLock acquiredLock = acquireLock(CMFService.getTenantId()); acquiredLock.lock(); try { final List<WorkflowTask> queryTasks = listTasks(taskId, null); return AuthenticationUtil.runAs(new RunAsWork<NodeRef>() { @Override public NodeRef doWork() throws Exception { WorkflowTask task = queryTasks.get(0); task.getProperties().putAll(props); return addTaskInternal(task); } }, CMFService.getSystemUser()); } catch (Exception e) { LOGGER.error(e); } finally { acquiredLock.unlock(); } return null; }
From source file:org.alfresco.repo.workflow.WorkflowReportServiceImpl.java
@Override public void addTask(final WorkflowPath workflowPath) { if (!isEnabled()) { return;//from ww w . ja v a2s . c om } if (DEBUG_ENABLED) { LOGGER.debug("ADD TASK FOR PATH " + workflowPath.getId()); } ReentrantLock acquiredLock = acquireLock(CMFService.getTenantId()); acquiredLock.lock(); try { WorkflowInstance instance = workflowPath.getInstance(); final List<WorkflowTask> queryTasks = listTasks(null, instance.getId()); AuthenticationUtil.runAs(new RunAsWork<NodeRef>() { @Override public NodeRef doWork() throws Exception { WorkflowTask task = queryTasks.get(0); return addTaskInternal(task); } }, CMFService.getSystemUser()); } catch (Exception e) { LOGGER.error(e); } finally { acquiredLock.unlock(); } }
From source file:net.ymate.platform.cache.support.CacheableProxy.java
public Object doProxy(IProxyChain proxyChain) throws Throwable { ICaches _caches = Caches.get(proxyChain.getProxyFactory().getOwner()); ///*from w w w. ja v a 2 s . c o m*/ Cacheable _anno = proxyChain.getTargetMethod().getAnnotation(Cacheable.class); if (_anno == null) { return proxyChain.doProxyChain(); } // Object _cacheKey = StringUtils.trimToNull(_anno.key()); if (_cacheKey == null) { _cacheKey = _caches.getModuleCfg().getKeyGenerator().generateKey(proxyChain.getTargetMethod(), proxyChain.getMethodParams()); } ReentrantLock _locker = __LOCK_MAP.get(_cacheKey.toString()); if (_locker == null) { _locker = new ReentrantLock(); ReentrantLock _previous = __LOCK_MAP.putIfAbsent(_cacheKey.toString(), _locker); if (_previous != null) { _locker = _previous; } } _locker.lock(); CacheElement _result = null; try { ICacheScopeProcessor _scopeProc = _caches.getModuleCfg().getCacheScopeProcessor(); if (!_anno.scope().equals(ICaches.Scope.DEFAULT) && _scopeProc != null) { _result = _scopeProc.getFromCache(_caches, _anno.scope(), _anno.cacheName(), _cacheKey.toString()); } else { _result = (CacheElement) _caches.get(_anno.cacheName(), _cacheKey); } boolean _flag = true; if (_result != null && !_result.isExpired()) { _flag = false; } if (_flag) { Object _cacheTarget = proxyChain.doProxyChain(); if (_cacheTarget != null) { _result = new CacheElement(_cacheTarget); int _timeout = _anno.timeout() > 0 ? _anno.timeout() : _caches.getModuleCfg().getDefaultCacheTimeout(); if (_timeout > 0) { _result.setTimeout(_timeout); } if (!_anno.scope().equals(ICaches.Scope.DEFAULT) && _scopeProc != null) { _scopeProc.putInCache(_caches, _anno.scope(), _anno.cacheName(), _cacheKey.toString(), _result); } else { _caches.put(_anno.cacheName(), _cacheKey, _result); } } } } finally { _locker.unlock(); } return _result != null ? _result.getObject() : null; }