fr4gus
fr4gus

Reputation: 396

NullpointerException using put method on a LinkedHashMap

I'm using a LinkedHashMap as cache. I've overridden removeEldestEntry in order to force this cache to have a fixed size. Older values will be removed. This is how my map is initialized:

<!-- language: lang-java -->
    sBackgroundBitmapCache = new LinkedHashMap<String, Bitmap>(backgroundCacheSize) {
        private static final long serialVersionUID = 287204858147490218L;

        @Override
        protected boolean removeEldestEntry(LinkedHashMap.Entry<String, Bitmap> eldest) {
            if (size() > backgroundCacheSize) {
                Log.d(TAG, "Removing hash " + eldest.getKey() + " from background cache");
                return true;
            } else {
                return false;
            }
        }
    };

So obviously I'm going to use that cache using put method. But I'm getting crash reports, when using put method:

java.lang.NullPointerException
at java.util.LinkedHashMap.postRemove(LinkedHashMap.java:291)
at java.util.HashMap.remove(HashMap.java:637)
at java.util.LinkedHashMap.addNewEntry(LinkedHashMap.java:186)
at java.util.HashMap.put(HashMap.java:411)

I haven't been able to find why, using put method, may cause a nullpointer exception. I'm 100% sure, key and value are not nulls.

Any help will be appreciated.

-f4

Upvotes: 1

Views: 1492

Answers (1)

parkerfath
parkerfath

Reputation: 1649

As Mike said, the problem could be related to trying to use the cache from multiple threads. I had the same problem and seem to have fixed it by making sure all the put()s happened from the UI thread.

Upvotes: 1

Related Questions