Android Development design mode--singleton mode about thread unsafe problem handling

Source: Internet
Author: User

Singleton mode is the most common and simplest design pattern in design mode, which ensures that only one instance exists in the program and can be accessed globally. For example, in the Android real-world app development using the account information object management, database objects (Sqliteopenhelper), etc. will be used in the singleton mode. Here are some examples of the points we need to be aware of when applying a singleton pattern in the development process.


First, the role
Singleton mode (Singleton): guarantees that a class has only one instance and provides a global access point to access it

Second, the application scenario

1. An instance object in the app needs to be accessed frequently.

2. Only one instance will exist for each boot in the app. such as account system, database system.

Three, the commonly used way

(1) Lazy type

This is a very easy way to write out in development, as follows

[Java]View PlainCopy 
  1. Public class Singleton {
  2. / * Holds private static instances, prevents references, and assigns null here to enable lazy loading * /
  3. private static Singleton instance = null;
  4. / * Private construction method to prevent instantiation of * /
  5. Private Singleton () {
  6. }
  7. /* 1: Lazy, static engineering method, create an instance */
  8. public static Singleton getinstance () {
  9. if (instance = = null) {
  10. Instance = new Singleton ();
  11. }
  12. return instance;
  13. }
  14. }

Call:

[Java]View PlainCopy 
    1. Singleton.getinstance (). method ();

Pros: Lazy Loading (load only when needed)

Disadvantage: Threads are unsafe and are prone to unsynchronized situations in multiple threads, such as when a database object is frequently read and written.

(2) plus sync lock

Now that the thread is unsafe, add the sync lock, an addition like this:

[Java]View PlainCopy 
    1. /*2. Lazy Variant, solving thread-safety problems **/
    2. public static synchronized Singleton getinstance () {
    3. if (instance = = null) {
    4. Instance = new Singleton ();
    5. }
    6. return instance;
    7. }

A more general way of writing is this

[Java]View PlainCopy 
  1. /* plus synchronized, but each time the instance is invoked it will load **/
  2. public static Singleton getinstance () {
  3. synchronized (Singleton. Class) {
  4. if (instance = = null) {
  5. Instance = new Singleton ();
  6. }
  7. }
  8. return instance;
  9. }

Call:

[Java]View PlainCopy 
    1. Singleton.getinstance (). method ();

Pros: Resolves a thread-insecure issue.

Cons: The efficiency is a bit low, each call to the instance to determine the synchronization lock

Add: The single example method used in the Android source code is: Inputmethodmanager,accessibilitymanager, etc. are all using this singleton mode

(3) Double test lock

To optimize (2) because each invocation of the instance to determine the synchronization lock problem, many people use the following a double-check method

[Java]View PlainCopy 
  1. /*3. Double Lock: Only when the first initialization is combined with a sync lock */
  2. public static Singleton getinstance () {
  3. if (instance = = null) {
  4. synchronized (Singleton. Class) {
  5. if (instance = = null) {
  6. Instance = new Singleton ();
  7. }
  8. }
  9. }
  10. return instance;
  11. }

This method seems to be a perfect solution to the above-mentioned efficiency problem, it may be in the concurrency is not much, the security is not very high situation can work perfectly, but this method also has unfortunate place. The problem is that it appears in this sentence

[Java]View PlainCopy 
    1. Instance = new Singleton ();

The optimization of the instruction rearrangement occurs during the JVM compilation, which causes the memory space to be allocated when the instance is actually not initialized, that is, instance!=null but not initialized, which causes the returned instance Not complete (refer to: http://www.360doc.com/content/11/0810/12/1542811_139352888.shtml).

Call:

[Java]View PlainCopy 
    1. Singleton.getinstance (). method ();

Advantage: It is possible to run the singleton mode perfectly if there is not much concurrency and security is not high

Disadvantage: There may be serious security risks during the compilation of different platforms.

Add: Open source project Android-universal-image-loader in Android image (https://github.com/nostra13/ Android-universal-image-loader) is used in this way .

(4) Implementation of the Inner class

The inner class is a good way to implement it, which can be recommended:

[Java]View PlainCopy 
  1. Public class Singletoninner {
  2. /** 
  3. * Inner class implements Singleton mode
  4. * Delay loading, reduce memory overhead
  5. *
  6. * @author Xuzhaohu
  7. *
  8. */
  9. private static class Singletonholder {
  10. private static Singletoninner instance = new Singletoninner ();
  11. }
  12. /** 
  13. * Private Constructors
  14. */
  15. Private Singletoninner () {
  16. }
  17. public static Singletoninner getinstance () {
  18. return singletonholder.instance;
  19. }
  20. protected void Method () {
  21. System.out.println ("Singletoninner");
  22. }
  23. }

Call:

[Java]View PlainCopy 
    1. Singletoninner.getinstance (). method ();

Pros: Lazy loading, thread safety (mutually exclusive when class loads in Java), and reduced memory consumption

(5) Methods of enumeration

This is a lot of people on the Web recommended a practice, but seemingly not widely used, we can try,

[Java]View PlainCopy 
  1. /**
  2. * @function: A singleton Mode enumeration implementation
  3. * @author Xuzhaohu
  4. *
  5. */
  6. Public enum Singletonenum {
  7. /** 
  8. * 1. Start support from Java1.5;
  9. * 2. Provision of a free serialization mechanism;
  10. * 3. Absolute prevention of multiple instantiation, even in the face of complex serialization or reflection attacks;
  11. */
  12. Instance
  13. private String others;
  14. Singletonenum () {
  15. }
  16. public Void Method () {
  17. System.out.println ("Singletonenum");
  18. }
  19. Public String getothers () {
  20. return others;
  21. }
  22. public void Setothers (String others) {
  23. this.others = others;
  24. }
  25. }

Call:

[Java]View PlainCopy 
    1. SingletonEnum.instance.method ();

Pros and Cons: like comments in code.

The above is mainly about the singleton mode 5 ways to create, you can according to their advantages and disadvantages of the actual use of personal projects. Talking about is a suggestion, we have more suggestions.

Android Development design mode--singleton mode about thread unsafe problem handling

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.