I have a threading, singleton, android question.
So let’s say we have the following singleton code.
public class Singleton {
private Singleton instance;
private int number1 = 0;
private Singleton() {
//lots of initialization code
}
public static synchronized Singleton getInstance() {
if(instance == null) {
instance = new Singleton();
}
return instance;
}
}
My question. Would access to number1 be threadsafe or would I need to create an accessor with a locking mechanism?
Thanks for the help.
Your code won’t compile, because
instanceis not static. The declaration should read:Other than that, you’ve set up a good mechanism to ensure that your application only has one instance of
Singleton.Doing this however, does not safeguard your member variable
number1in any way. If you access that member variable from multiple threads, you’ll still need to synchronize things properly.