Many blog could teach you how to write singleton but somebody may interest to face singelton with thread safe. We can see the below example for create the singleton instance with thread safe.
The below code will also explain What is volatile keyword and its responsibilty.
From the above, We know static will execute at first as per java rules. Here we able to see volatile keyword, which will create that instance in Main memory. The reason behind for adding volatile here is, we need multi threading task should be happened with the help of that instance. A lot of parallel threads will load simultaneously and if they want to access the instance, which should be in Main memory. The below picture will represent clearly.
The below code will also explain What is volatile keyword and its responsibilty.
private static volatile Test instance; public static Test getInstance () { if (instance == null) { synchronized (Test.class) { instance = new Test(); } } return instance; } }
From the above, We know static will execute at first as per java rules. Here we able to see volatile keyword, which will create that instance in Main memory. The reason behind for adding volatile here is, we need multi threading task should be happened with the help of that instance. A lot of parallel threads will load simultaneously and if they want to access the instance, which should be in Main memory. The below picture will represent clearly.
Volatile with Thread Safe Explanation |
Hope you understand volatile purpose here. Suppose if volatile is not used. some thread could access instance as NULL.
No comments:
Post a Comment