2

The documentation for using Guava HashMultimap stresses the importance of wrapping your multimap through Multimaps.synchronizedMultimap upon initialization for a thread-safe access. Given that, I know I can create the following multimap:

private Multimap<Short, String> successfulMultimap = 
Multimaps.synchronizedMultimap(HashMultimap.<Short, String>create());

However, my multimap needs to be injected using Spring because it will be used by another class on my service.

Without the synchronized wrapper, I know I can use something along these lines:

//setter
public void setSuccessfulMultimap(Multimap<Short, String> successfulMultimap) {
    this.successfulMultimap = successfulMultimap;
}

<!-- XML configuration -->
<bean id="myBean" factory-method="create" class="com.google.common.collect.HashMultimap"/>

But seeing as I need to initialize it as thread-safe, I'm lost on how to "spring"-ify it. Can someone help me on how to inject a synchronized multimap or any good approach to it?

Anders
  • 8,307
  • 9
  • 56
  • 88
BubeyReb
  • 63
  • 1
  • 4

1 Answers1

0

You should be able to put the appropriate code in the spring set method:

//setter
public void setSuccessfulMultimap(Multimap<Short, String> value) {
    successfulMultimap = Multimap.synchronizedMultimap(value);
}

Since it is set after object construction, you may also want to make the successfulMultimap member volatile to ensure the initialization is visible to other threads.

Warren Dew
  • 8,790
  • 3
  • 30
  • 44
  • 1
    Thank you, @Warren! Just what I was looking for. :) Although I used the setter type to the implementation of `HashMultimap` instead of the multimap interface. Also, since you've mentioned 'volatile'--do I still have to access my multimap using the `synchronized` block of java or will the `volatile` suffice? – BubeyReb Oct 28 '15 at 02:24
  • You need either to synchronize the access to the multimap or to wrap it in Multimap.synchronizedMultimap() as in my example so that access to the multimap after its construction is thread safe. Either one suffices. The volatile keyword only ensures that the multimap, once initialized, is visible to other threads, rather than still being in a cache while other threads read a null value. – Warren Dew Oct 28 '15 at 02:55
  • Thanks again, @WarrenDew! :) – BubeyReb Oct 28 '15 at 08:15