Ved
Ved

Reputation: 3500

Singletons in Multiple Classloader and VM cases

How to safely code Singletons in case of two or more Classloaders and VMs. I see this problem explained at: http://java.sun.com/developer/technicalArticles/Programming/singletons/

Solutions ?

Upvotes: 3

Views: 4908

Answers (4)

Akos
Akos

Reputation: 11

Attention: if the computer has multiple interfaces (IPs) then the same socket (8765) can be bound to all of them (so it is not that foolproof). File is better although there are cases when they can be hidden too (mount over, for example)

Upvotes: 1

gnat
gnat

Reputation: 6215

1) network socket survives multiple VMs

    Port busy 8765 java.net.BindException: Address already in use

2) so does file

    WARNING: Creating a new instance of CacheManager using the diskStorePath

safely code Singletons in case of two or more Classloaders and VMs based on these resources (if you really badly need to stick with this anti-pattern)

Upvotes: 0

Sanjay T. Sharma
Sanjay T. Sharma

Reputation: 23208

The article clearly states that distributed applications should stay away from Singletons. Any particular problem you are trying to solve here? Also, for singletons which hold true constants which are never modified during the application run, multiple "instances" of your "singleton" shouldn't pose a problem. In other cases, you are better off injecting your configuration (the dependency injection way of doing things) in the classes which need it.

Upvotes: 2

Peter Lawrey
Peter Lawrey

Reputation: 533530

If you want share a singleton between ClassLoaders, you have a common parent load the singleton, or you can have each ClassLoader explicitly define which classes Singleton you want that Classloader to use.

Upvotes: 3

Related Questions