2

I have used google guava in our application based on weakValues like below.

CacheBuilder
            .newBuilder()
            .weakValues()
            .concurrencyLevel(Runtime.getRuntime().availableProcessors())
            .removalListener(removalListener)
            .build(cacheLoader);

The removal listener is not called immediately after the cache weak value is removed. I have to clear native resource based on this and thus my program ends without releasing memory at native end. Is it a known issue?

Jose Ricardo Bustos M.
  • 8,016
  • 6
  • 40
  • 62
user2203937
  • 181
  • 1
  • 8

2 Answers2

2

In the Google Guava docs, it says the following:

Caches built with CacheBuilder do not perform cleanup and evict values "automatically," or instantly after a value expires, or anything of the sort. Instead, it performs small amounts of maintenance during write operations, or during occasional read operations if writes are rare.

It is also explained why they took this decision and the alternatives available.

fps
  • 33,623
  • 8
  • 55
  • 110
  • I read that already before and it does not answer as to how we get notification immediately after value is removed. It only talks about running maintenance in scheduled manner. Appreciate if you help with some concrete answer. – user2203937 Sep 19 '15 at 03:00
  • as the value is wrapped in weakreference, it gets removed by GC. It should send notification immediately in predictable manner but it is not sending due to cache maintenance of expunging stale entry sometime. Hence, I can not get hold of native reference that is part of value and then program exits and native pointer remains unclosed. I do have hack for it but I want to do it in clean way. – user2203937 Sep 19 '15 at 07:35
  • @user2203937 I'm curious... Why are you using weak values in the cache? What's your specific use case? I'm asking because it could be useful to know more details. – fps Sep 19 '15 at 22:20
  • @user2203937 Have you tried calling `cleanUp()` on the cache? – fps Sep 19 '15 at 22:26
  • I have allocated file handle in C++ and calling that using JNA. I want to cleanup native resource when JVM claims the instance and hence I used instance as value (weakvalue) in cache. – user2203937 Sep 20 '15 at 08:02
0

I don't think the listener will be called if JVM GC claimed the weakRef. that listener should only work when eviction policy triggers the eviction. e.g. expireAfterWriter() or expireAfterAccess()

linehrr
  • 1,668
  • 19
  • 24