Grinding design mode-3

Source: Internet
Author: User
ArticleDirectory
    • 3.3 thoughts on delayed Loading
    • 3.4 thoughts on caching
    • 3.5 Basic Implementation of cache in Java
    • 3.6 use cache to implement Singleton Mode
    • 3.7 Advantages and Disadvantages of Singleton Mode
3.3 thoughts on delayed Loading

The lazy implementation of the Singleton mode reflects the idea of delayed loading. What is delayed loading?
In layman's terms, it is not to load resources or data at the beginning. Wait until the resource or data is ready to be used. It is not loaded until it is hidden. It is also called lazy load, it's not lazy, it's "delayed loading", which is a very common idea in actual development, saving resources as much as possible.
What is it like? See the followingCode:


 

3.4 thoughts on caching

The lazy implementation of the Singleton mode also reflects the idea of caching. caching is also a very common feature in actual development.
In short, if some resources or data are frequently used, and these resources or data are stored outside the system, such as databases and hard disk files, therefore, each time you operate on the data, the data is obtained from the database or hard disk, which is slow and may cause performance problems.
A simple solution is to cache the data into the memory. During each operation, you can first find the data in the memory to check whether the data exists. If yes, you can directly use the data, if not, retrieve it and set it to the cache. The next access can be obtained directly from the memory. This saves a lot of time. Of course, cache is a typical space-for-time solution.
How is cache reflected in the implementation of Singleton mode?

3.5 Basic Implementation of cache in Java

Let's look at the basic implementation of cache in Java development. The most common way to implement cache in Java is to use map. The basic steps are as follows:

    • First go to the cache to find the data to be used.
    • If no data is found, create a data that meets the requirements and set the data back to the cache for future use.
    • If you find the corresponding data or create the corresponding data, you can directly use this data.

Let's take a look at the example. The sample code is as follows:

/*** Example of the basic implementation of cache in Java */public class javacache {/*** indicates the container for caching data, which is defined as map for convenient access, you can directly obtain the value based on the key. * The string key is used for simple demonstration */private Map <string, Object> map = new hashmap <string, Object> (); /*** obtain the value from the cache * @ Param key value * @ return key value */public object getvalue (string key) {// obtain object OBJ = map from the cache first. get (key); // determine whether there is a value in the cache if (OBJ = NULL) {// if not, obtain the corresponding data, for example, reading a database or file // This is only a demonstration, so you can directly write a false value OBJ = Key + ", value"; // set the obtained value back to the cache map. put (Key, OBJ);} // if there is a value, return using return OBJ ;}}

Here is only the basic implementation of the cache, and many other functions are not considered, such as clearing the cache and synchronizing the cache. Of course, there are still many implementation methods for Java caching, which are also very complicated. Now there are many professional cache frameworks and more cache knowledge, so I will not discuss them here.

 

3.6 use cache to implement Singleton Mode

In fact, the application of Java cache knowledge can also implement the singleton mode in disguise, which is a simulated implementation. Each time, the value is first taken from the cache. After an object instance is created, the cached value is set, so you do not need to create it again next time.
Although it is not a standard practice, the singleton mode function can also be implemented. For simplicity, the multi-thread problem is not considered. The sample code is as follows:

/*** Use the cache to simulate the implementation of Singleton in a single instance */public class Singleton {/*** to define a default key value, used to identify the storage of */private final static string default_key = "one";/*** cache instance container */Private Static Map <string, singleton> map = new hashmap <string, Singleton> ();/*** private constructor */private Singleton () {//} public static Singleton getinstance () {// obtain Singleton instance = (Singleton) map from the cache first. get (default_key); // if not, create a new one, and then set back to the cache if (instance = NULL) {instance = new Singleton (); map. put (default_key, instance);} // use return instance directly if any ;}}

Can it also implement the features required by a single instance? In fact, there are many ways to implement the mode, not just by referring to the implementation method of the mode. The above method can also implement the functions required by the Singleton, but it is quite troublesome to implement, not good, but it will be useful when the singleton mode is expanded later.
In addition, the mode is the accumulation of experience, and the reference implementation of the mode is not necessarily the best. For the singleton mode, we will give you some better implementation methods later.

3.7 Advantages and Disadvantages of Singleton Mode

 

1: Time and Space
Compare the preceding two methods:Lazy is a typical space changeThat is to say, each time you get an instance, you will judge whether to create the instance or not, and the time for judging the fee. Of course, if no one has been using the instance, it will not create the instance, saving the memory space.
The hungry Chinese style is a typical space change timeWhen the class is loaded, a class instance will be created. No matter you don't need to use it, it will be created first, and then you don't need to judge it every time you call it, saving the running time.

2: thread security
(1) In terms of thread security,The lazy mode without synchronization is thread unsafe.For example, there are two threads, thread a and thread B, and they call the getinstance method at the same time, which may cause concurrency problems. Example:

 ProgramTo continue running, both threads take one step forward, as shown below:


 

Some may think that the text description is not intuitive enough. Let's draw another illustration, as shown in Figure 4:


Figure 4 lazy Singleton thread Problems

According to the decomposition description in figure 4, we can see that when a and B are concurrent, two instances will be created, that is, the control of a single instance is invalid in the case of concurrency.

(2) The hungry Chinese style is thread-safeBecause the VM ensures that only one load will occur, and no concurrency will occur during class loading.

(3) how to implement lazy thread security?
Of course, the lazy style can also implement thread security, as long as synchronized is added, as shown below:

 
Public static synchronized Singleton getinstance (){}

However, this will reduce the overall access speed, and it is indeed a little slower to judge every time. Is there a better way to implement it?

(4) double check lock
you can use the "double check lock" method to implement thread security, in addition, the performance will not be greatly affected. So what is the "double check lock" mechanism?
the so-called double check locking mechanism means that the getinstance method does not need to be synchronized every time it enters the getinstance method, but is not synchronized first. After Entering the method, check whether the instance exists first, if it does not exist, enter the following synchronization block. This is the first check. After entering the synchronization block, check again whether the instance exists. If it does not exist, create an instance under synchronization. This is the second check. In this way, you only need to synchronize once, thus reducing the time wasted in making judgments multiple times during synchronization.
The Implementation of the double check locking mechanism uses a keyword volatile, which means that the value of the variable modified by volatile will not be cached by the local thread, all the reads and writes to the variable directly operate on the shared memory, so that multiple threads can correctly process the variable.
note , therefore, the double check locking mechanism can only be used in Java 5 or later versions.
the code may be clearer. The sample code is as follows:

Public class Singleton {/*** Add the volatile modifier to the variable for saving the instance */private volatile static Singleton instance = NULL; private Singleton () {} public static Singleton getinstance () {// check whether the instance exists. If it does not exist, enter the following synchronization block if (instance = NULL) {// synchronization block. Thread-safe creation of the Instance synchronized (Singleton. class) {// check whether the instance exists again. If it does not exist, create an instance. If (instance = NULL) {instance = new Singleton () ;}} return instance ;}}
 
 

This implementation method not only enables thread-safe instance creation, but also does not have a great impact on performance. It is only synchronized when the instance is created for the first time and will not need to be synchronized in the future, to speed up the operation.
Tip:Because the volatile keyword may block some necessary code optimization in the virtual machine, the running efficiency is not very high. Therefore, it is generally recommended that you do not need it unless necessary. That is to say, although the dual lock mechanism can be used to implement thread security Singleton, it is not recommended to use it in large quantities. Choose it as needed.

 

To be continued

 

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.