/** * 保存到缓存中 * * @param cacheKey * @param value */ public void putObect(CacheKey ckey, Object value) { if (ckey == null) return; if (cache.contain(ckey.getKey())) return; cache.put(ckey.getKey(), new CacheableWrapper(ckey.getDataKey(), value)); Debug.logVerbose( "[JdonFramework]<-cache->save cache: " + ckey.getKey() + ", cache size:" + cache.size(), module); }
/** * Selects a faction from the salvage list and generates a table using the same parameters as this * table, but from five years earlier. Generated tables are cached for later use. If the generated * table contains no units, it is discarded and the selected entry is deleted. This continues * until either a unit is generated or there are no remaining entries. * * @param filter - passed to generateUnit() in the generated table. * @return - a unit generated from another faction, or null if none of the factions in the salvage * list contain any units that meet the parameters. */ private MechSummary generateSalvage(UnitFilter filter) { while (salvageTotal > 0) { int roll = Compute.randomInt(salvageTotal); TableEntry salvageEntry = null; for (TableEntry te : salvageTable) { if (roll < te.weight) { salvageEntry = te; break; } roll -= te.weight; } if (salvageEntry != null) { UnitTable salvage = UnitTable.findTable( salvageEntry.getSalvageFaction(), key.getUnitType(), key.getYear() - 5, key.getRating(), key.getWeightClasses(), key.getNetworkMask(), key.getMovementModes(), key.getRoles(), key.getRoleStrictness(), key.getFaction()); if (salvage.hasUnits()) { return salvage.generateUnit(filter); } else { salvageTotal -= salvageEntry.weight; salvageTable.remove(salvageEntry); } } } assert (salvageTable.isEmpty() && salvageTotal == 0); return null; }
/** * @param index * @return - a string representing the entry at the indicated index for use in the table */ public String getEntryText(int index) { if (index >= salvageTable.size()) { return unitTable.get(index - salvageTable.size()).getUnitEntry().getName(); } else { if (key.getFaction().isClan()) { return "Isorla: " + salvageTable.get(index).getSalvageFaction().getName(key.getYear() - 5); } else { return "Salvage: " + salvageTable.get(index).getSalvageFaction().getName(key.getYear() - 5); } } }
public String toString() { StrWriter out = new StrWriter(); out.print("address=" + address.get() + " dirty=" + dirty); return out.toString(); }
/** * 如果该cache已经存在,则不再创建并返回已有cache * * @param groupId 如果cache和账号无关,置为null,创建全局cache * @param expireTime 小于0(比如-1)则忽略超时 */ public <K, V> Cache<K, V> createPersistedLruExpireCache( String groupId, CacheKey cacheID, int capacity, long expireTime) { if (groupId == null) { groupId = GLOBAL_CACHE_GROUP_ID; } Map<CacheKey, Cache> caches; synchronized (cacheMap) { caches = cacheMap.get(groupId); if (caches == null) { caches = new ConcurrentHashMap<>(); cacheMap.put(groupId, caches); LogUtil.w(sTAG, groupId + " caches not exist, warning."); } } Cache<K, V> cache = caches.get(cacheID); if (cache == null) { try { cache = new PersistedLruExpireCache(cacheID.getKey(), groupId, capacity, 1, expireTime); caches.put(cacheID, cache); } catch (IOException e) { LogUtil.e(sTAG, e.getMessage(), e); } } else { cache.setCapacity(capacity); } return cache; }
/** * Look-up the value through the cache. This always evaluates the {@code subKeyFactory} function * and optionally evaluates {@code valueFactory} function if there is no entry in the cache for * given pair of (key, subKey) or the entry has already been cleared. * * @param key possibly null key * @param parameter parameter used together with key to create sub-key and value (should not be * null) * @return the cached value (never null) * @throws NullPointerException if {@code parameter} passed in or {@code sub-key} calculated by * {@code subKeyFactory} or {@code value} calculated by {@code valueFactory} is null. */ public V get(K key, P parameter) { Objects.requireNonNull(parameter); expungeStaleEntries(); Object cacheKey = CacheKey.valueOf(key, refQueue); // lazily install the 2nd level valuesMap for the particular cacheKey ConcurrentMap<Object, Supplier<V>> valuesMap = map.get(cacheKey); if (valuesMap == null) { ConcurrentMap<Object, Supplier<V>> oldValuesMap = map.putIfAbsent(cacheKey, valuesMap = new ConcurrentHashMap<>()); if (oldValuesMap != null) { valuesMap = oldValuesMap; } } // create subKey and retrieve the possible Supplier<V> stored by that // subKey from valuesMap Object subKey = Objects.requireNonNull(subKeyFactory.apply(key, parameter)); Supplier<V> supplier = valuesMap.get(subKey); Factory factory = null; while (true) { if (supplier != null) { // supplier might be a Factory or a CacheValue<V> instance V value = supplier.get(); if (value != null) { return value; } } // else no supplier in cache // or a supplier that returned null (could be a cleared CacheValue // or a Factory that wasn't successful in installing the CacheValue) // lazily construct a Factory if (factory == null) { factory = new Factory(key, parameter, subKey, valuesMap); } if (supplier == null) { supplier = valuesMap.putIfAbsent(subKey, factory); if (supplier == null) { // successfully installed Factory supplier = factory; } // else retry with winning supplier } else { if (valuesMap.replace(subKey, supplier, factory)) { // successfully replaced // cleared CacheEntry / unsuccessful Factory // with our Factory supplier = factory; } else { // retry with current supplier supplier = valuesMap.get(subKey); } } } }
private void cacheMarkDirty(CacheKey key) { if (cache != null) { int index = key.ordinal(); cache[index] = null; cacheState[index] = STATE_NOT_CACHED; } }
@Test public void shouldTestCacheKeysEqual() { Date date = new Date(); CacheKey key1 = new CacheKey(new Object[] {1, "hello", null, new Date(date.getTime())}); CacheKey key2 = new CacheKey(new Object[] {1, "hello", null, new Date(date.getTime())}); assertTrue(key1.equals(key2)); assertTrue(key2.equals(key1)); assertTrue(key1.hashCode() == key2.hashCode()); assertTrue(key1.toString().equals(key2.toString())); }
@Test public void shouldTestCacheKeysNotEqualDueToOrder() throws Exception { CacheKey key1 = new CacheKey(new Object[] {1, "hello", null}); Thread.sleep(1000); CacheKey key2 = new CacheKey(new Object[] {1, null, "hello"}); assertFalse(key1.equals(key2)); assertFalse(key2.equals(key1)); assertFalse(key1.hashCode() == key2.hashCode()); assertFalse(key1.toString().equals(key2.toString())); }
private void populateCache(int index) { if (cache == null) { int size = CacheKey.values().length; cache = new Object[size]; cacheState = new byte[size]; } if (cacheState[index] == STATE_NOT_CACHED) { CacheKey key = CacheKey.values()[index]; if (getJSONObject().has(key.name())) { cache[index] = key.extractValue(this); cacheState[index] = STATE_CACHED_VALUE; } else { cacheState[index] = STATE_CACHED_NO_VALUE; } } }
private void write() throws IOException { if (isFree()) throw new IllegalArgumentException("cannot write a free element"); elem.clear(); long addr = address.get() * elementSize; for (int i = 0; i < nrfats; i++) { api.write(addr, elem); addr += fatsize; elem.clear(); } }
public void test() { Vector primaryKeys = new Vector(); primaryKeys.add(new java.math.BigDecimal(4)); CacheKey cacheKey = getAbstractSession() .getIdentityMapAccessorInstance() .acquireDeferredLock( primaryKeys, Employee.class, getSession().getDescriptor(Employee.class), false); CacheKey cacheKey2 = getAbstractSession() .getIdentityMapAccessorInstance() .acquireDeferredLock( primaryKeys, Employee.class, getSession().getDescriptor(Employee.class), false); if (cacheKey != cacheKey2) { throw new TestErrorException( "WeakIdentityMap failed to return same cachkey for successive calls for same primary key and class"); } // must release because the deferred lock is not removed on an initialize identity map cacheKey.releaseDeferredLock(); cacheKey2.releaseDeferredLock(); }
private static void evaluateAccessor( Object request, CachableValueAccessor node, CacheKey key, boolean isRoot) throws ServiceException { try { Object value = null; if (!isRoot) { if (node.m_accessor != null) { if (request != null) { value = node.m_accessor.invoke(request, (Object[]) null); } else { value = null; } } } else { value = request; } // walk down the accessor structure and apply the method. if (node.m_elementAccessors.size() != 0) { Iterator i = node.m_elementAccessors.keySet().iterator(); while (i.hasNext()) { CachableValueAccessor childAccessor = node.m_elementAccessors.get(i.next()); evaluateAccessor(value, childAccessor, key, false); } } else { // we've reached the leaf. Insert to cache key key.add(node.m_fullPath, value); } } catch (IllegalAccessException e) { throw new ServiceException( ErrorDataFactory.createErrorData( ErrorConstants.SVC_CLIENT_CACHE_NOT_SUPPORTED, ErrorConstants.ERRORDOMAIN), e); } catch (IllegalArgumentException e) { throw new ServiceException( ErrorDataFactory.createErrorData( ErrorConstants.SVC_CLIENT_CACHE_NOT_SUPPORTED, ErrorConstants.ERRORDOMAIN), e); } catch (InvocationTargetException e) { throw new ServiceException( ErrorDataFactory.createErrorData( ErrorConstants.SVC_CLIENT_CACHE_NOT_SUPPORTED, ErrorConstants.ERRORDOMAIN), e); } }
@Test public void shouldDemonstrateEmptyAndNullKeysAreEqual() { CacheKey key1 = new CacheKey(); CacheKey key2 = new CacheKey(); assertEquals(key1, key2); assertEquals(key2, key1); key1.update(null); key2.update(null); assertEquals(key1, key2); assertEquals(key2, key1); key1.update(null); key2.update(null); assertEquals(key1, key2); assertEquals(key2, key1); }
private boolean deleteTokenCacheItem( String authority, String itemAuthority, String resource, String clientId, String userId, boolean isMultipleResourceRefreshToken) { final AuthenticationContext authContext; try { authContext = getOrCreateContext(authority); } catch (Exception e) { callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, e.getMessage())); return true; } String key = CacheKey.createCacheKey( itemAuthority, resource, clientId, isMultipleResourceRefreshToken, userId); authContext.getCache().removeItem(key); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK)); return true; }
private CacheElement get(long address) { key.set(address); return get(key); }
private void expungeStaleEntries() { CacheKey<K> cacheKey; while ((cacheKey = (CacheKey<K>) refQueue.poll()) != null) { cacheKey.expungeFrom(map, reverseMap); } }
/** * Initializes table based on values provided by key * * @param key - a structure providing the parameters for generating the table */ protected UnitTable(CacheKey key) { this.key = key; /** * Generate the RAT, then go through it to build the NavigableMaps that will be used for random * selection. */ if (key.getFaction().isActiveInYear(key.getYear())) { List<TableEntry> table = RATGenerator.getInstance() .generateTable( key.getFaction(), key.getUnitType(), key.getYear(), key.getRating(), key.getWeightClasses(), key.getNetworkMask(), key.getMovementModes(), key.getRoles(), key.getRoleStrictness(), key.getDeployingFaction()); Collections.sort(table); table.forEach( te -> { if (te.isUnit()) { unitTotal += te.weight; unitTable.add(te); } else { salvageTotal += te.weight; salvageTable.add(te); } }); if (salvageTotal + unitTotal > 0) { salvagePct = salvageTotal * 100 / (salvageTotal + unitTotal); } } }
private boolean cacheHasKey(CacheKey key) { int index = key.ordinal(); populateCache(index); return cacheState[index] == STATE_CACHED_VALUE; }
private void cacheRemoveValue(CacheKey key) { int index = key.ordinal(); populateCache(index); cache[index] = null; cacheState[index] = STATE_CACHED_NO_VALUE; }
private boolean cacheValueIsNotNull(CacheKey key) { int index = key.ordinal(); populateCache(index); return cache[index] != null; }
private <T> T cacheGet(CacheKey key) { int index = key.ordinal(); populateCache(index); return (T) cache[index]; }
private Object peekCache(String key, int userId) { synchronized (mCache) { // Safe to reuse mCacheKey, because it is not stored in the map. return mCache.get(mCacheKey.set(key, userId)); } }
private void free() throws IOException { if (isFree()) throw new IllegalArgumentException("cannot free a free element"); flush(); address.free(); }
private boolean isFree() { return address.isFree(); }
private void invalidateCache(String key, int userId) { synchronized (mCache) { // Safe to reuse mCacheKey, because it is not stored in the map. mCache.remove(mCacheKey.set(key, userId)); } }
/** * Static utility for creating the cacheKey. * * @param opName An operation name. * @param request A request object of this operation. * @param accessorCache A CachableValueAccessor for accessing the Cached value. * @return A CacheKey for the given request object. * @throws ServiceException Exception during CacheKey generation. */ public static CacheKey generateCacheKey( String opName, Object request, CachableValueAccessor accessorCache) throws ServiceException { CacheKey key = CacheKey.createCacheKey(opName); evaluateAccessor(request, accessorCache, key, true); return key; }