Design Mode (5)-single-piece Mode

Source: Internet
Author: User

Synchronizing a method may reduce the execution efficiency by 100 times.

The control of static Initialization is in Java.

One class and one responsibility principle. (classes should do one thing and only do one thing) but one piece does two things. One is to manage their own instances (and provide global access variables) second, assume a role in the application,

(1). Private constructor. do not provide external access (2). Static methods provide external instances of the class itself. (3). Only one instance exists.

Singleton mode: (managing shared resources such as database connections or thread pools) mvc dao Service layer

Delayed instantiation (lazy) thread security problems -- lazy Instance

Eager to instantiate engerly (hunger style)

1. OO principles:

(1) Encapsulation changes (2) multi-purpose combination, less inheritance (3) Interface Programming, not implementation programming (4) effort to design loose coupling between interaction objects (5) classes should be open to extensions, and dependency abstraction should be disabled for modifications (6). Do not rely on specific classes.

2. OO mode: Singleton mode: ensures that a class has only one instance and provides global access points.

> Delayed instantiation: thread security issues

Public class Singleton {

Private static Singleton uniqueInstance;

Private Singleton (){}

Public staticSynchronizedSingleton getInstance () {// solve the thread problem but reduce the efficiency. Removing synchronized will cause thread security problems.

If (uniqueInstance = null ){

UniqueInstance = new Singleton ();

}

Return uniqueInstance;

}

}

---------------

Use "double check lock" to reduce the use of synchronization in getInstance ()

Double-checked locking is used to check whether the instance has been created. If not, "" is synchronized,Only synchronization is performed for the first time..

Public class Singleton {

PrivateVolatileStaitc Singleton uniqueInstance;

Private Singleton (){}

Public static Singleton getInstance (){

If (uniqueInstance = null ){

Synchronized (Singleton. class) {// because it is a static method

If (uniqueInstance = null ){

UniqueInstance = new Singleton ();

}

}

}

Return uniqueInstance;

}

}

(1) The volatitle keyword ensures that when the uniqueInstance variable is initialized to a Singleton instance, multiple threads correctly process the uniqueInstance variable.

(2) If the performance is your focus, you can greatly reduce the time consumption of getInstance.

(3) The double check lock does not apply to Java 1.4 or earlier versions. Many JVM implementations of the volatile keyword in earlier versions will cause the double check lock to fail.

>. Eager instantiation

(1). the JVM ensures that this Instance must be created before any thread accesses the static variables of the Instance.

Public class Singleton {

Private static Singleton uniqueInstance = new Singleton (); // you can use final to modify

Private Singleton (){}

Public static Singleton getInstance (){

Return uniqueInstance;

}

}

(1) When you need to control the number of entities, use the singleton mode.

(2) create a class, define all methods and variables as static, and directly treat the class as a single piece .? (A single piece of the class and a single piece of the object)

If your class is self-contained and does not rely on complex initialization, you can do so. However, becauseThe control of static Initialization is in Java.This may cause confusion, especially when many classes are involved,

This is often doneIt may cause some subtle bugs that are not easy to find related to the initialization order.Unless you absolutely need to useClass. Otherwise, we recommend that you useObject Singleton. Comparison Insurance

(3 ).Classloader)The two class loaders may have the opportunity to create their own single-piece mode .?

Yes. each class loader defines a namespace. If there are more than two class loaders and different class loaders, the same class may be loaded. From the perspective of the entire program, the same class will be loaded multiple times. if this happens on a single piece, it will produce a strange phenomenon where multiple pieces coexist. therefore, your program has multiple class loaders and uses the single-piece mode at the same time. Please be careful, there is a solution, you can specify the class loader and specify the same class loader.

(4). Global variables VS single-piece Mode

In Java, global variables are basically static references to objects. in this case, global variables have a disadvantage. We have mentioned one of them: eager instantiation VS delayed instantiation. but remember the purpose of this mode: ensure that the class has only one instance and provides global access. global variables can provide global access, but they cannot ensure that there is only one instance. global variables also encourage developers in disguise to use many global variables to point to many small objects to choose namespace pollution. A single piece does not encourage such a phenomenon, but it may still be abused.

Highlight-disadvantage of global variables: If you assign an object to a global variable, you mustObject created at the beginning ①In case this object is very resource-consuming, and the program has never used it in this execution.

Using the single-piece mode, we can create objects only when necessary.

①: This is actually related to implementation. Some JVM implementations are: objects are created only when they are used.

(5) It is exaggerated that the spam collector will eat a single piece!

Before Java 1.2, the spam collector has a BUG, which may cause a single piece to be removed as garbage when there is no global reference. that is to say, if a single piece is referenced by only the class of this single piece, the single piece will be cleared as garbage. this causes a confusing BUG: After a single piece is cleared, the next call to getInstance () will produce a "brand new" single piece. for many programs, this can cause confusing behavior, because the instance variable values of the object are gone and everything goes back to the original settings (for example, the network connection is reset ).

After Java 1.2, this bug has been fixed, and a global reference is no longer needed to protect a single piece.

Key points:

(1). Single-piece mode ensures that a class in the program has only one instance at most.

(2). The single-piece mode also provides global points for accessing this instance.

(3). Implementing the single-piece mode in Java requires a private constructor, a static method, and a static variable.

(4 ). determine the performance and resource restrictions, and then carefully select the appropriate solution to implement a single piece. to solve the problem of multithreading (we must ensure that all programs are multithreading ).

(5). If the fifth version of Java 2 is not used, the dual-check locking implementation will fail.

(6) If multiple class loaders are used, multiple instances may be generated due to the failure of a single piece.

(7). If JVM 1.2 or a previous version is used, you must create a single-piece registry to prevent the spam collector from recycling a single piece.

(0) volatitle keywords:

Each time a member variable modified by Volatile is accessed by a thread, the value of the member variable is forcibly re-read from the shared memory. In addition, when the member variables change, the thread is forced to write the change value back to the shared memory. In this way, two different threads always see the same value of a member variable at any time.

In the Java language specification, it is pointed out that in order to get the best speed, the thread is allowed to save the private copy of shared member variables, and the original value of shared member variables is compared only when the thread enters or leaves the synchronized code block.

In this way, when multiple threads interact with an object at the same time, you must notice that the thread needs to get the shared member variable changes in a timely manner.

The volatile keyword prompts VM: For this member variable, it cannot store its private copy, but should directly interact with the shared member variable.

Suggestion: use volatile on the member variables accessed by two or more threads. You do not need to use this variable when it is already in the synchronized code block or a constant.

Because volatile is used to block the necessary code optimization in the VM, the efficiency is relatively low. Therefore, this keyword must be used when necessary.

Just like in C, compiler optimization is prohibited ~~~~

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.