Is singleton thread safe?

hello all,

please help me by answering these questions?

singleton patterns calls for creation of a single class that can be shared between classes. since one class has been created

Can singletons be used in a multithreaded environment? is singleton thread safe?

Are threading problems a consequence of the pattern or programming language?

thank you very much,

Hiru

[409 byte] By [hiru130883a] at [2007-10-2 4:47:23]
# 1

The singleton pattern isn't inherently thread-safe, but you can write thread-safe singletons.

Any class that has no writable class or instance data members is inherently thread safe. Any method that uses only local variables or parameters is inherently thread-safe. If a class has writable class or data members, the sections of code that modifies them should appear in a synchronized block.

If your singleton meets these criteria, I believe it's thread safe.

%

duffymoa at 2007-7-16 0:52:09 > top of Java-index,Other Topics,Patterns & OO Design...
# 2

Your wording is a little bit misleading. A singleton is an *Object* of a class that only allows the creation of a single object. This is done by hiding constructors (private) from clients and providing an static method to get/build the instance.

So, just synchronize that method and your done, on the "creation" side.

Of course, if methods of that object are being called by different threads you probably have to "synchronize" most critical methods, or all of them as well.

However, be aware that if you use multiple ClassLoaders (i.e. distributed environment, web development, etc) this singleton pattern may not work, as your Class may be loaded by different ClassLoaders and therefore don't share static variables -typically, the "singleton"- (if I'm wrong here, please let me know ;-)

c.ayaa at 2007-7-16 0:52:09 > top of Java-index,Other Topics,Patterns & OO Design...
# 3
hello ,Thank you for your response. could you please provide me with some useful URLs to read about thread safe singletons? with examples would be most helpful!thank you very much for your time .Hiru
hiru130883a at 2007-7-16 0:52:10 > top of Java-index,Other Topics,Patterns & OO Design...
# 4
hi! i found another thread where duffymo has shown examples about thread safe singletons. thanks duffymo and c.aya for your response.Hiru
hiru130883a at 2007-7-16 0:52:10 > top of Java-index,Other Topics,Patterns & OO Design...
# 5

> The singleton pattern isn't inherently thread-safe,

> but you can write thread-safe singletons.

> Any class that has no writable class or instance data

> members is inherently thread safe.

What do you mean by "writable". Perhaps this terminology is well-defined and I'm ignorant, but it sounds like you're saying as long as no class member can be set it's thread-safe. That of course isn't true because if the member is exposed in any way and is mutable it isn't.

> Any method that uses only local variables or parameters

> is inherently thread-safe. If a class has writable class or

> data members, the sections of code that modifies them

> should appear in a synchronized block.

If the parameter is mutable it is not thread-safe. If I pass you an array and your code is synchronized there is nothing to keep me from modifying that array while you use it. Even if you do a defensive copy I could modify it during the copy.

kablaira at 2007-7-16 0:52:10 > top of Java-index,Other Topics,Patterns & OO Design...
# 6

The simplest thread-safe implementation of Singleton is:

final public class Singleton {

private static final Singleton instance = new Singleton();

private Singleton() {

super();

}

public static Singleton getInstance() {

return instance;

}

}

Not sure where duffy's thread is with the examples, so I'm posting here as it perhaps may have been able more advanced Singletons that use lazy instantiation or registries.

kablaira at 2007-7-16 0:52:10 > top of Java-index,Other Topics,Patterns & OO Design...
# 7

> The simplest thread-safe implementation of Singleton

> is:

>

> > final public class Singleton {

> private static final Singleton instance = new

> new Singleton();

>

>private Singleton() {

> super();

>}

>

>public static Singleton getInstance() {

> return instance;

>}

> }

>

>

> Not sure where duffy's thread is with the examples,

> so I'm posting here as it perhaps may have been able

> more advanced Singletons that use lazy instantiation

> or registries.

I'm not sure where my thread is either, but I think this is the right way to do it.

Lazy instantiation didn't work last time I checked, due to the double check locking problem. I'm not sure if the Java memory model has been changed to correct this. I'd argue that in 99% of the cases lazy instantiation is not necessary and doesn't buy anything worthwhile.

There's a strong argument that Singleton is overused and misused, but that's another thread. If you must, I think this example is correct.

But it still doesn't say anything about thread safety, because it doesn't have any data members to protect. The example is thread safe, but it doesn't do anything, either.

%

duffymoa at 2007-7-16 0:52:10 > top of Java-index,Other Topics,Patterns & OO Design...
# 8

It's thread-safe in the context of avoiding common multithreading issues that result in multiple Singletons. This does leave multithreading issues that are common to all classes, but I was under the impression they were asking about specific Singleton thread-safety issues.

