Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

Multithreading in singleton mode

Shulou Source: shulou.com Published: 2022-06-03 04:35:20 10月17日 Update

The principle of singleton pattern: ensure that a class has an instance and provide a global access point (memory address is unique)

Implementation method:

1. Full mode:

1: publicclass Singleton {2: 3: privatestatic Singleton s = null; 4: 5: private Singleton () {6: 7:} 8: 9: publicstatic Singleton getInstance () {10: 11: if (s = = null) {12: s = new Singleton (); 13:} 14: return s; 15:} 16:}

2. Hungry man model

1: publicclass Singleton {2: privatestatic Singleton s = new Singleton (); 3: private Sinleton () {} 4: publicstatic Singleton getInstance () {5: return s; 6:} 7:} singleton mode thread safety issues: 1. Implement 1: publicclass Single 2: {3: privatestatic Single single through the synchronized keyword 4: private Single () {5:} 6: publicstaticsynchronized Single getInstance () {7: if (single = = null) {8: single = new Single (); 9:} 10: return single 11:} 12:} in this way, you can force only one thread to call the method to get an instance of the class while the program is running, but it also has the disadvantage that synchronization is needed only when the object is used for the first time. When you get the object again, synchronization is no longer needed, and synchronization becomes redundant. 2. In fact, the hungry mode is an effective means to improve multithreading, so JVM ensures that when any thread accesses a singleton object, the instance must be created first. The code is the same as above 3. Another way to improve multithreading 1: publicclass Singleton {2: 3: privatevolatilestatic Singleton uniqueInstance 4: 5: private Singleton () {} 6: 7: publicstatic Singleton getInstance () {8: if (uniqueInstance = = null) {/ / (1) 9: / / the code here 10: synchronized () {11: / / check again 12: if (uniqueInstance = = null) 13: uniqueInstance = new Singleton () 14:} 15:} 16: return uniqueInstance; 17:} 18:}

At the beginning, if 1, 2, or 3 threads go to (1), suppose 1 enters the synchronization block, and 2, 3 wait. 1 after instantiation, 2 enters the synchronization block, finds that uniqueInstance is no longer empty, and jumps out of the synchronization block. Then 3 enters and jumps out of the synchronous block.

The volatile keyword ensures that when a uniqueInstance variable is initialized to an Singleton instance, multiple threads correctly uniqueInstance the variable. If performance is your priority, then this can help you greatly reduce the time consumption of getInstance ().

Tags: Thread synchronization pattern instance only object code key keyword variable way first time guarantee effective secure so practice global memory again Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MariaDB OPPO Reno Microsoft Shulou Technology Docker