List of usage examples for java.util.concurrent.locks Lock unlock
void unlock();
From source file:DemandCache.java
/** * @see java.util.Map#putAll(java.util.Map) */// ww w .ja v a 2 s .c o m public void putAll(Map<? extends K, ? extends V> m) { Lock lock = theLock.writeLock(); lock.lock(); try { if (thePurgeTime < System.currentTimeMillis() - 60 * 1000) purge(); for (java.util.Map.Entry<? extends K, ? extends V> entry : m.entrySet()) { CacheValue cv = new CacheValue(); cv.value = entry.getValue(); _access(cv, ACCESS_SET); theCache.put(entry.getKey(), cv); } } finally { lock.unlock(); } }
From source file:jenkins.plugins.git.GitSCMFileSystem.java
<V> V invoke(final FSFunction<V> function) throws IOException, InterruptedException { Lock cacheLock = AbstractGitSCMSource.getCacheLock(cacheEntry); cacheLock.lock();//from w w w . ja v a2 s . co m try { File cacheDir = AbstractGitSCMSource.getCacheDir(cacheEntry); if (cacheDir == null || !cacheDir.isDirectory()) { throw new IOException("Closed"); } return client.withRepository(new RepositoryCallback<V>() { @Override public V invoke(Repository repository, VirtualChannel virtualChannel) throws IOException, InterruptedException { return function.invoke(repository); } }); } finally { cacheLock.unlock(); } }
From source file:org.pepstock.jem.gwt.server.services.CommonResourcesManager.java
/** * Gets all resources list defined in JEM * /*from w ww .ja v a 2 s .c o m*/ * @param filter * filter of resources * @return collection of resources * @throws ServiceMessageException * @throws Exception * if any exception occurs */ public Collection<Resource> values(String filter) throws ServiceMessageException { // checks if the user is authorized to read resources information // if not, this method throws an exception checkAuthorization(new StringPermission(Permissions.RESOURCES_READ)); IMap<String, Resource> map = getInstance().getMap(Queues.COMMON_RESOURCES_MAP); // creates a Resource predicate // using filter filled on UI ResourcePredicate predicate; try { predicate = new ResourcePredicate(Filter.parse(filter)); } catch (Exception e) { LogAppl.getInstance().debug(e.getMessage(), e); // default case, all resources with empty filter by name Filter all = new Filter(); all.add(new FilterToken(ResourceFilterFields.NAME.getName(), StringUtils.EMPTY)); predicate = new ResourcePredicate(all); } Collection<Resource> result = null; // locks all map to have a consistent collection // only for 10 seconds otherwise // throws an exception boolean isLock = false; Lock lock = getInstance().getLock(Queues.COMMON_RESOURCES_MAP_LOCK); try { isLock = lock.tryLock(10, TimeUnit.SECONDS); if (isLock) { // performs predicate to have the collection result = map.values(predicate); } else { // timeout exception throw new ServiceMessageException(UserInterfaceMessage.JEMG022E, Queues.COMMON_RESOURCES_MAP); } } catch (InterruptedException e) { throw new ServiceMessageException(UserInterfaceMessage.JEMG022E, e, Queues.COMMON_RESOURCES_MAP); } finally { // unlocks always the map if (isLock) { lock.unlock(); } } // returns a collection return result; }
From source file:com.mg.framework.service.DatabaseAuditServiceImpl.java
public void loadAuditSetup() { boolean startTran = false; try {/*ww w. j a v a 2 s . c om*/ logger.info("load audit setup"); startTran = ServerUtils.getTransactionManager().getStatus() == Status.STATUS_NO_TRANSACTION; if (startTran) ServerUtils.getTransactionManager().begin(); List<PersistentObject> list = OrmTemplate.getInstance() .findByCriteria(OrmTemplate.createCriteria("com.mg.merp.core.model.DatabaseAuditSetup")); Lock lock = entityAuditSetupLock.writeLock(); lock.lock(); try { if (entityAuditSetup != null) entityAuditSetup.clear(); for (PersistentObject item : list) { String entityName = (String) item.getAttribute("AuditedEntityName"); EntityAuditSetup auditSetup = entityAuditSetup.get(entityName); if (auditSetup == null) entityAuditSetup.put(entityName, new EntityAuditSetup(item)); else auditSetup.setAudit(item); } } finally { lock.unlock(); } if (startTran) ServerUtils.getTransactionManager().commit(); } catch (Exception e) { logger.error("load audit setup failed", e); try { if (startTran) ServerUtils.getTransactionManager().rollback(); } catch (Exception ee) { logger.error("transaction rollback failed", ee); } } }
From source file:jp.aegif.nemaki.cmis.service.impl.NavigationServiceImpl.java
@Override public ObjectData getFolderParent(CallContext callContext, String repositoryId, String folderId, String filter) {/*w ww . ja v a 2 s .c o m*/ exceptionService.invalidArgumentRequiredString("folderId", folderId); Lock childLock = threadLockService.getReadLock(repositoryId, folderId); try { childLock.lock(); // ////////////////// // General Exception // ////////////////// Folder folder = (Folder) contentService.getContent(repositoryId, folderId); exceptionService.objectNotFound(DomainType.OBJECT, folder, folderId); exceptionService.permissionDenied(callContext, repositoryId, PermissionMapping.CAN_GET_FOLDER_PARENT_OBJECT, folder); // ////////////////// // Specific Exception // ////////////////// Folder parent = contentService.getParent(repositoryId, folderId); Lock parentLock = threadLockService.getReadLock(repositoryId, parent.getId()); try { parentLock.lock(); exceptionService.objectNotFoundParentFolder(repositoryId, folderId, parent); exceptionService.invalidArgumentRootFolder(repositoryId, folder); // ////////////////// // Body of the method // ////////////////// return compileService.compileObjectData(callContext, repositoryId, parent, filter, true, IncludeRelationships.NONE, null, true); } finally { parentLock.unlock(); } } finally { childLock.unlock(); } }
From source file:org.pentaho.platform.plugin.action.olap.impl.OlapServiceImpl.java
/** * Clears all caches for all locales.//from w ww. j av a 2 s.c o m */ protected void resetCache(IPentahoSession session) { final Lock writeLock = cacheLock.writeLock(); try { writeLock.lock(); final ICacheManager cacheMgr = PentahoSystem.getCacheManager(session); cacheMgr.clearRegionCache(CATALOG_CACHE_REGION); } finally { writeLock.unlock(); } }
From source file:org.mule.security.oauth.BaseOAuthClientFactory.java
/** * Passivates the object by updating the state of the persisted object with the * one of the given one. If the object doesn't exist in the object store then it * is created//w w w . ja v a 2 s. c o m * * @param key the key of the object at the object store * @param connector an instance of {@link org.mule.security.oauth.OAuth2Adapter} * @throws IllegalArgumentException if obj is not an instance of the type returned by {@link BaseOAuthClientFactory#getAdapterClass()} */ @Override public final void passivateObject(String key, OAuth2Adapter connector) throws Exception { if (!this.getAdapterClass().isInstance(connector)) { throw new IllegalArgumentException("Invalid connector type"); } OAuthState state; Lock lock = this.getLock(key); lock.lock(); try { if (this.objectStore.contains(key)) { state = this.retrieveOAuthState(key, false); this.objectStore.remove(key); } else { state = new OAuthState(); } state.setAccessToken(connector.getAccessToken()); state.setAccessTokenUrl(connector.getAccessTokenUrl()); state.setAuthorizationUrl(connector.getAuthorizationUrl()); state.setRefreshToken(connector.getRefreshToken()); this.setCustomStateProperties(connector, state); this.objectStore.store(key, state); } finally { lock.unlock(); } }
From source file:com.enonic.cms.business.portal.image.ImageServiceImpl.java
public ImageResponse process(ImageRequest imageRequest) { Preconditions.checkNotNull(imageRequest, "imageRequest cannot be null"); final ImageRequestTrace imageRequestTrace = livePortalTraceService.getCurrentImageRequestTrace(); String blobKey = getBlobKey(imageRequest); if (blobKey == null) { return ImageResponse.notFound(); }/*from w w w .j a v a 2 s. c o m*/ imageRequest.setBlobKey(blobKey); final Lock locker = concurrencyLock.getLock(imageRequest.getCacheKey()); try { locker.lock(); ImageResponse res = imageCache.get(imageRequest); if (res != null) { ImageRequestTracer.traceImageResponse(imageRequestTrace, res); ImageRequestTracer.traceUsedCachedResult(imageRequestTrace, true); return res; } try { res = doProcess(imageRequest); ImageRequestTracer.traceImageResponse(imageRequestTrace, res); ImageRequestTracer.traceUsedCachedResult(imageRequestTrace, false); return res; } catch (Exception e) { throw new ImageProcessorException("Failed to process image: " + e.getMessage(), e); } } finally { locker.unlock(); } }
From source file:org.apache.rave.synchronization.SynchronizingAspect.java
@Around("synchronizePointcut()") public Object synchronizeInvocation(ProceedingJoinPoint proceedingJoinPoint) throws Throwable { MethodSignature methodSignature = (MethodSignature) proceedingJoinPoint.getSignature(); Method method = methodSignature.getMethod(); Object target = proceedingJoinPoint.getTarget(); Object[] args = proceedingJoinPoint.getArgs(); Class<?> targetClass = AopProxyUtils.ultimateTargetClass(target); Synchronized annotation = getAnnotation(targetClass, method); Validate.notNull(annotation, "Could not find @Synchronized annotation!"); Lock lock = getLock(targetClass, method, args, annotation); if (lock == null) { logger.debug(/*from ww w . j a v a 2 s . co m*/ "No lock obtained for call [{}] on targetClass [{}] - proceeding without synchronization on " + "thread {}", new Object[] { method.getName(), targetClass.getName(), Thread.currentThread().getId() }); return proceedingJoinPoint.proceed(); } else { try { logger.debug( "Lock obtained for call [{}] on targetClass [{}] - proceeding with synchronization on thread {}", new Object[] { method.getName(), targetClass.getName(), Thread.currentThread().getId() }); lock.lock(); return proceedingJoinPoint.proceed(); } finally { lock.unlock(); lockService.returnLock(lock); } } }
From source file:com.crossover.trial.weather.metrics.impl.DropwizardMetricsService.java
@Override public MetricsReport<Meter, HistogramSnapshotDTO> buildReport() { Lock read = registryLock.readLock(); read.lock();//from ww w .java 2 s.c om try { MetricsReport.Builder<Meter, HistogramSnapshotDTO> builder = new MetricsReport.Builder<Meter, HistogramSnapshotDTO>() .withRadiusFrequency(new HistogramSnapshotDTO(registry.histogram("radius"))).withDataSize( dataPointRepository.countTotalMeasurementsInLastTimeWindow(timestamp().minusDays(1))); registry.getMeters().entrySet().stream().forEach(entry -> { Airport airport = airportRepository.findOne(IATA.valueOf(entry.getKey())); if (airport == null) registry.remove(entry.getKey()); else { Meter meter = registry.meter(entry.getKey()); if (meter != null) builder.withAirportMetric(airport, meter); } }); return builder.build(); } finally { read.unlock(); } }