In the initial learning design mode, I am excited about the excellent design ideas, in the future project, many times the integration of design patterns, and in the current design, we have been aware of the original design mode of foresight, but there are some shortcomings, we need to improve, it has been said that the world is not the absolute thing, of course, Again simple things, the environment has changed, will also change, today and everyone to share in the multi-threaded single-mode optimization.
1, traditional
First, we look back at how the traditional singleton (lazy type) works:
public class singletonclass{ private static Singletonclass instance=null; public static Singletonclass getinstance () { if (instance==null) { instance=new singletonclass (); } return instance; } Private Singletonclass () { }}
It is not difficult to see, in the multi-threaded execution, the ordinary code will be annoyed, we look at the multi-threaded code runtime Picture:
2, double lock
We see that both thread 1 and thread 2 execute code ②, and we get not a singleton object, but multiple objects. We have synchronized optimizations for these.
public static class singleton{ private static Singleton instance=null; Private Singleton () { //do something } public static Singleton getinstance () { if (instance==null) { synchronized (singleton.class) { if (null==instance) { instance=new Singleton ();}} } return instance;} }
We are looking at the multi-threaded operation diagram of this code:
You see,③ only executed once, not only it was protected by the synchronization mechanism, but also a double judgment, so as to ensure the normal operation of the single-threaded mode.
3, enumeration
After jdk1.5, Java takes note of this detail, and when creating a singleton application, we can use the enumeration type to do our work, and he is thread-safe.
Source:
public enum singletonenum{INSTANCE; private String name; Publicstring GetName () {returnname; } publicvoid setName (String name) {this.name = name; } }
This optimization, which allows us to apply the code more gracefully, but also brings a certain problem, is that we have a vague concept of the type of object, so in the work, it is recommended to retain the double lock mode, some tool classes can take enumeration type optimization, simplifying our code and logic.
Summary:
Details of the optimization, like the carving of a piece of art, we contact the more people, the more the idea of the more intense, so we often judge a person how the character and quality, through his contact with the people, friends can be speculated out, and the computer, is so, we contact the excellent framework of many, Nature is a good designer!
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Java Engineering Optimization--a singleton mode under multi-threading