I agree with you on the lazy instantiation. Avoiding the instantiation only really helps if it's never instantiated, and I think it's safe to assume that in most cases it wouldn't be there if it wasn't going to get instantiated at some point. I seem to recall a developer works article that provided a method for safely using lazy instantiation, but it reached a level of complexity that was simply absurd. In fact, that was the article's point, as I recall, that to truly do it safely you have to make your code so ridiculously complex and convoluted that you gain nothing.

kablaira at 2007-7-16 0:52:10 > top of Java-index,Other Topics,Patterns & OO Design...
# 9

> > The singleton pattern isn't inherently

> thread-safe,

> > but you can write thread-safe singletons.

> > Any class that has no writable class or instance

> data

> > members is inherently thread safe.

>

> What do you mean by "writable". Perhaps this

> terminology is well-defined and I'm ignorant, but it

> sounds like you're saying as long as no class member

> can be set it's thread-safe. That of course isn't

> true because if the member is exposed in any way and

> is mutable it isn't.

Writable means that the data can be changed, which in this case is the same as mutable.

>

> > Any method that uses only local variables or

> parameters

> > is inherently thread-safe. If a class has writable

> class or

> > data members, the sections of code that modifies

> them

> > should appear in a synchronized block.

>

> If the parameter is mutable it is not thread-safe.

> If I pass you an array and your code is synchronized

> d there is nothing to keep me from modifying that

> array while you use it. Even if you do a defensive

> copy I could modify it during the copy.

Not exactly.

A parameter is passed in the flow of a thread. Thus the caller is making a decision about what to pass to the the method. Just as the caller can not pass a null when it is not expected the caller is also responsible for determing the correct instance to pass to a method.

Additionally a thread safe class is not responsible for making all parameters passed to it thread safe as well. That would not only require significant extra code it is also likely to lead to performance problems. Consider what happens to a parameter that is passed down 10 levels and each level in turn locks it.

There might be situations where that is the correct way to handle a design but the domain of that is the design (sub-system) not the individual class.

jschella at 2007-7-16 0:52:10 > top of Java-index,Other Topics,Patterns & OO Design...
# 10

> Writable means that the data can be changed, which in

> this case is the same as mutable.

Okay, I wasn't sure of the definition in this context. Then I'd have to agree with that.

> >

> > > Any method that uses only local variables or

> > parameters

> > > is inherently thread-safe. If a class has

> writable

> > class or

> > > data members, the sections of code that modifies

> > them

> > > should appear in a synchronized block.

> >

> > If the parameter is mutable it is not thread-safe.

> > If I pass you an array and your code is

> synchronized

> > d there is nothing to keep me from modifying that

> > array while you use it. Even if you do a

> defensive

> > copy I could modify it during the copy.

>

> Not exactly.

>

> A parameter is passed in the flow of a thread. Thus

> the caller is making a decision about what to pass to

> the the method. Just as the caller can not pass a

> null when it is not expected the caller is also

> responsible for determing the correct instance to

> pass to a method.

>

> Additionally a thread safe class is not responsible

> for making all parameters passed to it thread safe as

> well. That would not only require significant extra

> code it is also likely to lead to performance

> problems. Consider what happens to a parameter that

> is passed down 10 levels and each level in turn locks

> it.

>

> There might be situations where that is the correct

> way to handle a design but the domain of that is the

> design (sub-system) not the individual class.

So you're saying that it is thread-safe because the burden is on the caller to ensure it's not passing a value that will be misused, such as concurrent access of an array it's passing? I can see that I guess.

kablaira at 2007-7-16 0:52:10 > top of Java-index,Other Topics,Patterns & OO Design...
# 11

>

> So you're saying that it is thread-safe because the

> burden is on the caller to ensure it's not passing a

> value that will be misused, such as concurrent access

> of an array it's passing? I can see that I guess.

The class is thread safe. The application might be another matter.

jschella at 2007-7-16 0:52:10 > top of Java-index,Other Topics,Patterns & OO Design...
# 12

> The class is thread safe. The application might be

> another matter.

Right, I agree with that. I was thinking of situations where the parameter was used in conjunction with an instance variable. However, he specifically said only local variables and parameters. I wasn't thinking and violated the premise of his statement.

kablaira at 2007-7-16 0:52:10 > top of Java-index,Other Topics,Patterns & OO Design...
# 13

Hi,

Before explaining whether a singleton is thread safe i want to explaing what is thread safe here

When multiple threads execute a single instance of a program and therefore share memory, multiple threads could possibly be attempting to read and write to the same place in memory.If we have a multithreaded program, we will have multiple threads processing the same instance.What happens when Thread-A examines instance variable x? Notice how Thread-B has just incremented instance variable x. The problem here is Thread-A has written to the instance variable x and is not expecting that value to change unless Thread-A explicitly does so. Unfortunately Thread-B is thinking the same thing regarding itself; the only problem is they share the same variable.

