Thread Safe Singleton
This program demonstrates thread safe Singleton.
Problem Statement
Write a Java program to implement thread safe Singleton using synchronized method.
Source Code
| 1 | class Singleton { |
| 2 | private static Singleton instance; |
| 3 | private Singleton(){ } |
| 4 | public static synchronized Singleton getInstance(){ |
| 5 | if(instance==null) instance=new Singleton(); |
| 6 | return instance; |
| 7 | } |
| 8 | } |
| 9 | public class SingletonThreadSafe { |
| 10 | public static void main(String[] args) { |
| 11 | System.out.println("Eduinq Singleton Thread Safe"); |
| 12 | Singleton s1=Singleton.getInstance(); |
| 13 | Singleton s2=Singleton.getInstance(); |
| 14 | System.out.println(s1==s2); |
| 15 | } |
| 16 | } |
Program Output
Eduinq Singleton Thread Safe true
Explanation
Synchronization ensures thread safety. - Only one thread can access method at a time. - Prevents multiple instances in multithreaded environment. - This guarantees Singleton integrity across threads. Conclusion: Shows how to implement thread safe Singleton.