List of usage examples for java.util.concurrent.locks ReentrantLock lock
public void lock()
From source file:com.netflix.config.ConcurrentMapConfiguration.java
protected void addPropertyDirect(String key, Object value) { ReentrantLock lock = locks[Math.abs(key.hashCode()) % NUM_LOCKS]; lock.lock(); try {/*from w w w. jav a 2s . c om*/ Object previousValue = map.putIfAbsent(key, value); if (previousValue == null) { return; } if (previousValue instanceof List) { // the value is added to the existing list ((List) previousValue).add(value); } else { // the previous value is replaced by a list containing the previous value and the new value List<Object> list = new CopyOnWriteArrayList<Object>(); list.add(previousValue); list.add(value); map.put(key, list); } } finally { lock.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()); ///* ww w .ja va 2s . c om*/ 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; }
From source file:org.eclipselabs.etrack.server.web.storage.AbstractStorageResource.java
@Override protected Representation doConditionalHandle() throws ResourceException { ReentrantLock lock = null; synchronized (locks) { lock = locks.get(getReference().toString()); if (lock == null) { lock = new ReentrantLock(); locks.put(getReference().toString(), lock); }/*ww w . jav a 2s . c om*/ } lock.lock(); try { Representation result = super.doConditionalHandle(); return result; } finally { lock.unlock(); } }
From source file:me.xiaopan.android.spear.download.HttpClientImageDownloader.java
@Override public DownloadResult download(DownloadRequest request) { // ?????//from w w w .j a v a 2 s .c o m ReentrantLock urlLock = getUrlLock(request.getUri()); urlLock.lock(); DownloadResult result = null; int number = 0; while (true) { // ??? if (request.isCanceled()) { if (Spear.isDebugMode()) Log.w(Spear.LOG_TAG, NAME + "" + "? - ??" + "" + request.getName()); break; } // ? File cacheFile = request.getCacheFile(); 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 (Spear.isDebugMode()) Log.w(Spear.LOG_TAG, NAME + "" + " - ??" + "" + request.getName()); } else { if (Spear.isDebugMode()) Log.e(Spear.LOG_TAG, NAME + "" + " - ???" + "" + request.getName()); } e.printStackTrace(); if (!retry) { break; } } } // ? urlLock.unlock(); return result; }
From source file:com.wooki.domain.biz.ChapterManagerImpl.java
public void updateContent(Long chapterId, Draft draft) { assert chapterId != null; assert draft != null; assert draft.getData() != null; // Update last modified timestamp Date lastModified = Calendar.getInstance().getTime(); ReentrantLock lock = getOrCreateLock(chapterId); Publication publication = publicationDao.findLastRevision(chapterId); lock.lock(); Chapter chapter = null;/* www. j a va 2 s . c om*/ try { chapter = chapterDao.findById(chapterId); if (chapter.getLastModified() != null && !chapter.getLastModified().equals(draft.getTimestamp())) { throw new ConcurrentModificationException( "Document has been modified by another user in the meantime."); } chapter.setLastModified(lastModified); chapterDao.update(chapter); } finally { lock.unlock(); } // we check the published flag. If set, then this Publication must // be considered as "locked" and we must create a new publication as // the new working copy if (publication == null || (publication != null && publication.isPublished())) { publication = new Publication(); // Security check if (!securityCtx.isLoggedIn() || !this.securityCtx.canWrite(chapter.getBook())) { throw new AuthorizationException("Publish action not authorized"); } publication.setChapter(chapter); publication.setCreationDate(Calendar.getInstance().getTime()); publicationDao.create(publication); } publication.setContent(draft.getData()); publication.setLastModified(lastModified); publicationDao.update(publication); }
From source file:me.xiaopan.sketch.download.HttpClientImageDownloader.java
@Override public DownloadResult download(DownloadRequest request) { // ?????/* w w w. j a v a 2 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.ut.biolab.medsavant.server.db.LockController.java
/** * Obtain a lock. If another thread already owns the lock, an exception will * be thrown.//from w ww .j av a 2 s . c o m * * @param database The database with the project to be unlocked. * @param projectID The project ID to lock * @throws LockException */ public synchronized void requestLock(String database, int projectID) throws LockException { LOG.info("Server lock requested"); Key key = new Key(database, projectID); ReentrantLock lock = locks.get(key); // create the lock if one doesn't exist for the project if (lock == null) { lock = new ReentrantLock(); locks.put(key, lock); } // lock it down // (if this thread owns the lock, call lock again which will increase the hold count) if (!lock.isLocked() || lock.isHeldByCurrentThread()) { lock.lock(); LOG.info(String.format("Server locked - hold count %d", lock.getHoldCount())); } else { throw new LockException("Database is locked for changes"); } }
From source file:org.apache.openejb.util.classloader.URLClassLoaderFirst.java
@Override public Class<?> loadClass(final String name, final boolean resolve) throws ClassNotFoundException { final ReentrantLock lock = LOCK; lock.lock(); try {/*ww w . j ava 2s. com*/ // already loaded? Class<?> clazz = findLoadedClass(name); if (clazz != null) { if (resolve) { resolveClass(clazz); } return clazz; } // JSE classes? if (canBeLoadedFromSystem(name)) { try { clazz = system.loadClass(name); if (clazz != null) { if (resolve) { resolveClass(clazz); } return clazz; } } catch (final ClassNotFoundException ignored) { // no-op } } // look for it in this classloader final boolean ok = !(shouldSkip(name) || shouldDelegateToTheContainer(this, name)); if (ok) { clazz = loadInternal(name, resolve); if (clazz != null) { return clazz; } } // finally delegate clazz = loadFromParent(name, resolve); if (clazz != null) { return clazz; } if (!ok) { clazz = loadInternal(name, resolve); if (clazz != null) { return clazz; } } throw new ClassNotFoundException(name); } finally { lock.unlock(); } }
From source file:org.gdg.frisbee.android.cache.ModelCache.java
public CacheItem put(final String url, final Object obj, DateTime expiresAt) { if (obj == null) return null; Log.d(LOG_TAG, String.format("put(%s)", url)); CacheItem d = new CacheItem(obj, expiresAt); if (null != mMemoryCache) { mMemoryCache.put(url, d);/*from www .j a va2 s. c o m*/ } if (null != mDiskCache) { checkNotOnMainThread(); final String key = transformUrlForDiskCacheKey(url); final ReentrantLock lock = getLockForDiskCacheEdit(key); lock.lock(); try { DiskLruCache.Editor editor = mDiskCache.edit(key); writeValueToDisk(editor.newOutputStream(0), obj); writeExpirationToDisk(editor.newOutputStream(1), expiresAt); editor.commit(); } catch (IOException e) { e.printStackTrace(); } finally { lock.unlock(); scheduleDiskCacheFlush(); } } return d; }
From source file:com.streamsets.datacollector.io.DataStore.java
@VisibleForTesting void acquireLock() { LOG.trace("Acquiring lock for '{}'", file); ReentrantLock lock = null; synchronized (DataStore.class) { lock = FILE_LOCKS.get(file);/* ww w. ja v a2s.com*/ if (lock == null) { lock = new ReentrantLock(); FILE_LOCKS.put(file, lock); } else { Utils.checkState(!lock.isHeldByCurrentThread(), Utils.format("The current thread already has a lock on '{}'", file)); } } lock.lock(); LOG.trace("Acquired lock for '{}'", file); }