[concurrency-interest] ConcurrentHashMap of singletons

Joe Bowbeer joe.bowbeer at gmail.com
Tue Oct 4 06:10:35 EDT 2011


You may want to use putIfAbsent unless you add external synchronization.

This is covered in "Java Concurrency in Practice" in several sections at the
end of chapter 5.

http://jcip.net/listings.html

By the way, a similar question was asked in June about a "Multiton"
implementation in Wikipedia, which could still use a little work:

http://en.wikipedia.org/wiki/Multiton_pattern#Java

In the next version of ConcurrentHashMap, computeIfAbsent functionality is
planned, which may be even better suited for your needs:

http://gee.cs.oswego.edu/cgi-bin/viewcvs.cgi/jsr166/src/jsr166e/ConcurrentHashMapV8.java?view=markup

Joe

On Tue, Oct 4, 2011 at 2:01 AM, Mohan Radhakrishnan wrote:

>  Hi,****
>
> ** **
>
> ** **
>
>     private static final Map<String, Provider> providers =****
>
>         new ConcurrentHashMap<String, Provider>();****
>
> ** **
>
>     public static Service newInstance(String name) {****
>
>         Provider p = providers.get(name);****
>
>         if (p == null)****
>
>             throw new IllegalArgumentException(****
>
>                 "No provider registered with name: " + name);****
>
>         return p.newService();****
>
>     }****
>
> ** **
>
>  I have had a doubt about this type of code in ‘Effective Java’ that uses a
> ‘ConcurrentHashMap’ instead of synchronizing newInstance. This looks like
> another way of implementing a set of singletons if we extend this pattern by
> putting a new object if it is null. Are there any problems here ?****
>
> ** **
>
> Thanks,****
>
> Mohan****
>
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://cs.oswego.edu/pipermail/concurrency-interest/attachments/20111004/72a60122/attachment.html>


More information about the Concurrency-interest mailing list