public Map<K, V> getLatestAccessedItems(int n) { // we need to grab the lock since we are changing lastAccessedCopy markAndSweepLock.lock(); Map<K, V> result = new LinkedHashMap<K, V>(); TreeSet<CacheEntry> tree = new TreeSet<CacheEntry>(); try { for (Map.Entry<Object, CacheEntry> entry : map.entrySet()) { CacheEntry ce = entry.getValue(); ce.lastAccessedCopy = ce.lastAccessed; if (tree.size() < n) { tree.add(ce); } else { if (ce.lastAccessedCopy > tree.last().lastAccessedCopy) { tree.remove(tree.last()); tree.add(ce); } } } } finally { markAndSweepLock.unlock(); } for (CacheEntry<K, V> e : tree) { result.put(e.key, e.value); } return result; }
/** * Put an object into the cache specifying both the key to use and the cache groups the object * belongs to. * * @param key Key of the object in the cache * @param groups The cache groups to add the object to * @param content The object to cache * @param policy Object that implements the refresh policy logic */ public void putInCache( String key, Object content, String[] groups, EntryRefreshPolicy policy, String origin) { CacheEntry cacheEntry = this.getCacheEntry(key, policy, origin); boolean isNewEntry = cacheEntry.isNew(); // [CACHE-118] If we have an existing entry, create a new CacheEntry so we can still access the // old one later if (!isNewEntry) { cacheEntry = new CacheEntry(key, policy); } cacheEntry.setContent(content); cacheEntry.setGroups(groups); cacheMap.put(key, cacheEntry); // Signal to any threads waiting on this update that it's now ready for them // in the cache! completeUpdate(key); if (listenerList.getListenerCount() > 0) { CacheEntryEvent event = new CacheEntryEvent(this, cacheEntry, origin); if (isNewEntry) { dispatchCacheEntryEvent(CacheEntryEventType.ENTRY_ADDED, event); } else { dispatchCacheEntryEvent(CacheEntryEventType.ENTRY_UPDATED, event); } } }
private void refreshEntry(Context context, CacheEntry entry) throws IOException, MessagingException { LogUtils.d(Logging.LOG_TAG, "AuthenticationCache refreshEntry %d", entry.mAccountId); try { final AuthenticationResult result = mAuthenticator.requestRefresh(context, entry.mProviderId, entry.mRefreshToken); // Don't set the refresh token here, it's not returned by the refresh response, // so setting it here would make it blank. entry.mAccessToken = result.mAccessToken; entry.mExpirationTime = result.mExpiresInSeconds * DateUtils.SECOND_IN_MILLIS + System.currentTimeMillis(); saveEntry(context, entry); } catch (AuthenticationFailedException e) { // This is fatal. Clear the tokens and rethrow the exception. LogUtils.d(Logging.LOG_TAG, "authentication failed, clearning"); clearEntry(context, entry); throw e; } catch (MessagingException e) { LogUtils.d(Logging.LOG_TAG, "messaging exception"); throw e; } catch (IOException e) { LogUtils.d(Logging.LOG_TAG, "IO exception"); throw e; } }
public boolean put(K key, V value) { if (LOCAL_LOGV) { Log.v(TAG, "Trying to put " + key + " into cache."); } if (mCacheMap.size() >= MAX_CACHED_ITEMS) { // TODO Should remove the oldest or least hit cached entry // and then cache the new one. if (LOCAL_LOGV) { Log.v(TAG, "Failed! size limitation reached."); } return false; } if (key != null) { CacheEntry<V> cacheEntry = new CacheEntry<V>(); cacheEntry.value = value; mCacheMap.put(key, cacheEntry); if (LOCAL_LOGV) { Log.v(TAG, key + " cached, " + mCacheMap.size() + " items total."); } return true; } return false; }
public String toString() { StringBuffer sb = new StringBuffer(); sb.append("\n----------- START CACHE BLOCK -----------"); sb.append("\nEntry DN: ").append(entryDN); sb.append(" Valid Entry: ").append(isValidEntry); sb.append("\nOrganization: ").append(organizationDN); sb.append("\nString Attributes: "); if ((stringAttributes != null) && (!stringAttributes.isEmpty())) { sb.append(MiscUtils.mapSetToString(stringAttributes)); } sb.append("\nByte Attributes: "); sb.append(MiscUtils.mapSetToString(byteAttributes)); sb.append("\nByte Negative Attributes: "); if ((byteAttributes != null) && (!byteAttributes.isEmpty())) { sb.append(byteAttributes.getNegativeByteAttrClone().toString()); } sb.append("\nCache Entries: "); if (cacheEntries != null && !cacheEntries.isEmpty()) { Iterator itr = cacheEntries.keySet().iterator(); while (itr.hasNext()) { String principal = (String) itr.next(); CacheEntry ce = (CacheEntry) cacheEntries.get(principal); sb.append("\nPrincipal: ").append(principal); sb.append(ce.toString()); } } else { sb.append("<empty>"); } sb.append("\n----------- END CACHE BLOCK -----------"); return sb.toString(); }
// ------------------------------ private helpers for the tests private void insert3(byte type, int op1, int op2, int answer) { final CacheEntry ce = access3(type, op1, op2); ce.type = type; ce.op1 = op1; ce.op2 = op2; ce.ret = answer; }
@Override public HighlightField highlight(HighlighterContext context) { try { CacheEntry entry = (CacheEntry) context.hitContext.cache().get(CACHE_KEY); if (entry == null) { entry = new CacheEntry(); // Build the QueryWeigher with the top level reader to get all the frequency information entry.queryWeigher = new BasicQueryWeigher( new ElasticsearchQueryFlattener(100), context.hitContext.topLevelReader(), context.query.originalQuery()); context.hitContext.cache().put(CACHE_KEY, entry); } HighlightExecutionContext executionContext = new HighlightExecutionContext(context, entry); try { return executionContext.highlight(); } finally { executionContext.cleanup(); } } catch (Exception e) { throw new FetchPhaseExecutionException( context.context, "Failed to highlight field [" + context.fieldName + "]", e); } }
/** * 创建一个图标缓存 * * @param componentName * @param info * @param labelCache * @return */ private CacheEntry cacheLocked( ComponentName componentName, ResolveInfo info, HashMap<Object, CharSequence> labelCache) { // 通过componentName在集合中获取图标缓存 CacheEntry entry = mCache.get(componentName); // 如果缓存为空,则创建缓存 if (entry == null) { entry = new CacheEntry(); mCache.put(componentName, entry); // 获得ComponentName 用它作为Key ComponentName key = getComponentNameFromResolveInfo(info); // 如果标签缓存不为空,并且集合中有这个键。则从集合中获得应用的标题 if (labelCache != null && labelCache.containsKey(key)) { entry.title = labelCache.get(key).toString(); } else { // 否则 通过通过ResolveInfo获得程序名,作为标题 entry.title = info.loadLabel(mPackageManager).toString(); // 如果标签集合不为空则将新的标签放入集合 if (labelCache != null) { labelCache.put(key, entry.title); } } // 如果标题为空 if (entry.title == null) { // 则从info中获得标题 entry.title = info.activityInfo.name; } // 为entry获得图标 entry.icon = Utilities.createIconBitmap(getFullResIcon(info), mContext); } return entry; }
public void init(@NotNull final LogicalPosition logical, final @NotNull List<CacheEntry> cache) { reset(); myTargetLogical = logical; int start = 0; int end = cache.size() - 1; // We inline binary search here because profiling indicates that it becomes bottleneck to use // Collections.binarySearch(). while (start <= end) { int i = (end + start) >>> 1; CacheEntry cacheEntry = cache.get(i); // There is a possible case that single logical line is represented on multiple visual lines // due to soft wraps processing. // Hence, we check for bot logical line and logical columns during searching 'anchor' cache // entry. if (cacheEntry.endLogicalLine < logical.line || (cacheEntry.endLogicalLine == logical.line && myStorage.getSoftWrap(cacheEntry.endOffset) != null && cacheEntry.endLogicalColumn <= logical.column)) { start = i + 1; continue; } if (cacheEntry.startLogicalLine > logical.line || (cacheEntry.startLogicalLine == logical.line && cacheEntry.startLogicalColumn > logical.column)) { end = i - 1; continue; } // There is a possible case that currently found cache entry corresponds to soft-wrapped line // and soft wrap occurred // at target logical column. We need to return cache entry for the next visual line then // (because single logical column // is shared for 'before soft wrap' and 'after soft wrap' positions and we want to use the one // that points to // 'after soft wrap' position). if (cacheEntry.endLogicalLine == logical.line && cacheEntry.endLogicalColumn == logical.column && i < cache.size() - 1) { CacheEntry nextLineCacheEntry = cache.get(i + 1); if (nextLineCacheEntry.startLogicalLine == logical.line && nextLineCacheEntry.startLogicalColumn == logical.column) { setInitialPosition(nextLineCacheEntry.buildStartLinePosition()); return; } } setInitialPosition(cacheEntry.buildStartLinePosition()); return; } throw new IllegalStateException( String.format( "Can't map logical position (%s) to visual position. Reason: no cached information information about target visual " + "line is found. Registered entries: %s", logical, cache)); }
private void clearEntry(Context context, CacheEntry entry) { LogUtils.d(Logging.LOG_TAG, "clearEntry"); entry.mAccessToken = ""; entry.mRefreshToken = ""; entry.mExpirationTime = 0; saveEntry(context, entry); mCache.remove(entry.mAccountId); }
public synchronized boolean hasCompleteSet(String principalDN) { CacheEntry ce = (CacheEntry) cacheEntries.get(principalDN); boolean completeSet = false; if (ce != null && !hasExpiredAndUpdated()) { completeSet = ce.isCompleteSet(); } return completeSet; }
public void purge() { CacheEntry queueEntry = expirationQueue.peek(); while ((queueEntry != null) && queueEntry.isExpired()) { super.remove(queueEntry.getKey()); expirationQueue.remove(); queueEntry = expirationQueue.peek(); } }
protected static void assertMapEntries( Map<Object, Object> expected, InMemoryBasedCacheSupport<Object, Object> cache) { assertEquals("Length not currect", expected.size(), cache.getEntries().size()); for (final Object key : expected.keySet()) { final CacheEntry<?, ?> entry = cache.getEntries().get(key); assertNotNull("Entry for key '" + key + "' is null!", entry); assertEquals("key '" + key + "'", expected.get(key), entry.getValue().getValue()); } }
public V get(long key) { CacheEntry<V> e = map.get(key); if (e == null) { missCounter.incrementAndGet(); return null; } e.lastAccessed = accessCounter.incrementAndGet(); return e.value; }
public V get(K key) { CacheEntry<K, V> e = map.get(key); if (e == null) { if (islive) stats.missCounter.incrementAndGet(); return null; } if (islive) e.lastAccessed = stats.accessCounter.incrementAndGet(); return e.value; }
/** Update all dirty cache objects to the underlying RecordManager. */ protected void updateCacheEntries() throws IOException { Iterator<CacheEntry> iter = _hash.valuesIterator(); while (iter.hasNext()) { CacheEntry entry = iter.next(); if (entry._isDirty) { _recman.update(entry._recid, entry._obj, entry._serializer); entry._isDirty = false; } } }
/** Add a CacheEntry. Entry goes at the end of the list. */ protected void addEntry(CacheEntry entry) { if (_first == null) { _first = entry; _last = entry; } else { _last._next = entry; entry._previous = _last; _last = entry; } }
public int compareTo(CacheEntry rhs) { // Order first by attribute Id if (value.getAttrId() < rhs.getValue().getAttrId()) return -1; if (value.getAttrId() > rhs.getValue().getAttrId()) return 1; // then by class name int strcmp = value.getClass().getName().compareTo(rhs.getValue().getClass().getName()); if (strcmp != 0) return strcmp; // then by value return value.compareAttribute(rhs.getValue()); }
// Javadoc inherited. public Object perform(MethodActionEvent event) throws Throwable { CacheEntry entry = (CacheEntry) event.getArgument(CacheEntry.class); if (hasEntry) { Assert.assertSame(expectedKey, entry.getKey()); Assert.assertSame(expectedValue, entry.getValue()); } else { Assert.assertNull(entry); } return null; }
/** * Show the cached object. * * @param info the font info * @param character the encoded character */ public CharWidth showCachedCharacter( FontInfo info, AffineTransform ctm, Point2D curpt, String character) { this.character = character; CacheEntry key = new CacheEntry(info, character); CacheEntry val = (CacheEntry) cache.get(key); if (val == null) return null; ctm.translate(curpt.getX(), curpt.getY()); AffineTransform ftm = info.getFontMatrix(); ctm.concatenate(ftm); show(val.getObject(), ctm); return val.getCharWidth().transform(ftm); }
/** Fill in "application" with the icon and label for "info." */ public void getTitleAndIcon(ApplicationInfo application, ResolveInfo info) { synchronized (mCache) { CacheEntry entry = cacheLocked(application.componentName, info); if (entry.titleBitmap == null) { entry.titleBitmap = mBubble.createTextBitmap(entry.title); } application.title = entry.title; application.titleBitmap = entry.titleBitmap; application.iconBitmap = entry.icon; } }
/** * Purge least recently used object from the cache * * @return recyclable CacheEntry */ protected CacheEntry purgeEntry() throws IOException { CacheEntry entry = _first; if (entry == null) return new CacheEntry(-1, null, null, false); if (entry._isDirty) _recman.update(entry._recid, entry._obj, entry._serializer); removeEntry(entry); _hash.remove(entry._recid); entry._obj = null; entry._serializer = null; entry._isDirty = false; return entry; }
public static void put( final NodeInterface startNode, final NodeInterface endNode, final PermissionResolutionMask mask) { final CacheEntry entry = getOrCreateCacheEntry(startNode, endNode); // remember UUIDs allUuids.add(startNode.getUuid()); allUuids.add(endNode.getUuid()); entry.mask = mask; }
public CEResource lookup(final String key) { if (key == null || cache == null) { return null; } CacheEntry entry = (CacheEntry) cache.get(key); if (entry != null) { return (CEResource) entry.getCEResource().clone(); } return null; }
public long bytesInCache() { final ResourceServletConfiguration cpv = resourceServletConfiguration; final Map<CacheKey, CacheEntry> responseCache = getCacheMap(); final Map<CacheKey, CacheEntry> cacheCopy = new HashMap<>(); cacheCopy.putAll(responseCache); long cacheByteCount = 0; for (final CacheKey cacheKey : cacheCopy.keySet()) { final CacheEntry cacheEntry = responseCache.get(cacheKey); if (cacheEntry != null && cacheEntry.getEntity() != null) { cacheByteCount += cacheEntry.getEntity().length; } } return cacheByteCount; }
/** * Indicates whether or not the cache entry is stale. * * @param cacheEntry The cache entry to test the freshness of. * @param refreshPeriod The maximum allowable age of the entry, in seconds. * @param cronExpiry A cron expression specifying absolute date(s) and/or time(s) that the cache * entry should expire at. If the cache entry was refreshed prior to the most recent match for * the cron expression, the entry will be considered stale. * @return <code>true</code> if the entry is stale, <code>false</code> otherwise. */ protected boolean isStale(CacheEntry cacheEntry, int refreshPeriod, String cronExpiry) { boolean result = cacheEntry.needsRefresh(refreshPeriod) || isFlushed(cacheEntry); if ((!result) && (cronExpiry != null) && (cronExpiry.length() > 0)) { try { FastCronParser parser = new FastCronParser(cronExpiry); result = result || parser.hasMoreRecentMatch(cacheEntry.getLastUpdate()); } catch (ParseException e) { log.warn(e); } } return result; }
public AbstractDomainObject lookup(String key) { processQueue(); CacheEntry entry = this.cache.get(key); if (entry != null) { AbstractDomainObject result = entry.get(); if (result != null) { return result; } else { removeEntry(entry); return null; } } else { return null; } }
/** * Gets an entry for the package, which can be used as a fallback entry for various components. * This method is not thread safe, it must be called from a synchronized method. */ private CacheEntry getEntryForPackageLocked( String packageName, UserHandleCompat user, boolean useLowResIcon) { ComponentKey cacheKey = getPackageKey(packageName, user); CacheEntry entry = mCache.get(cacheKey); if (entry == null || (entry.isLowResIcon && !useLowResIcon)) { entry = new CacheEntry(); boolean entryUpdated = true; // Check the DB first. if (!getEntryFromDB(cacheKey, entry, useLowResIcon)) { try { int flags = UserHandleCompat.myUserHandle().equals(user) ? 0 : PackageManager.GET_UNINSTALLED_PACKAGES; PackageInfo info = mPackageManager.getPackageInfo(packageName, flags); ApplicationInfo appInfo = info.applicationInfo; if (appInfo == null) { throw new NameNotFoundException("ApplicationInfo is null"); } Drawable drawable = mUserManager.getBadgedDrawableForUser(appInfo.loadIcon(mPackageManager), user); entry.icon = Utilities.createIconBitmap(drawable, mContext); entry.title = appInfo.loadLabel(mPackageManager); entry.contentDescription = mUserManager.getBadgedLabelForUser(entry.title, user); entry.isLowResIcon = false; // Add the icon in the DB here, since these do not get written during // package updates. ContentValues values = newContentValues(entry.icon, entry.title.toString(), mPackageBgColor); addIconToDB( values, cacheKey.componentName, info, mUserManager.getSerialNumberForUser(user)); } catch (NameNotFoundException e) { if (DEBUG) Log.d(TAG, "Application not installed " + packageName); entryUpdated = false; } } // Only add a filled-out entry to the cache if (entryUpdated) { mCache.put(cacheKey, entry); } } return entry; }
public void unbindDrawables() { if (Launcher.LOGD) Log.d(TAG, "unbindDrawables"); synchronized (mCache) { for (CacheEntry ce : mCache.values()) { if (null != ce.icon) { ce.icon.recycle(); ce.icon = null; } if (null != ce.titleBitmap) { ce.titleBitmap.recycle(); ce.titleBitmap = null; } } } }
// ----- private methods ----- private static CacheEntry getOrCreateCacheEntry( final NodeInterface startNode, final NodeInterface endNode) { final String cacheKey = cacheKey(startNode, endNode); CacheEntry entry = cache.get(cacheKey); if (entry == null) { entry = new CacheEntry(); entry.key = cacheKey; cache.put(cacheKey, entry); } return entry; }