Cost of using weak references in Java

后端 未结 3 1093
渐次进展
渐次进展 2020-12-23 13:51

Has anyone researched the runtime costs involved in creating and garbage collecting Java WeakReference objects? Are there any performance issues (e.g. contention) for multi

3条回答
  •  一生所求
    2020-12-23 14:33

    cache using weak references may significantly slow down your app if it's rebuild on demand e.g. in getters:

    public Object getSomethingExpensiveToFind() {
        if(cache.contains(EXPENSIVE_OBJ_KEY)) {
            return cache.get(EXPENSIVE_OBJ_KEY);
        }
    
        Object sth = obtainSomethingExpensiveToFind(); // computationally expensive
        cache.put(EXPENSIVE_OBJ_KEY, sth);
        return sth;
    } 
    

    imagine this scenario:

    1) app is running low on memory

    2) GC cleans weak references, thus cache is cleared too

    3) app continues, a lot of methods like getSomethingExpensiveToFind() are invoked and rebuild the cache

    4) app is running low on memory again

    5) GC cleans wear references, clears cache

    6) app continues, a lot of methods like getSomethingExpensiveToFind() are invoked and rebuild the cache again

    7) and so on...

    I came upon such problem - the app was interrupted by GC very often and it compeletly defeated the whole point of caching.

    In other words, if improperly managed, weak references can slow down your application.

提交回复
热议问题