On the Design Model-singleton Model

Source: Internet
Author: User

On the Design Model-singleton Model

Import java. io. serializable; public class Singleton implements Serializable {private Singleton () {} private static class SingletonHolder {private static final Singleton INSTANCE = new Singleton ();} public static Singleton getInstance () {return SingletonHolder. INSTANCE;} private Object readResolve () {return SingletonHolder. INSTANCE ;}}

What is the difference between the above Code?

Let's first recall the advantages and disadvantages of the Order example mode:

Lazy mode: There is an object lock. Lock competition has a certain impact on performance.

Hunger mode: Initialize the singleton object at the beginning. If the initialization time of the singleton object is long (large object), the time consumed for class loading is increased.


The above Code uses internal classes. When classes are loaded, the singleton object is not initialized and the singleton object is initialized for the first time. Due to the loading mechanism of internal classes, solved the lock problem,


Here, the reader can already know the role of the internal class, but there is another difference that is not mentioned, but the private method is added.

Oh, by the way, let's take a look at the test results:



The result is True, which is incredible,

Yes. This method solves the problem of serialization destroying the singleton mode.


Legacy: reflection can destroy the singleton Mode

Zookeeper

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.