How to write an interviewer's view of Java Singleton

Source: Internet
Author: User
Tags volatile

Singleton mode is a kind of common software design pattern. In its core structure, there is only one special class that is called a singleton. The singleton mode ensures that there is only one instance of a class in the system.

Today we don't talk about the use of singleton patterns, just say if the interviewer lets you hit a piece of code to implement a singleton pattern in the case of an interview, how to write a single example code that gives the interviewer a bright look. Because I am learning Java, the next instance will be written in the Java language.

When it comes to Singleton mode, the first thought is that there is a self-reference in the class that is initialized to null and is decorated with the private modifier, and other classes are not directly accessible. In addition, the Singleton pattern class also needs to have the private construction method, this is not difficult to understand, if the construction method is public, then the class outside can directly invoke the constructor method of the class, so that there is no singleton characteristics. So how do you get the unique instance of the class? This requires a public fetch, which returns a singleton pattern class, and the returned result is naturally the only instance in the class. With this in mind, we can implement the simplest single-case pattern class:

It has to be said that such a practice has indeed met the requirements of a singleton model, under normal circumstances there is only one singleton object in the system. But what if there is concurrency? Two users access the class's accessor at the same time, assuming that the singleton object has not yet been instantiated, the system will call the construction method two times, so that there will be two instances of the Singleton class in the system. A single case that illustrates this approach does not take into account concurrency, stating that the interviewer is just a cursory understanding of the singleton pattern, and does not think deeply about it, to make the interviewer satisfied? Oh......

Java is a lot easier to say than C + + for the ease of programming. A synchronized keyword solves the common locking problem when considering thread synchronization. The Synchronized keyword, when used to decorate a method or a block of code, guarantees that at most one thread executes the code at the same time. That is, when two threads access the synchronized method or block of code in the class at the same time, only one thread can execute its code, and the other can only wait until the current thread call ends. The implementation of the single example is so easy! Simply change the code slightly:

This way the interviewer will think you this interviewer is more comprehensive when thinking about the problem, considering the concurrency situation, compared to the way before the interviewer will think: young, very promising Oh!

However, it is not enough to let the interviewer look good, we have to let him appreciate, through a single case such a small problem can get an offer. This means that the second implementation can be optimized. How to optimize it? We see that the current system will be locked every time the acquisition method is called, and the time to lock up is where we can optimize. Now what I'm thinking is that we just need to add a lock to the first call and then no more locks, so we save time for each call to locking, although the time for the computer to perform the lock is very short but over time it is quite a bit longer.

So how does it come true? This requires the introduction of another keyword volatile. The volatile modifier ensures that instance = new Singleton (); the corresponding instruction is not reordered (the JVM may change the order of execution to improve its performance if it finds that the code execution sequence changes but the results are unchanged.) Good pit ... ), which is also thread-safe.

How to understand it?

    1. Thread 1 enters the Get method.

    2. Because single is null, thread 1 enters the synchronized block at//1.

    3. Thread 1 is pre-occupied by thread 2.

    4. Thread 2 enters the Get method.

    5. Because single is still null, thread 2 attempts to acquire a lock at//1. However, because thread 1 holds the lock, thread 2 is blocked at//1.

    6. Thread 2 is pre-occupied by thread 1.

    7. Thread 1 executes, because the instance at//2 is still null, thread 1 also creates a singleton object and assigns its reference to single.

    8. Thread 1 exits the synchronized block and returns the instance from the Get method.

    9. Thread 1 is pre-occupied by thread 2.

    10. Thread 2 Gets the lock at//1 and checks if single is null.

    11. Because single is non-null, and the second singleton object is not created, the object created by thread 1 is returned.

Like this procedure, the interviewer can not give you an offer after reading it? Sao years, the future is boundless Ah!

How to write an interviewer's view of Java Singleton

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.