[concurrency-interest] ConcurrentHashMap of singletons

Nader Aeinehchi nader at aeinehchi.com
Tue Oct 4 05:59:04 EDT 2011


As long as you have correctly populated the map(providers) with provider 
objects, this pattern:
1. acts as a singleton
2. is thread safe
3. scales good

You should prefer this pattern rather synchronizing newInstance.





On 10/04/2011 11: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
>
> DISCLAIMER:
> ========================================================================================================================================================== 
>
> The information contained in this e-mail message may be privileged 
> and/or confidential and protected from disclosure under applicable 
> law. It is intended only for the individual to whom or entity to which 
> it is addressed as shown at the beginning of the message. If the 
> reader of this message is not the intended recipient, or if the 
> employee or agent responsible for delivering the message is not an 
> employee or agent of the intended recipient, you are hereby notified 
> that any review, dissemination,distribution, use, or copying of this 
> message is strictly prohibited. If you have received this message in 
> error, please notify us immediately by return e-mail and permanently 
> delete this message and your reply to the extent it includes this 
> message. Any views or opinions presented in this message or 
> attachments are those of the author and do not necessarily represent 
> those of the Company. All e-mails and attachments sent and received 
> are subject to monitoring, reading, and archival by the Company.
> ==========================================================================================================================================================
>
>
> _______________________________________________
> Concurrency-interest mailing list
> Concurrency-interest at cs.oswego.edu
> http://cs.oswego.edu/mailman/listinfo/concurrency-interest

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://cs.oswego.edu/pipermail/concurrency-interest/attachments/20111004/ed0cc214/attachment.html>


More information about the Concurrency-interest mailing list