Highlight face question && implement Singleton (singleton) mode-java version

Source: Internet
Author: User

Title: Design a class. We can only produce an instance of this class. (from "Point of the Sword")
Parsing: A class that can only produce one instance is the type that implements the singleton (singleton) pattern. Because design patterns play an important role in object-oriented programming, many companies like to ask questions about design patterns during the interview process.

In a frequently used pattern, Singleton is the only pattern that can be fully implemented with just dozens of lines of code.

Therefore, writing a singleton type is a non-common face question.


Here we give a few solutions. For everyone to participate in the test.


* Bad Solution One: only applies to single-threaded environments.


because the requirement can only produce an instance. So we have to set the constructor as a private function to prevent others from creating instances. We can define a static instance and create it when needed. Based on this idea of implementation:
Public class singleton1{
Private Singleton1 () {
}
private final static Singleton1 instance = null;
Public static Singleton1 getinstance () {
if (instance = = null)
instance = new Singleton1 ();
return instance;
}
}
The above code, in the static property instance of Singleton1, only creates an instance when instance is null to avoid repeated creation. At the same time. We define the constructor as a private function so that we can ensure that only one instance is created.




* Bad Solution II: Although working in a multithreaded environment is inefficient
The code in solution one works fine on a single thread. But in the case of multithreading, there is a problem. Assume that two threads execute at the same time to an if statement that infers whether instance is null. and instance did not create it, then two threads would create an instance, and the type Singleton1 would no longer meet the requirements of the singleton pattern.

To ensure that we can only get an instance of the type in a multithreaded environment, we need to add a synchronous lock. Change the Singleton1 slightly to get the following code, for example:
Public class Singleton2 {
private static Singleton2 instance = null;
Private Singleton2 () {}


Public static synchronized Singleton2 getinstance () {
if (instance = = null) {
instance = new Singleton2 ();
      }
return instance;
   }
}
we still have two threads that want to create an instance at the same time. Because only one thread can get a sync lock at a time. When the first thread adds a lock, the second thread can only wait. When the first thread discovers that the instance has not been created, it creates an instance. The first thread then releases the sync Lock, at which point the second thread can add a synchronous lock and execute the next code. This time because the instance has already been created by the first thread, the second thread will not create instances again and again, so that we can only get one instance in a multithreaded environment.
But the type Singleton2 is not very perfect yet. Every time we get an instance of Singleton2 through attribute instance, we try to add a synchronous lock, and locking is a very time-consuming operation. We should try to avoid it when it is not necessary.
* * Feasible solution one: two times before and after the synchronization lock is inferred if the instance already exists
we only need to lock the instance before it is created to ensure that only one thread creates the instance. Once the instance has been created, we don't need to lock the operation anymore. Therefore we improve for example the following:
Public class Singleton3 {
private static Singleton3 instance = null;
Private Singleton3 () {}
Public static Singleton3 getinstance () {
if (instance = = null) {
synchronzied (singleton3.class) {
Singleton3 temp = instance;
if (temp = = null) {
temp = new Singleton3 ();
Instance = Temp
            }
         }
      }
return instance;
   }
}
because of the order reordering problem, it cannot be written directly as follows:
Public class Singleton3 {
private static Singleton3 instance = null;
Private Singleton3 () {}
Public static Singleton3 getinstance () {
if (instance = = null) {
synchronzied (singleton3.class) {
if (instance = = null) {
instance = new Singleton3 ();
            }
         }
      }
return instance;
   }
}
However, assuming that the instance instance variable is modified with a volatile modifier, the volatile modifier will ensure that instance = new Singleton (), and that the corresponding instruction is not reordered, such as the following singleton code is thread-safe:
Public class Singleton3 {
private static volatile Singleton3 instance = null;
Private Singleton3 () {}
Public static Singleton3 getinstance () {
if (instance = = null) {
synchronzied (singleton3.class) {
if (instance = = null) {
instance = new Singleton3 ();
            }
         }
      }
return instance;
   }
}
Singleton3 uses a locking mechanism to ensure that only one instance is created in a multithreaded environment, and that two if inferences are used to improve efficiency.

This code is relatively complex, easy error, and we have a better solution.


* * Strongly recommended solution Two: the use of internal classes
such a method belongs to the lazy Singleton, because the Java mechanism stipulates that the internal class Singletonholder only in the getinstance () method when the first call will be loaded (implemented lazy). and its load-in process is linear safe. An instance is instantiated once when the inner class is loaded.
Public class Singleton {


Private Singleton () {}
private Static class Singletonholder {
private final static Singleton INSTANCE = new Singleton ();
   } 
Public static Singleton getinstance () {
return singletonholder.instance;
   }
}



Copyright notice: This article blog original articles, blogs, without consent, may not be reproduced.

Highlight face question && implement Singleton (singleton) mode-java version

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.