user4180854
user4180854

Reputation:

singleton thread safety in Java

Basically i was going trough a multithreading guide in developers.android.com when i saw something that confused me...(i am reffering to this article

http://developer.android.com/training/multiple-threads/create-threadpool.html

)

In the Define the Thread Pool Class section where they mention that the class should have a private constructor in order to make it singleton, the writer claims that by doing this the code would not require synhronization. I am confused why this is thread safe, as altough it is a singleton it can still be referenced by multiple threads simultaneously causing memory consistency errors etc.

Upvotes: 1

Views: 342

Answers (1)

Maxaon3000
Maxaon3000

Reputation: 1129

What they mean is:

  • Since the constructor is private only a method inside the class itself may create an instance of that class
  • The only instance of that class created is through:

    static  
    {
          // Creates a single static instance of PhotoManager
           sInstance = new PhotoManager();
    }
    
  • The static { ... } block is thread safe because it is executed by the class loader, which is synchronized

Upvotes: 3

Related Questions