First method to make a program threadsafe-: Avoidance

To ensure we have our own unique variable instance for each thread, we simply move the declaration of the variable from within the class to within the method using it. We have now changed our variable from an instance variable to a local variable. The difference is that, for each call to the method, a new variable is created; therefore, each thread has its own variable. Before, when the variable was an instance variable, the variable was shared for all threads processing that class instance. The following thread-safe code has a subtle, yet important, difference.

second defense:Partial synchronization

Thread synchronization is an important technique to know, but not one you want to throw at a solution unless required. Anytime you synchronize blocks of code, you introduce bottlenecks into your system. When you synchronize a code block, you tell the JVM that only one thread may be within this synchronized block of code at a given moment. If we run a multithreaded application and a thread runs into a synchronized code block being executed by another thread, the second thread must wait until the first thread exits that block.

It is important to accurately identify which code block truly needs to be synchronized and to synchronize as little as possible. In our example, we assume that making our instance variable a local variable is not an option.

Third Defence:--Whole synchronization

Here u should implement an interface which make the whole class a thread safe on or synchronized

Thre views are made by Phillip Bridgham, M.S., is a technologist for Comtech Integrated Systems.I'm inspired by this and posting the same here

ashkuma at 2007-7-16 0:52:10 > top of Java-index,Other Topics,Patterns & OO Design...
# 14

> Hi,

>

> Before explaining whether a singleton is thread safe

> e i want to explaing what is thread safe here

>

> When multiple threads execute a single instance of a

> program and therefore share memory, multiple threads

> could possibly be attempting to read and write to the

> same place in memory.If we have a multithreaded

> program, we will have multiple threads processing the

> same instance.What happens when Thread-A examines

> instance variable x? Notice how Thread-B has just

> incremented instance variable x. The problem here is

> Thread-A has written to the instance variable x and

> is not expecting that value to change unless Thread-A

> explicitly does so. Unfortunately Thread-B is

> thinking the same thing regarding itself; the only

> problem is they share the same variable.

>

> First method to make a program threadsafe-: Avoidance

>

>

> To ensure we have our own unique variable instance

> for each thread, we simply move the declaration of

> the variable from within the class to within the

> method using it. We have now changed our variable

> from an instance variable to a local variable. The

> difference is that, for each call to the method, a

> new variable is created; therefore, each thread has

> its own variable. Before, when the variable was an

> instance variable, the variable was shared for all

> threads processing that class instance. The following

> thread-safe code has a subtle, yet important,

> difference.

>

> second defense:Partial synchronization

>

> Thread synchronization is an important technique to

> know, but not one you want to throw at a solution

> unless required. Anytime you synchronize blocks of

> code, you introduce bottlenecks into your system.

> When you synchronize a code block, you tell the JVM

> that only one thread may be within this synchronized

> block of code at a given moment. If we run a

> multithreaded application and a thread runs into a

> synchronized code block being executed by another

> thread, the second thread must wait until the first

> thread exits that block.

>

> It is important to accurately identify which code

> block truly needs to be synchronized and to

> synchronize as little as possible. In our example, we

> assume that making our instance variable a local

> variable is not an option.

>

> Third Defence:--Whole synchronization

>

> Here u should implement an interface which make the

> whole class a thread safe on or synchronized

>

>

> Thre views are made by Phillip Bridgham, M.S., is a

> technologist for Comtech Integrated Systems.I'm

> inspired by this and posting the same here

Was there a point in all of that? The posted Singleton is thread-safe. Furthermore, some of that was misleading. A local variable is only duplicated if the method is synchronized, a premise I did not see established.Also, it is misleading to say that only one Thread can be in a synchronized block of code at any time because the same block may be using different monitors at runtime, in which case two threads could be in the same block of code at the same time.

private Object lock;

public void doSomething() {

lock = new Object();

synchronized(lock) {

// Do something.

}

}

It is not guaranteed that only one Thread can enter that synchronized block because every Thread that calls doSomething() will end up synchronizing on another monitor.

This is a trivial example and obviously something no competent developer would do, but it illustrates that the statement assumes premises that I have not seen established. It would be more accurate to say that only one Thread can enter a synchronized block so long as it uses the same monitor.

It's also not noted in the discussion of local variables vs instance variables that what he says only applies to primitives. When it comes to actual Objects, just because the variable holding the reference is unique to each Thread does not make use of it thread-safe if it points to an Object to which references are held elsewhere.

kablaira at 2007-7-16 0:52:10 > top of Java-index,Other Topics,Patterns & OO Design...