0

I am stuck in a problem and really need some help to go through this In my application. I have a ConcurrentHashMap where multiple can thread can store or retrieve data simultaneously. To solve this issue I have chosen. Now the problem after certain period of time few of the data's are not needed any more in my application. So, I need them to be garbage collected. In case of WeakHashMap it's easy because whnever the key will be null the values will be removed too for garbage collection. Nut how to implement WeakReference style for ConcurrentHashMap.

Souvik
  • 1,219
  • 3
  • 16
  • 38

2 Answers2

1

Depending on your performance requirements you may find using Collections.synchronizedMap(weakHashMap) the simplest option.

OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213
  • But this will not allow multiple thread to work on the map simultaneousness. So, the performance will be compromised. In my case performance contains a very good point – Souvik Aug 19 '13 at 12:09
  • In that case you could check [this](http://stackoverflow.com/q/2255950/823393) question for some further ideas. – OldCurmudgeon Aug 19 '13 at 12:15
  • Google multimap and WeakHashMap is not work exactly in same way(As per the comments in the POST) – Souvik Aug 19 '13 at 19:29
0
class ConcurrentWeekHashMap<K, V> {
    private val lock = ConcurrentHashMap<K, V>()
    private val weekMap = WeakHashMap<K, V>()

    fun put(key: K, value: V): V? {
        var result: V? = null
        lock.compute(key) { _, _ ->
            result = weekMap.put(key, value)
            null
        }
        return result
    }

    fun get(key: K): V? {
        var result: V? = null
        lock.compute(key) { _, _ ->
            result = weekMap[key]
            null
        }
        return result
    }

    ...

}

sevendark
  • 1
  • 1