Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to implement Singleton pattern

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

How to achieve the Singleton model, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain for you in detail, people with this need can come to learn, I hope you can gain something.

Title

To design a class, we can only generate one instance of that class.

Analyze the simplest implementation

Private construction method

Static method to get an instance

Do you need to consider memory or concurrent environment

If you need to consider memory, create an instance object (hungry) when you use it, and not create an instance (lazy, lazy load) when you don't use it.

If you need to think about thread safety, make sure that getting instances is synchronized and avoid creating multiple instances.

Mode of realization

[x] 1. Single thread (lazy, hungry)

[x] 2. The efficiency of multithreading is not high (the method of locking to obtain instances)

[x] 3. Determine whether the instance already exists before and after adding the synchronization lock

[x] 4. Create an instance using static initialization (recommended, thread-safe, which takes up some memory)

[x] 5. Use static inner classes to create instances on demand (most recommended, thread-safe, efficient, smart you should be able to understand)

Coding to achieve 1. Single thread (lazy, hungry) single package cn.jast.java.offer.singleton;/** * simple hungry * * / public class SimpleHungerSingleton {private static SimpleHungerSingleton simpleSingleton; private SimpleHungerSingleton () {simpleSingleton = new SimpleHungerSingleton ();} public static SimpleHungerSingleton getInstance () {return simpleSingleton;}} simple lazy single package cn.jast.java.offer.singleton / * simple lazy singles * * / public class SimpleLazySingleton {private static SimpleLazySingleton simpleSingleton; private SimpleLazySingleton () {} public static SimpleLazySingleton getInstance () {if (simpleSingleton = = null) {simpleSingleton = new SimpleLazySingleton ();} return simpleSingleton }} Thread safety testing / * testing simple singleton thread safety * / public static void testSimpleLazySingleton () {Set singletonSet = Collections.synchronizedSet (new HashSet ()); ExecutorService executorService = Executors.newFixedThreadPool (50); for (int I = 0; I)

< 10; i++) { executorService.submit(()->

{SimpleLazySingleton simpleLazySingleton = SimpleLazySingleton.getInstance (); singletonSet.add (simpleLazySingleton);});} executorService.shutdown () While (true) {if (executorService.isShutdown ()) {if (singletonSet.size () > 1) {System.out.println ("simple singleton exists to create multiple instance objects, examples are as follows:"); System.out.println (singletonSet);} break }}}

Output:

A simple singleton exists to create multiple instance objects. Examples are as follows: [cn.jast.java.offer.singleton.SimpleLazySingleton@2b9283d, cn.jast.java.offer.singleton.SimpleLazySingleton@72fba635] 2. Inefficient multithreading (method of locking instances) package cn.jast.java.offer.singleton;public class Synchronized1Singleton {private static Synchronized1Singleton instance; private Synchronized1Singleton () {} / * each time an object is acquired, a lock is added to ensure that the object is created * @ return * / public static synchronized Synchronized1Singleton getInstance () {if (instance = = null) {instance = new Synchronized1Singleton () } return instance;}}

Test:

Public static void testSynchronized1Singleton () {long startTime = System.currentTimeMillis (); Set singletonSet = Collections.synchronizedSet (new HashSet ()); ExecutorService executorService = Executors.newFixedThreadPool (50); for (int I = 0; I

< 10; i++) { executorService.submit(()->

{Synchronized1Singleton singleton = Synchronized1Singleton.getInstance (); singletonSet.add (singleton);});} executorService.shutdown (); while (true) {if (executorService.isShutdown ()) {System.out.println (String.format ("execution time:% s ms", System.currentTimeMillis ()-startTime)) If (singletonSet.size () > 1) {System.out.println ("A simple singleton exists to create multiple instance objects. Examples are as follows:"); System.out.println (singletonSet);} break;}

Output:

Execution time: 72 ms (Note: a sample) 3. Determine whether the instance already exists package cn.jast.java.offer.singleton;public class Synchronized2Singleton {private static Synchronized2Singleton instance; private Synchronized2Singleton () {} public static Synchronized2Singleton getInstance () {if (instance==null) {synchronized (Synchronized2Singleton.class) {if (instance==null) {instance= new Synchronized2Singleton () before and after adding the synchronization lock } return instance;}} 4. Create an instance using static initialization (recommended, thread-safe) package cn.jast.java.offer.singleton;/** * recommended * / public class StaticInitializeSingleton {private static StaticInitializeSingleton instance; static {instance = new StaticInitializeSingleton ();} private StaticInitializeSingleton () {} public static StaticInitializeSingleton getInstance () {return instance;}} 5. Use static inner classes to create instances on demand (most recommended, thread-safe, efficient) package cn.jast.java.offer.singleton;/** * recommended * / public class StaticInnerClassSingleton {private StaticInnerClassSingleton () {} public static StaticInnerClassSingleton getInstance () {return Inner.instance;} private static class Inner {private static final StaticInnerClassSingleton instance = new StaticInnerClassSingleton ();}} complete test package cn.jast.java.offer.singleton Import java.util.*;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;public class Main {public static void main (String [] args) {/ / testSimpleLazySingleton (); testSynchronized1Singleton (); / / testSynchronized2Singleton (); / / testStaticInitializeSingleton (); / / testNestedClassSingleton () } / * Test thread safety for simple singletons * / public static void testSimpleLazySingleton () {Set singletonSet = Collections.synchronizedSet (new HashSet ()); ExecutorService executorService = Executors.newFixedThreadPool (50); for (int I = 0; I

< 10; i++) { executorService.submit(()->

{SimpleLazySingleton simpleLazySingleton = SimpleLazySingleton.getInstance (); singletonSet.add (simpleLazySingleton);});} executorService.shutdown () While (true) {if (executorService.isShutdown ()) {if (singletonSet.size () > 1) {System.out.println ("simple singleton exists to create multiple instance objects, examples are as follows:"); System.out.println (singletonSet);} break * / public static void testSynchronized1Singleton () {long startTime = System.currentTimeMillis (); Set singletonSet = Collections.synchronizedSet (new HashSet ()); ExecutorService executorService = Executors.newFixedThreadPool (50); for (int I = 0; I)

< 10; i++) { executorService.submit(()->

{Synchronized1Singleton singleton = Synchronized1Singleton.getInstance (); singletonSet.add (singleton);});} executorService.shutdown (); while (true) {if (executorService.isShutdown ()) {System.out.println (String.format ("execution time:% s ms", System.currentTimeMillis ()-startTime)) If (singletonSet.size () > 1) {System.out.println ("A simple singleton exists to create multiple instance objects. Examples are as follows:"); System.out.println (singletonSet);} break The efficiency of Synchronized2Singleton is several times or more than that of Synchronized1Singleton * / public static void testSynchronized2Singleton () {long startTime = System.currentTimeMillis (); Set singletonSet = Collections.synchronizedSet (new HashSet ()); ExecutorService executorService = Executors.newFixedThreadPool (50); for (int I = 0; I)

< 10; i++) { executorService.submit(()->

{Synchronized2Singleton singleton = Synchronized2Singleton.getInstance (); singletonSet.add (singleton);});} executorService.shutdown (); while (true) {if (executorService.isShutdown ()) {System.out.println (String.format ("execution time:% s ms", System.currentTimeMillis ()-startTime)) If (singletonSet.size () > 1) {System.out.println ("A simple singleton exists to create multiple instance objects. Examples are as follows:"); System.out.println (singletonSet);} break }} / * / public static void testStaticInitializeSingleton () {Set singletonSet = Collections.synchronizedSet (new HashSet ()); ExecutorService executorService = Executors.newFixedThreadPool (50); for (int I = 0; I

< 10; i++) { executorService.submit(()->

{Synchronized2Singleton singleton = Synchronized2Singleton.getInstance (); singletonSet.add (singleton);});} executorService.shutdown () While (true) {if (executorService.isShutdown ()) {if (singletonSet.size () > 1) {System.out.println ("simple singleton exists to create multiple instance objects, examples are as follows:"); System.out.println (singletonSet);} break } public static void testNestedClassSingleton () {Set singletonSet = Collections.synchronizedSet (new HashSet ()); ExecutorService executorService = Executors.newFixedThreadPool (50); for (int I = 0; I

< 10; i++) { executorService.submit(()->

{StaticInnerClassSingleton singleton = StaticInnerClassSingleton.getInstance (); singletonSet.add (singleton);});} executorService.shutdown () While (true) {if (executorService.isShutdown ()) {if (singletonSet.size () > 1) {System.out.println ("simple singleton exists to create multiple instance objects, examples are as follows:"); System.out.println (singletonSet);} break Answer your own question and answer

Q: why is the singleton pattern's way to get instances static? Answer: because the constructor is private, you cannot create an instance through new, so you can only get the instance through the class method. Can you create an instance through reflection?

Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report