[design mode] Single-piece mode concept and three solutions to solve multithreading problems

Source: Internet
Author: User
Tags volatile

Mainly from the Head fisrt design mode to learn knowledge;

1. Define a single-piece mode

A single-piece mode ensures that a class has only one instance and provides a global access point;

In the entire system context, there is only one object that can be used for many objects that require only one or a larger cost in the system, such as thread pooling, caching, dialog boxes, processing preferences and registry objects, log objects, objects that act as drivers for devices such as printers, video cards, and so on;

The use of single-piece mode can avoid the system maintenance too much no record state data, all instances of the function can be substituted for related objects, there are many instances of processing may result in inconsistent results;

2. Main ideas

2.1 holds a static class object by the class and exposes the access interface to the class object by means of the method;

Class 2.2 prohibits instantiation of external objects

3. Implementation of single-piece mode

3.1 The following is a simple implementation of a single-piece mode, the idea is to hold a static object, when necessary, through the common method of the class to get the object's reference, there is another way is to delay the instantiation, when the object needs to be used to instantiate the object, if the object is not referenced, then is not instantiated , system resources are not wasted.

 Public classSingleton {Private StaticSingleton uniqueinstance; PrivateSingleton () {} Public StaticSingleton getinstance () {if(Uniqueinstance = =NULL) {uniqueinstance=NewSingleton (); }    }    returnuniqueinstance; }   Public Static voidMain (string[] args) {Singleton Singleton=singleton.getinstance ();    System.out.println (Singleton.tostring ()); [Email protected] Singleton=singleton.getinstance ();    System.out.println (Singleton.tostring ()); [Email protected] Singleton=singleton.getinstance ();    System.out.println (Singleton.tostring ()); [Email protected] Singleton=singleton.getinstance ();    System.out.println (Singleton.tostring ()); [Email protected]}}

Here, the memory addresses of several classes of objects are the same, referencing the same object.

4. Single-piece mode and multithreading

The above single-piece mode implementation has been able to meet basic usage requirements, but when the single-mode mode encounters multiple threads, many strange problems occur (in fact, many of the code is problematic after encountering multiple threads).

For example, in the example above, the problem occurs when the code is in a state like the following:

This time the object is not the same, multithreading causes the single-piece mode is not the same as our definition.

In order to solve this problem, there are three workarounds:

* Using the Synchronized method, the getinstance () into a synchronous method, this can solve our problem, but the instantiation is only used at the first time, there is no such problem exists, Then forcing synchronization through synchronized can degrade the concurrency of the system, which is suitable for getinstance () performance without affecting or affecting acceptable places;

  

 Public Static synchronized Singleton getinstance () {...

* Use the "eager" instantiation method, which is like object generation when the class is initialized;

 Public class Singleton {  privatestaticnew  Singleton ();   Private Singleton () {}    Public Static Singleton getinstance () {     return  uniqueinstance;    }}

* use "double check Plus lock" (since JDK 1.4)

After use, the code is like this:

  

 Public classSingleton {Private volatile StaticSingleton uniqueinstance; PrivateSingleton () {} Public StaticSingleton getinstance () {if(Uniqueinstance = =NULL) {      synchronized(Singleton.class) {        if(Uniqueinstance = =NULL) {uniqueinstance=NewSingleton (); }      }    }    returnuniqueinstance; }   Public Static voidMain (string[] args) {System.out.println ("Test"); Singleton Singleton=singleton.getinstance ();    System.out.println (Singleton.tostring ()); Singleton=singleton.getinstance ();    System.out.println (Singleton.tostring ()); Singleton=singleton.getinstance ();    System.out.println (Singleton.tostring ()); Singleton=singleton.getinstance ();  System.out.println (Singleton.tostring ()); }}

The modification of the variable by means of volatile is visible to other threads, and there is no command ordering; For more details, see: Address

Then when the judgment is uninitialized, then the class into the lock and then re-empty after the initialization of the class, which solves the problems we encountered before, but also very good implementation of the concept of single-piece mode.

[design mode] Single-piece mode concept and three solutions to solve multithreading problems

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.