google / guava

Google core libraries for Java

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Support for weak values in `Multimap`

mlichtblau opened this issue · comments

API(s)

com.google.common.collect.Multimap;
com.google.common.collect.MultimapBuilder;

How do you want it to be improved?

Support .weakValues() similar to com.google.common.collect.MapMaker, allowing for individual values to be garbage collected. When all values are garbage collected accessing the value should return an empty collection.

Why do we need it to be improved?

Currently there is no .weakValues() option on the MultimapBuilder, but it would be just as useful there as in normal map.

Example

val multimapBuilder = MultimapBuilder.hashKeys().weakValues().hashSetValues();

Current Behavior

Currently there is no way to build a Multimap with weak values.

Desired Behavior

Allow the same behavior like in MapMaker.weakValues() in MultimapBuilder

Concrete Use Cases

I want to create a type of notification component where subscribers can wait for the termination of a task with a given task id.
Oftentimes multiple subscribers are interested in subscribing to the same task.
Checking the status of the task in an external system is expensive so each thread polling the status would be too expensive.
My notification component would implement this interface:

CompletableFuture<Task> getFinishedTask(TaskId id);

In my design of the notification component it would be good to have a Multimap<TaskId, CompletableFuture> that keeps track of which task ids should be checked and which completable futures belong to those tasks.
However, as the CompletableFuture does not notify the upstream supplier whether the task is cancelled so it is not possible to cleanup tasks that have not yet completed, but are not referenced anymore.
Being able to use weak values in a Multimap would allow the futures to garbage collected and prevent the notification component from continuing checking the task once all futures have been garbage collected anyways.

Checklist