Single-case mode with Android

Source: Internet
Author: User

http://blog.csdn.net/ljianhui/article/details/29275655

The singleton mode under multithreading is unsafe

Single-instance mode in Android

There are a large number of singleton classes in Android, such as: Inputmethodmanager class, Calendardatabasehelper class, editable class, and so on. In these classes, there is a method getinstance, where the method either returns the reference to the object directly or determines whether a reference to a class is NULL, if it is not NULL, returns the reference directly, and if NULL, a new object and returns. For example, for the Calendardatabasehelper class, the following code exists:

 1  public  static  synchronized   Calendardatabasehelper getinstance (contextcontext)  2  3  if  (Ssingleton = = null  )  4  {  Ssingleton = Newcalendardatabasehelper (context);  6   7  return   Ssingleton;  8 } 

As you can see from the code here, the implementation is very similar to what is described above, but because Java does not use the programmer to manage the memory itself, it does not require a reference count, and the method is public static. The synchronized is to ensure that only one thread can enter the method at the same time, which is to prevent the 6th one from the above-mentioned security problem in multi-threaded mode.

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.