The difference between the implementation of the A Hungry man mode and the static inner class implementation of the Singleton pattern

Source: Internet
Author: User

The A Hungry Man method implementation code is as follows:

 PackagePriv.jack.dp.demo.singleton;/** * @authorJack * A hungry man mode singleton * Thread safety * does not support lazy loading, easy to generate garbage objects * Advantages: No lock, execution efficiency will improve. */ Public classHungrysingleton {Private StaticHungrysingleton INSTANCE =NewHungrysingleton (); PrivateHungrysingleton () {System.out.println ("Init ..."); }         Public voidHello () {System.out.println ("Hello world!"); }         Public StaticHungrysingleton getinstance () {returnINSTANCE; }         Public Static voidmain (String [] args) {System.out.println ("Main start ...");     Hungrysingleton.getinstance (). hello (); }}

Static inner class implementation code:

 PackagePriv.jack.dp.demo.singleton;/** * @authorJack * Supports lazy loading, multi-threaded * objects are created at the time of use*/ Public classStaticinnersingleton {Private Static classstaticinnersingletonholder{Private Static FinalStaticinnersingleton INSTANCE =NewStaticinnersingleton (); }        PrivateStaticinnersingleton () {System.out.println ("Init ..."); }         Public Static FinalStaticinnersingleton Getinstantce () {returnstaticinnersingletonholder.instance; }         Public voidHello () {System.out.println ("Hello world!"); }             Public Static voidmain (String [] args) {System.out.println ("Main start ...");     Staticinnersingleton.getinstantce (). hello (); }    }

A hungry man mode run result

init...main Start...hello  World!

Static internal class mode run result

main Start...init...hello  world!

The difference is that static internal classes are lazy-loaded and take into account high-performance benefits.

The difference between the implementation of the A Hungry man mode and the static inner class implementation of the Singleton pattern

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.