Java Code Examples for java.util.WeakHashMap#put()

The following examples show how to use java.util.WeakHashMap#put() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: WeakSetPrototype.java    From es6draft with MIT License 6 votes vote down vote up
/**
 * 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;
}
 
Example 2
Source File: WeakHashMapUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@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));
}
 
Example 3
Source File: LatinKeyboardBaseView.java    From hackerskeyboard with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 4
Source File: BadgrServiceImpl.java    From sunbird-lms-service with MIT License 6 votes vote down vote up
@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;
}
 
Example 5
Source File: XulUtils.java    From starcor.xul with GNU Lesser General Public License v3.0 5 votes vote down vote up
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);
	}
}
 
Example 6
Source File: not_covered_not_covered_t.java    From coming with MIT License 5 votes vote down vote up
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);
}
 
Example 7
Source File: not_covered_not_covered_s.java    From coming with MIT License 5 votes vote down vote up
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);
}
 
Example 8
Source File: ObjectStreamClass.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * 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;

}
 
Example 9
Source File: CopyOnWriteWeakHashMap.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example 10
Source File: StringUtil.java    From qaf with MIT License 5 votes vote down vote up
/**
 * @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;
}
 
Example 11
Source File: CopyOnWriteWeakHashMap.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example 12
Source File: WeakHashMapDemo.java    From code with Apache License 2.0 5 votes vote down vote up
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
}
 
Example 13
Source File: SunToolkit.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
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);
}
 
Example 14
Source File: MenuWrapper.java    From zhangshangwuda with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 15
Source File: MenuWrapper.java    From CSipSimple with GNU General Public License v3.0 5 votes vote down vote up
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);
}
 
Example 16
Source File: XMutexTest.java    From xsync with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 17
Source File: MenuWrapper.java    From Libraries-for-Android-Developers with MIT License 5 votes vote down vote up
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);
}
 
Example 18
Source File: DocValuesCache.java    From SearchServices with GNU Lesser General Public License v3.0 4 votes vote down vote up
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;
    }
}
 
Example 19
Source File: ToStringBuilderStyle.java    From lite-pool with Apache License 2.0 4 votes vote down vote up
/**
 * 
 */
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);
}
 
Example 20
Source File: Misc.java    From uima-uimaj with Apache License 2.0 3 votes vote down vote up
/**
 * 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;      
  }
}