下面列出了java.util.WeakHashMap#put ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 23.4.3.1 WeakSet.prototype.add ( value )
*
* @param cx
* the execution context
* @param thisValue
* the function this-value
* @param value
* the new value
* @return this weak set object
*/
@Function(name = "add", arity = 1, nativeId = WeakSetPrototypeAdd.class)
public static Object add(ExecutionContext cx, Object thisValue, Object value) {
/* steps 1-3 */
WeakSetObject s = thisWeakSetObject(cx, thisValue, "WeakSet.prototype.add");
/* step 4 */
if (!Type.isObject(value)) {
throw newTypeError(cx, Messages.Key.WeakSetKeyNotObject);
}
/* step 5 */
WeakHashMap<ScriptObject, Boolean> entries = s.getWeakSetData();
/* steps 6-7 */
entries.put(Type.objectValue(value), Boolean.TRUE);
/* step 8 */
return s;
}
@Override
@SuppressWarnings("unchecked")
public Response getAssertionList(Request request) throws IOException {
Map<String, Object> filterMap = (Map<String, Object>) request.getRequest().get(JsonKey.FILTERS);
List<String> requestData = (List) filterMap.get(BadgingJsonKey.ASSERTIONS);
List<Map<String, Object>> responseList = new ArrayList<>();
for (String assertionId : requestData) {
WeakHashMap<String, Object> map = new WeakHashMap<>();
map.put(BadgingJsonKey.ASSERTION_ID, assertionId);
String url = BadgingUtil.createBadgerUrl(map, BadgingUtil.SUNBIRD_BADGER_GETASSERTION_URL, 3);
HttpUtilResponse httpResponse = HttpUtil.doGetRequest(url, BadgingUtil.getBadgrHeaders());
if (httpResponse.getStatusCode() == 200) {
Map<String, Object> res = mapper.readValue(httpResponse.getBody(), HashMap.class);
// calling to create response as per sunbird
res = BadgingUtil.prepareAssertionResponse(res, new HashMap<String, Object>());
responseList.add(res);
}
}
Response response = new Response();
response.getResult().put(BadgingJsonKey.ASSERTIONS, responseList);
return response;
}
private Keyboard getLongPressKeyboard(Key popupKey) {
final WeakHashMap<Key, Keyboard> cache;
if (popupKey.isDistinctCaps()) {
cache = mMiniKeyboardCacheCaps;
} else if (popupKey.isShifted()) {
cache = mMiniKeyboardCacheShift;
} else {
cache = mMiniKeyboardCacheMain;
}
Keyboard kbd = cache.get(popupKey);
if (kbd == null) {
kbd = popupKey.getPopupKeyboard(getContext(), getPaddingLeft() + getPaddingRight());
if (kbd != null) cache.put(popupKey, kbd);
}
//Log.i(TAG, "getLongPressKeyboard returns " + kbd + " for " + popupKey);
return kbd;
}
@Test
public void givenWeakHashMap_whenCacheValueThatHasNoReferenceToIt_GCShouldReclaimThatObjectButLeaveReferencedObject() {
//given
WeakHashMap<UniqueImageName, BigImage> map = new WeakHashMap<>();
BigImage bigImageFirst = new BigImage("foo");
UniqueImageName imageNameFirst = new UniqueImageName("name_of_big_image");
BigImage bigImageSecond = new BigImage("foo_2");
UniqueImageName imageNameSecond = new UniqueImageName("name_of_big_image_2");
map.put(imageNameFirst, bigImageFirst);
map.put(imageNameSecond, bigImageSecond);
assertTrue(map.containsKey(imageNameFirst));
assertTrue(map.containsKey(imageNameSecond));
//when
imageNameFirst = null;
System.gc();
//then
await().atMost(10, TimeUnit.SECONDS).until(() -> map.size() == 1);
await().atMost(10, TimeUnit.SECONDS).until(() -> map.containsKey(imageNameSecond));
}
private static void myWeakHashMap() {
WeakHashMap<Integer, String> map = new WeakHashMap<>();
Integer key = new Integer(2);
String value = "WeakHashMap";
map.put(key, value);
System.out.println(map);
key = null;
System.out.println(map);
System.gc();
System.out.println(map);//null
}
public void invalidate() {
if (mNativeMap.isEmpty()) return;
final WeakHashMap<android.view.MenuItem, MenuItem> menuMapCopy = new WeakHashMap<android.view.MenuItem, MenuItem>(mNativeMap.size());
for (int i = 0; i < mNativeMenu.size(); i++) {
final android.view.MenuItem item = mNativeMenu.getItem(i);
menuMapCopy.put(item, mNativeMap.get(item));
}
mNativeMap.clear();
mNativeMap.putAll(menuMapCopy);
}
@Test
public void testWeakMapWithTwoEqualMutexes() {
// Arrange
XMutex<String> mutex1 = new XMutex<>(FIRST_KEY);
XMutex<String> mutex2 = new XMutex<>(SECOND_KEY);
WeakHashMap<XMutex<String>, WeakReference<XMutex<String>>> map = new WeakHashMap<>();
// Act
map.put(mutex1, new WeakReference<>(mutex1));
map.put(mutex2, new WeakReference<>(mutex2));
// Asserts
Assertions.assertThat(map.size()).isEqualTo(1);
}
public void invalidate() {
if (mNativeMap.isEmpty()) return;
final WeakHashMap<android.view.MenuItem, MenuItem> menuMapCopy = new WeakHashMap<android.view.MenuItem, MenuItem>(mNativeMap.size());
for (int i = 0; i < mNativeMenu.size(); i++) {
final android.view.MenuItem item = mNativeMenu.getItem(i);
menuMapCopy.put(item, mNativeMap.get(item));
}
mNativeMap.clear();
mNativeMap.putAll(menuMapCopy);
}
public void invalidate() {
if (mNativeMap.isEmpty()) return;
final WeakHashMap<android.view.MenuItem, MenuItem> menuMapCopy = new WeakHashMap<android.view.MenuItem, MenuItem>(mNativeMap.size());
for (int i = 0; i < mNativeMenu.size(); i++) {
final android.view.MenuItem item = mNativeMenu.getItem(i);
menuMapCopy.put(item, mNativeMap.get(item));
}
mNativeMap.clear();
mNativeMap.putAll(menuMapCopy);
}
public synchronized void setWindowDeactivationTime(Window w, long time) {
AppContext ctx = getAppContext(w);
if (ctx == null) {
return;
}
@SuppressWarnings("unchecked")
WeakHashMap<Window, Long> map = (WeakHashMap<Window, Long>)ctx.get(DEACTIVATION_TIMES_MAP_KEY);
if (map == null) {
map = new WeakHashMap<Window, Long>();
ctx.put(DEACTIVATION_TIMES_MAP_KEY, map);
}
map.put(w, time);
}
private static void _doSaveInfo(WeakHashMap<Canvas, ArrayList<CanvasSaveInfo>> stack, CanvasSaveInfo info) {
if (stack != null) {
ArrayList<CanvasSaveInfo> canvasSaveInfos = stack.get(info.canvas);
if (canvasSaveInfos == null) {
canvasSaveInfos = new ArrayList<CanvasSaveInfo>();
stack.put(info.canvas, canvasSaveInfos);
}
canvasSaveInfos.add(info);
}
}
@Override
public synchronized V put(K key, V value) {
WeakHashMap<K, V> tmp = new WeakHashMap<K, V>(map);
V result = tmp.put(key, value);
map = Collections.unmodifiableMap(tmp);
return result;
}
/**
* @param csvKeyVal
* array of key=value pair.
* @param ensureKeyUppercase
* : if true then it will set upper-case key for value
* @return map
*/
public static Map<String, String> toMap(String[] csvKeyVal, boolean ensureKeyUppercase) {
WeakHashMap<String, String> map = new WeakHashMap<String, String>();
if (null == csvKeyVal) {
return map;
}
for (String param : csvKeyVal) {
if (isNotBlank(param)) {
String[] kv = param.split("=", 2);
map.put(ensureKeyUppercase ? kv[0].toUpperCase() : kv[0], kv.length > 1 ? (kv[1]) : "");
}
}
return map;
}
@Override
public synchronized V put(K key, V value) {
WeakHashMap<K, V> tmp = new WeakHashMap<K, V>(map);
V result = tmp.put(key, value);
map = Collections.unmodifiableMap(tmp);
return result;
}
/**
* Return the descriptor (ObjectStreamClass) corresponding to the class
* {@code cl}. Returns an ObjectStreamClass even if instances of the
* class cannot be serialized
*
* @param cl
* a java.langClass for which to obtain the corresponding
* descriptor
* @return the corresponding descriptor
*/
static ObjectStreamClass lookupStreamClass(Class<?> cl) {
WeakHashMap<Class<?>, ObjectStreamClass> tlc = getCache();
ObjectStreamClass cachedValue = tlc.get(cl);
if (cachedValue == null) {
cachedValue = createClassDesc(cl);
tlc.put(cl, cachedValue);
}
return cachedValue;
}
public void invalidate() {
if (mNativeMap.isEmpty()) { return; }
final WeakHashMap<android.view.MenuItem, MenuItem> menuMapCopy = new WeakHashMap<android.view.MenuItem, MenuItem>(mNativeMap.size());
for (int i = 0; i < mNativeMenu.size(); i++) {
final android.view.MenuItem item = mNativeMenu.getItem(i);
menuMapCopy.put(item, mNativeMap.get(item));
}
mNativeMap.clear();
mNativeMap.putAll(menuMapCopy);
}
public void invalidate() {
if (mNativeMap.isEmpty()) { return; }
final WeakHashMap<android.view.MenuItem, MenuItem> menuMapCopy = new WeakHashMap<android.view.MenuItem, MenuItem>(mNativeMap.size());
for (int i = 0; i < mNativeMenu.size(); i++) {
final android.view.MenuItem item = mNativeMenu.getItem(i);
menuMapCopy.put(item, mNativeMap.get(item));
}
mNativeMap.clear();
mNativeMap.putAll(menuMapCopy);
}
/**
*
*/
static void register(Object v) {
if (v == null) return; WeakHashMap<Object, Object> m = REGISTRY.get();
if (m == null) REGISTRY.set((m = new WeakHashMap<>())); m.put(v, null);
}
public static synchronized NumericDocValues getNumericDocValues(String field, LeafReader reader) throws IOException
{
WeakHashMap<Object, NumericDocValues> fieldCache = cache.get(field);
if(fieldCache == null)
{
fieldCache = new WeakHashMap<Object, NumericDocValues>();
cache.put(field, fieldCache);
}
Object cacheKey = reader.getCoreCacheKey();
NumericDocValues cachedValues = fieldCache.get(cacheKey);
if(cachedValues == null)
{
NumericDocValues fieldValues = reader.getNumericDocValues(field);
if(fieldValues == null)
{
return null;
}
else
{
int maxDoc = reader.maxDoc();
boolean longs = false;
int[] intValues = new int[maxDoc]; //Always start off with an int array.
SettableDocValues settableValues = new IntValues(intValues);
for(int i=0; i<maxDoc; i++)
{
long value = fieldValues.get(i);
if(value > Integer.MAX_VALUE && !longs)
{
longs = true;
settableValues = new LongValues(intValues);
}
settableValues.set(i, value);
}
fieldCache.put(cacheKey, settableValues);
return settableValues;
}
}
else
{
return cachedValues;
}
}
/**
* Some objects can be shared, if "equal", rather than creating duplicates, if they're read-only.
* This may in general be beneficial by reducing the size of the "working set" via more sharing of read-only objects.
* Users should insure the read-only property.
* This routine allows
* a) creating a potentially sharable object
* b) checking to see if we already have an "equal" one, and
* c) if so, using that and allowing the just created one to be GC'd.
*
* Items in this "set" are held with weak references, so may be gc'd if no longer referenced anywhere.
* @param obj - the object to use a cached substitute for, if one exists
* @param cache - the cache
* @param <T> the type of the cached object
* @return - the object or a cached version of it.
*/
public static <T> T shareExisting(T obj, WeakHashMap<T, WeakReference<T>> cache) {
if (null == obj) {
throw new IllegalArgumentException();
}
T v;
synchronized (cache) {
WeakReference<T> r = cache.get(obj);
if (r == null || (v = r.get()) == null) {
cache.put(obj, new WeakReference<>(obj));
return obj;
}
return v;
}
}