Single-Case mode

Source: Internet
Author: User

Single-Case mode


1) Implementation of the single case:

Thread Safety (locking):

One drawback of the above code is that when the class is loaded, it is directly new to a static object, and when there are more such classes in the system, the startup speed slows down. Now the popular design is to say "lazy loading", we can initialize the first class object at the first use. So this fits in the small system.

If you are using a common variable that is not protected under multithreading, the result of the variable will be inconsistent with the theoretical value, so that the thread is unsafe, but the common variable works under the protection mechanism without any unknown changes . , then this thread is safe. .

In the case of a singleton, there is an object that is saved as a member variable of the class, not as a local variable, so the other method is actually manipulating the same object when it accesses the object concurrently.

For example, two people call a method at the same time (give me a cake), but this method returns a single object of a cake, two people at the same time to get the same cake, and sit down, raise a knife and fork, the first person to swallow the cake, it caused the second person obviously got the cake, but did not eat the result.

Tomcat can be preheated with a single case.

Traditional singleton can save memory


For thread safety: (using sync Lock)


Single lock and Double lock:


One of the above code locks a method, the granularity is a bit large, the improvement is only locked in the new statement is OK. is called a "double lock" mechanism:


Management of the Singleton implementation: (Registration of single case)

This example uses map to store the ID of the created object to prevent repeated instantiation of the object.

When do I use a single case? Stateless objects can be used as singleton. No data-like service (no ID for those), DAO is available as a singleton, with data such as Userbean not available. (such as a printer). There are also classes that only read-only data (no set method) can be used as a singleton:

There are also the following application scenarios:

1.Windows of the TaskManager (Task Manager) is a very typical singleton mode (this is very familiar with it), think about it, is not it, you can open two Windowstask Manager it? don't believe you try it yourself Oh ~

2.windows of the RecycleBin (Recycle Bin) is also a typical single-case application. During the whole system operation, the Recycle Bin maintains the only one instance.

3. The website counter, generally also uses the Singleton pattern realization, otherwise difficult to synchronize.

4. Application of the log application, the general use of single-case mode implementation, which is generally due to the shared log file is open, because there can only be one instance to operate, otherwise the content is not good to append.

5. The Web application's configuration object reads, generally also applies the singleton pattern, this is because the configuration file is the shared resource.

6. Database connection pooling is generally designed with a singleton pattern, because database connections are a database resource. Database software system in the use of database connection pool, mainly to save the open or close the database connection caused by the efficiency of loss, this loss of efficiency is very expensive, because how to use a single case mode to maintain, can greatly reduce this loss.

7. the multi-threaded thread pool design is generally also a singleton pattern, because thread pooling facilitates the control of threads in the pool.

8. the file system of the operating system is also a specific example of a large single-instance pattern implementation, and an operating system can have only one file system.

9. HttpApplication is also a typical application of unit cases. People familiar with the entire request lifecycle of ASP (IIS) should know that HttpApplication is also a singleton mode, and all HttpModule All Share a HttpApplication instance .

When it comes to the façade class, it is impossible to mention the façade (facade) mode. Client communication with multiple subsystems must be done through a unified façade (facade) object, which is the façade mode. This unified façade (facade) object is the façade class. In façade mode, typically only one façade class is required, and this façade class has only one instance, in other words, it is a singleton class. But that's not absolute.

General rules for writing a single case:

1. Make the class into a singleton the constant pool must be stored with static.

Generally defined within a method:

is thread-safe, and a variable in the stack has a reference to the object in the heap.

and to the management of the single case:

The map is placed in a constant pool in the heap and can be accessed by multiple threads and is unsafe for threads.

Servlets are singleton, with privatestring name in the servlet, or because of the Do/get method that causes thread safety. Third-party class libraries to understand the API can be made into a single case. (There are methods to modify the data can not be used as a singleton)

The singleton mode is also a kind of common design pattern, what does it bring to our advantage? In fact, it is nothing more than a three-part function:

First, control the use of resources, through thread synchronization to control the concurrent access of resources;

Second, control the number of instances generated, to achieve the purpose of saving resources.

Third, as a medium of communication, that is, data sharing, it can not establish a direct association under the conditions of a number of unrelated two threads or processes to achieve communication between.

For example, the design of database connection pool is generally based on singleton mode, database connection is a kind of database resource

Two types of single cases:

1. A Hungry man type

Public class Eagersingleton

{

Private static final Eagersingleton m_instance = newEagersingleton ();

/**

* Private default Construction child

*/

Private Eagersingleton () {}

/**

* Static Factory Method

*/

Public Static Eagersingleton getinstance ()

{

return m_instance;

}

}

2. Lazy type

Public class Lazysingleton

{

Private Static Lazysingleton m_instance = null;

/**

* private default constructor to ensure that the outside world cannot be instantiated directly

*/

Private Lazysingleton () {}

/**

* static Factory method, returning the only instance of this class

*/

Synchronized public static Lazysingleton getinstance ()

{

if (m_instance = = null)

{

M_instance = newLazysingleton ();

}

return m_instance;

}

}

A hungry man-type is thread-safe, creating a static object at the same time as the class is created for the system to use, not change later

Lazy type If you create an instance object without adding synchronized, the access to the object is not thread-safe

It is recommended to use the first

Single-Case mode

Related Article

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.