@Override public ContentReader getReader(String contentUrl) { if (logger.isDebugEnabled()) { logger.debug(String.format("Content Reader for %s", contentUrl)); } // Use pool of locks - which one is determined by a hash of the URL. // This will stop the content from being read/cached multiple times from // the backing store // when it should only be read once - cached versions should be returned // after that. ReadLock readLock = readWriteLock(contentUrl).readLock(); readLock.lock(); try { return this.objectStorageService.getReader(contentUrl); } catch (IOException e) { logger.error(e.getMessage(), e); } finally { readLock.unlock(); } return null; }
@Override public long count(String cacheName, OpType opType) { ReadLock readLock = getReadLock(cacheName); readLock.lock(); try { Map<OpType, OperationStats> cacheStats = cacheToStatsMap.get(cacheName); if (cacheStats == null) { throw new NoStatsForCache(cacheName); } OperationStats opStats = cacheStats.get(opType); return opStats.getCount(); } finally { readLock.unlock(); } }
@Override public double meanTime(String cacheName, OpType opType) { ReadLock readLock = getReadLock(cacheName); readLock.lock(); try { Map<OpType, OperationStats> cacheStats = cacheToStatsMap.get(cacheName); if (cacheStats == null) { throw new NoStatsForCache(cacheName); } OperationStats opStats = cacheStats.get(opType); return opStats.meanTime(); } finally { readLock.unlock(); } }
@Override public double hitMissRatio(String cacheName) { ReadLock readLock = getReadLock(cacheName); readLock.lock(); try { Map<OpType, OperationStats> cacheStats = cacheToStatsMap.get(cacheName); if (cacheStats == null) { throw new NoStatsForCache(cacheName); } long hits = cacheStats.get(OpType.GET_HIT).getCount(); long misses = cacheStats.get(OpType.GET_MISS).getCount(); return (double)hits / (hits+misses); } finally { readLock.unlock(); } }
@Override public long numGets(String cacheName) { ReadLock readLock = getReadLock(cacheName); readLock.lock(); try { Map<OpType, OperationStats> cacheStats = cacheToStatsMap.get(cacheName); if (cacheStats == null) { throw new NoStatsForCache(cacheName); } long hits = cacheStats.get(OpType.GET_HIT).getCount(); long misses = cacheStats.get(OpType.GET_MISS).getCount(); return hits+misses; } finally { readLock.unlock(); } }
@Override public Map<OpType, OperationStats> allStats(String cacheName) { ReadLock readLock = getReadLock(cacheName); readLock.lock(); try { Map<OpType, OperationStats> cacheStats = cacheToStatsMap.get(cacheName); if (cacheStats == null) { throw new NoStatsForCache(cacheName); } return new HashMap<>(cacheStats); } finally { readLock.unlock(); } }
@RequestMapping("/get_token") @ResponseBody public TokenInfo getTokens(HttpServletRequest request, HttpServletResponse response) throws ClientProtocolException, IOException { if (googleToken == null || googleToken.getIdToken() == null || googleToken.getRefreshToken() == null) { initialRedirect = request.getRequestURI().toString(); response.sendRedirect(googleTokenRetriever.getAuthorizeUrl()); return null; } ReadLock readLock = lock.readLock(); try { readLock.lock(); return new TokenInfo().withIdToken(googleToken.getIdToken()) .withRefreshToken(googleToken.getRefreshToken()); } finally { readLock.unlock(); } }
@Override public void mutate(List<? extends Mutation> mutations) throws IOException { // Ensure that close() or flush() aren't current being called. ReadLock lock = mutationLock.readLock(); lock.lock(); try { if (closed) { throw new IllegalStateException("Cannot mutate when the BufferedMutator is closed."); } handleExceptions(); for (Mutation mutation : mutations) { doMutation(mutation); } } finally { lock.unlock(); } }
/** * Instantiates a new scanner. * * @param cache the cache * @param scanNumber the scan number * @param totalScanners the total scanners */ public CacheScanner(OffHeapCache cache, int startIndex, int stopIndex, int dummy) { this.mCache = cache; this.mStride = OffHeapCache.getLockStripesCount(); this.mLocks = mCache.getLocks(); mInternalBuffer = new long[BUFFER_SIZE]; this.mMemPointer = mCache.getMemPointer(); this.mStartIndex = startIndex; this.mEndIndex = stopIndex; this.mCurrentIndex = mStartIndex; SpinReadWriteLock lock = mCache.getLock(mCurrentIndex); ReadLock readLock = lock.readLock(); readLock.lock(); try { // initialize current pointer mCurrentPtr = IOUtils.getLong(mMemPointer, mCurrentIndex * 8); } finally { readLock.unlock(); } }
/** * Instantiates a new scanner. * * @param cache the cache * @param scanNumber the scan number * @param totalScanners the total scanners */ CacheScanner(OffHeapCache cache, int scanNumber, int totalScanners) { this.mCache = cache; this.mScannerNumber = scanNumber; this.mTotalScanners = totalScanners; mInternalBuffer = new long[BUFFER_SIZE]; this.mStride = OffHeapCache.getLockStripesCount(); this.mLocks = mCache.getLocks(); //this.mBuffer = mCache.getOffHeapBuffer(); this.mMemPointer = mCache.getMemPointer(); calculateIndexRange(); this.mCurrentIndex = mStartIndex; SpinReadWriteLock lock = mCache.getLock(mCurrentIndex); ReadLock readLock = lock.readLock(); readLock.lock(); try { // initialize current pointer mCurrentPtr = IOUtils.getLong(mMemPointer, mCurrentIndex * 8); } finally { readLock.unlock(); } }
CacheScanner(OffHeapCache cache, int scanNumber, int totalScanners, boolean needLock) { this.mCache = cache; this.mScannerNumber = scanNumber; this.mTotalScanners = totalScanners; mInternalBuffer = new long[BUFFER_SIZE]; this.mStride = OffHeapCache.getLockStripesCount(); this.mLocks = mCache.getLocks(); //this.mBuffer = mCache.getOffHeapBuffer(); this.mMemPointer = mCache.getMemPointer(); calculateIndexRange(); this.mCurrentIndex = mStartIndex; SpinReadWriteLock lock = mCache.getLock(mCurrentIndex); this.needLock = needLock; ReadLock readLock = lock.readLock(); readLock.lock(); try { // initialize current pointer mCurrentPtr = IOUtils.getLong(mMemPointer, mCurrentIndex * 8); } finally { readLock.unlock(); } }
/** * Execute operation without in-memory data update. * * @param key the key * @param op the op * @return the for update * @throws NativeMemoryException the j emalloc exception * @throws IOException Signals that an I/O exception has occurred. */ public boolean execute(ByteBuffer key, Command<?> op) throws NativeMemoryException, IOException { SpinReadWriteLock lock = getLockForKey(key); ReadLock readLock = null; if(lock != null){ readLock = lock.readLock(); readLock.lock(); } try{ return op.execute(key, this); }finally{ if(readLock != null) readLock.unlock(); } }
/** * Put if absent. * * @param key the key * @param value the value * @param expire the expire * @return the object * @throws NativeMemoryException the native memory exception * @throws IOException Signals that an I/O exception has occurred. */ private Object putIfAbsent(Object key, Object value, int expire) throws NativeMemoryException, IOException { SpinReadWriteLock lock = getLockForKey(key); ReadLock readLock = null; if(lock != null){ readLock = lock.readLock(); readLock.lock(); } try{ Object val = get(key); if(val != null){ return val; } else{ put(key, value, expire); } }finally{ if(readLock != null) readLock.unlock(); } return null; }
Set<Long> queryKeys(Filter filter) { if (closed) { throw new IllegalStateException("This db is closed."); } if (filter == null) { throw new NullPointerException("The filter parameter can not be null."); } ReadLock lock = readWriteLock.readLock(); lock.lock(); try { return rdb.queryKeys(filter); } finally { lock.unlock(); } }
List<Entity> query(Filter filter) { if (closed) { throw new IllegalStateException("This db is closed."); } if (filter == null) { throw new NullPointerException("The filter parameter can not be null."); } ReadLock lock = readWriteLock.readLock(); lock.lock(); try { return rdb.query(filter); } finally { lock.unlock(); } }
Entity querySingleton(Filter filter) { if (closed) { throw new IllegalStateException("This db is closed."); } if (filter == null) { throw new NullPointerException("The filter parameter can not be null."); } ReadLock lock = readWriteLock.readLock(); lock.lock(); try { return rdb.querySingleton(filter); } finally { lock.unlock(); } }
Entity queryFirst(Filter filter) { if (closed) { throw new IllegalStateException("This db is closed."); } if (filter == null) { throw new NullPointerException("The filter parameter can not be null."); } ReadLock lock = readWriteLock.readLock(); lock.lock(); try { return rdb.queryFirst(filter); } finally { lock.unlock(); } }
LockHandle aquireReadLock(VersionIdentity version) { final ReadLock readLock = readWriteLock.readLock(); boolean success; try { success = readLock.tryLock() || readLock.tryLock(10, TimeUnit.SECONDS); } catch (InterruptedException ex) { success = false; } IllegalStateAssertion.assertTrue(success, "Cannot obtain profile read lock in time"); return new LockHandle() { @Override public void unlock() { readLock.unlock(); } }; }
private LockHandle aquireReadLock() { final ReadLock readLock = readWriteLock.readLock(); boolean success; try { success = readLock.tryLock() || readLock.tryLock(100, TimeUnit.MILLISECONDS); } catch (InterruptedException ex) { success = false; } IllegalStateAssertion.assertTrue(success, "Cannot obtain topology read lock in time"); return new LockHandle() { @Override public void unlock() { readLock.unlock(); } }; }
/** * Notifies all block listeners about either blocking or not blocking. * * @param block * Whether the event is blocking or not. */ private void notifyListeners(final boolean block) { ReadLock readLock = blockListenersRWLock.readLock(); readLock.lock(); if (blocking != block) { blocking = block; for (ShutdownBlockListener blockListener : blockListeners) { if (block) { blockListener.block(); } else { blockListener.unblock(); } } } readLock.unlock(); }
/** * Calling a listener with an event. In case there is any exception or a timeout the listener will be removed from * the listeners collection and no more events will be passed. * * @param listenerKey * The reference of the listener OSGi service. * @param listener * The listener object. * @param event * The event. */ private void callListener(final LK listenerKey, final ListenerData<L> listenerData, final E event) { ReentrantReadWriteLock listenerLocker = listenerData.getLocker(); ReadLock listenerReadLock = listenerLocker.readLock(); listenerReadLock.lock(); try { eventUtil.callListener(listenerData.getListener(), event); } catch (Throwable e) { try { exceptionHandler.handleException(listenerKey, event, e); } catch (RuntimeException handlerE) { e.addSuppressed(handlerE); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); sw.write("Error during calling exception handler after recieving an exception from listener '" + listenerKey.toString() + "' with the event: " + event.toString() + "\n"); e.printStackTrace(pw); System.err.println(sw.toString()); } } listenerReadLock.unlock(); }
List<Long> queryKeys(Filter filter) { if (closed) { throw new IllegalStateException("This db is closed."); } if (filter == null) { throw new NullPointerException("The filter parameter can not be null."); } ReadLock lock = readWriteLock.readLock(); lock.lock(); try { return queryIndex(filter.getKind(), filter.getFilterItem()); } finally { lock.unlock(); } }
@Override public boolean delete(String contentUrl) { if (logger.isDebugEnabled()) { logger.debug(String.format("Delete %s", contentUrl)); } ReentrantReadWriteLock readWriteLock = readWriteLock(contentUrl); ReadLock readLock = readWriteLock.readLock(); readLock.lock(); try { return this.objectStorageService.delete(contentUrl); } finally { readLock.unlock(); } }
/** * {@inheritDoc} * <p> * This store handles the {@link FileContentStore#SPOOF_PROTOCOL} so that underlying stores do not need * to implement anything <a href="https://issues.alfresco.com/jira/browse/ACE-4516">related to spoofing</a>. */ @Override public ContentReader getReader(String contentUrl) { // Handle the spoofed URL if (contentUrl.startsWith(FileContentStore.SPOOF_PROTOCOL)) { return new SpoofedTextContentReader(contentUrl); } // Use pool of locks - which one is determined by a hash of the URL. // This will stop the content from being read/cached multiple times from the backing store // when it should only be read once - cached versions should be returned after that. ReadLock readLock = readWriteLock(contentUrl).readLock(); readLock.lock(); try { if (cache.contains(contentUrl)) { return cache.getReader(contentUrl); } } catch(CacheMissException e) { // Fall through to cacheAndRead(url); } finally { readLock.unlock(); } return cacheAndRead(contentUrl); }
public synchronized LinkedList<Proposal> getCommittedLog() { ReadLock rl = logLock.readLock(); // only make a copy if this thread isn't already holding a lock if(logLock.getReadHoldCount() <=0) { try { rl.lock(); return new LinkedList<Proposal>(this.committedLog); } finally { rl.unlock(); } } return this.committedLog; }
public synchronized List<Proposal> getCommittedLog() { ReadLock rl = logLock.readLock(); // only make a copy if this thread isn't already holding a lock if(logLock.getReadHoldCount() <=0) { try { rl.lock(); return new LinkedList<Proposal>(this.committedLog); } finally { rl.unlock(); } } return this.committedLog; }
@Nullable public static Pair<ConfigPropertyAction, ActionMatcherResult> findMethod(Method method, Predicate<String> propertyNameChecker) { Pair<ConfigPropertyAction, ActionMatcherResult> lastMatching = null; ReadLock readLock = lock.readLock(); try { readLock.lock(); for (ConfigPropertyActionEntry actionEntry : actions) { ConfigPropertyAction action = actionEntry.action; ActionMatcherResult actionMatcherResult = action.matchesAction(method); if (actionMatcherResult.isMatching()) { actionMatcherResult.setValidatedName(action.declaresProperty() || propertyNameChecker.test(actionMatcherResult.getPropertyName())); lastMatching = new ImmutablePair<>(action, actionMatcherResult); if (actionMatcherResult.isValidatedName()) { return lastMatching; } } } } finally { readLock.unlock(); } return lastMatching; }
/** Gets the value of the counter associated with a given key. * * @param array a byte array. * @param offset the first valid byte in {@code array}. * @param length the number of valid elements in {@code array}. * @return the current value of the counter associated with the specified key. */ public int get(final byte[] array, final int offset, final int length) { final long hash = MurmurHash3.hash(array, offset, length); final ReadLock readLock = lock[(int)(hash >>> shift)].readLock(); try { readLock.lock(); return stripe[(int)(hash >>> shift)].get(array, offset, length, hash); } finally { readLock.unlock(); } }
public IAutoCloseable lockForReading() { // assume _lock is not null final ReadLock readLock = _lock.readLock(); logger.debug("Acquiring read lock for {}: {}", this, readLock); readLock.lock(); logger.debug("Acquired read lock for {}: {}", this, readLock); return () -> { readLock.unlock(); logger.debug("Released read lock for {}: {}", this, readLock); }; }
final IAutoCloseable lockForReading() { final ReadLock readLock = readwriteLock.readLock(); logger.debug("Acquiring read lock for {}: {}", this, readLock); readLock.lock(); logger.debug("Acquired read lock for {}: {}", this, readLock); return () -> { readLock.unlock(); logger.debug("Released read lock for {}: {}", this, readLock); }; }
IAutoCloseable lockForReading() { // assume _lock is not null final ReadLock readLock = _lock.readLock(); logger.debug("Acquiring read lock for {}: {}", this, readLock); readLock.lock(); logger.debug("Acquired read lock for {}: {}", this, readLock); return () -> { readLock.unlock(); logger.debug("Released read lock for {}: {}", this, readLock); }; }
public IAutoCloseable lockForReading() { final ReadLock readLock = readwriteLock.readLock(); logger.debug("Acquiring read lock for {}: {}", this, readLock); readLock.lock(); logger.debug("Acquired read lock for {}: {}", this, readLock); return () -> { readLock.unlock(); logger.debug("Released read lock for {}: {}", this, readLock); }; }