Interview Topic Collection && Implementation Singleton (singleton) mode version-java

Source: Internet
Author: User

Title: Designing a class, we can only produce an instance of the class. (from "Point of the Sword")
parsing: A class that can produce only 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 common 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 very common facet question.
below we give a few solutions for your reference.
* Bad Solution one: only applies to single-threaded environments.
since the requirement can only produce one instance, we must set the constructor to private to prevent others from creating the instance. We can define a static instance and create the instance 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;
}
}
In the static property instance of Singleton1, the preceding code creates an instance only when instance is null to avoid duplicate creation. At the same time, we define the constructor as a private function, which makes sure that only one instance is created.


* Bad solution two: Although in multi-threaded environment can work but not high efficiency
The code in solution one works fine on a single thread, but in the case of multithreading there is a problem. Imagine that if two threads were running simultaneously to an if statement that judged whether instance is null, and instance did not, 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 one instance of the type in a multithreaded environment, we need to add a synchronous lock. Change the Singleton1 slightly to get the following code:
Public class Singleton2 {
private static Singleton2 instance = null;
Private Singleton2 () {}


Public static synchronized Singleton2 getinstance () {
if (instance = = null) {
instance = new Singleton2 ();
      }
return instance;
   }
}
we're still fake. There are two threads that want to create an instance at the same time. Since only one thread can get a synchronous lock at a time, the second thread waits only when the first thread is added to a lock. 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 run the next code. At this point, because the instance has already been created by the first thread, the second thread will not create the instance repeatedly, thus guaranteeing that we can only get one instance in a multithreaded environment.
But the type Singleton2 is not perfect yet. Every time we get an instance of Singleton2 through attribute instance, we try to add a sync lock, and locking is a very time-consuming operation that we should try to avoid when it is not necessary.
* * Feasible solution one: two times before and after the synchronization lock to determine whether the instance already exists
we just 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. So we improved as follows:
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 is not possible to write 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, if the instance instance variable is modified with a volatile modifier, the volatile modifier will ensure that instance = new Singleton (), the corresponding instruction is not reordered, and the following 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 the two if judgments are used to improve efficiency. This code is more complex, error-prone, and we have a better solution.


* * Strongly recommended solution Two: the use of internal classes
This method belongs to the lazy Singleton, because the Java mechanism stipulates that the inner class Singletonholder will be loaded only when the getinstance () method is first called (Implementing Lazy), and its loading process is linear and 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;
   }
}



Interview Topic Collection && Implementation Singleton (singleton) mode version-java

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.