Search code examples
javaintegerhashmapnettyinternal

ConcurrentIdentityWeakKeyHashMap and Integer keys


Though internal, I presumed that it is safe to use ConcurrentIdentityWeakKeyHashMap generally. However, the following code:

ConcurrentIdentityWeakKeyHashMap map = new ConcurrentIdentityWeakKeyHashMap();
for(int key = 0;  key < 132; key++){
     map.put(key, key);
 }
for(int key = 0;  key < 132; key++){
     System.out.println(map.get(key));
 }

produces:

0
1
..
124
125
126
127
null
null
null
null

Is this a bug or a misconception on my side (i.e. "shouldn't be used with Integers" or "internal use only")?

EDIT: based on Lucianos comments, I altered the code a bit to make it hold a reference to the (I hope at least) very same Integer in the list and in the map:

 ArrayList<Integer> list = new ArrayList<Integer>(132);
 ConcurrentIdentityWeakKeyHashMap<Integer, Integer> map = new ConcurrentIdentityWeakKeyHashMap<Integer, Integer>();
 for(int key = 0;  key < 132; key++){
     Integer key2 = key;
     list.add(key2);
     map.put(key2, key2);
 }
 for(int key = 0; key < 132; key++){
     System.out.println(map.get(list.get(key)));
 }

Now, it works...


Solution

  • Integer up to 127 are precached in the Integer class, so they will never be garbage collected.