

We are calling a System.gc() to force the JVM to trigger a GC process.

The default behavior of a WeakHashMap is to reclaim an entry that has no reference to it on next GC, so this entry will be deleted from memory by the next GC process. Next, we set the imageName reference to be null, therefore there are no more references pointing to the bigImage object. The imageName will be stored in a map as a WeakReference type. We are putting a BigImage object as a value and an imageName object reference as a key. We're creating a WeakHashMap instance that will store our BigImage objects. UniqueImageName imageName = new UniqueImageName("name_of_big_image") Īwait().atMost(10, TimeUnit.SECONDS).until(map::isEmpty) Let's test our WeakHashMap and see how it behaves: WeakHashMap map = new WeakHashMap() īigImage bigImage = new BigImage("image_id") When a key of a big image object is not in use in our application in any place, that entry will be deleted from memory.įortunately, the WeakHashMap has exactly these characteristics. Ideally, we want a Map implementation that allows GC to automatically delete unused objects. What's more, they'll never be reclaimed from the cache by a GC process, even when they are not in use in our application anymore. Using a simple HashMap will not be a good choice because the value objects may occupy a lot of memory. We want to pick a proper map implementation for solving that problem. We should extend this support to weak self captures, and permit implicit self as long as self has been unwrapped.Let's say that we want to build a cache that keeps big image objects as values, and image names as keys. IntroductionĪs of SE-0269, implicit self is permitted in closures when self is written explicitly in the capture list. This is implemented in apple/swift#40702, and the full proposal document is here. As a follow up from this discussion earlier this year, here's a pitch for allowing implicit self for weak self captures.
