Thinking about the loading time of Java classes caused by two bugs

Source: Internet
Author: User

There is a singleton class that reads:

 Public  class bluetoothmanager {    Private StaticBluetoothmanager sinstance; Public StaticBluetoothmanagergetinstance() {if(Sinstance = =NULL) {synchronized(Bluetoothmanager.class) {if(Sinstance = =NULL) {sinstance =NewBluetoothmanager (); }            }        }returnSinstance; }Private FinalHandler Mhandler =NewHandler () {@Override         Public void Handlemessage(Message msg) {Super. Handlemessage (msg); }    };Private FinalLescancallback Mlescancallback =NewLescancallback () {@Override         Public void Onlescan(Bluetoothdevice device,intRssibyte[] Scanrecord) {}};}

This class occasionally crashes during the actual run, because calling getinstance may be in the main thread, or in a child thread, and the first call to getinstance will trigger the creation of the Bluetoothmanager singleton object. Since Mhandler is a member variable inside an object, it is initialized together, and because there is no incoming looper, the looper of the current caller's thread is passed by default, which throws an exception if the thread does not have looper. So this problem occurs when you first call getinstance in a child thread without looper, the solution is to pass in a valid looper when constructing handler.

The second problem is lescancallback, this class is a callback that is scanned with Bluetooth ble and needs to be used in API 18 and above, or it will crash. Under API 18, even if not scanned, this mlescancallback is not used, as long as any action triggers the initialization of mlescancallback, it will cause a crash.

What would trigger the initialization of this internal member variable for Bluetoothmanager? Because it is not static, the Mlescancallback is initialized only when the Bluetoothmanager object is created. If Mlescancallback is static, it will be initialized as long as the Bluetoothmanager class is initialized.

Now let's summarize the Java class load, and first look at the timing of class initialization:

    1. When instantiating an object using the New keyword, refer to a static field of a class (except for a static field that was final decorated, has placed the result in a constant pool at compile time), or when a static method is called.
    2. When you use the Java.lang.reflect package method to make a reflection call to a class, if the class has not been initialized, you need to trigger its initialization first.
    3. When initializing a class, it is necessary to trigger the initialization of its parent class if it finds that its parent class has not yet been initialized.
    4. When the virtual machine starts, the user needs to specify a main class to execute (the class that contains the main () method), and the virtual opportunity initializes the main class first.

Note that the first of the above, the final modified static variable, if it is similar to a string this basic type will be put into a constant pool, reference such a field is not OK with the class, so does not trigger the initialization of the class.

By the way, determining whether a class is initialized can be considered by logging in the class's global static code block.

When a class is initialized, the static code block of the class is called first, and then in the class is initialized (excluding the static inner class), and if the class object is created, then the non-static members in the class are initialized, and the constructor of the class is called finally.

Take a look at the following singleton patterns:

public  class  bluetoothmanager {private  bluetoothmanager  () {} private   Static  class  bluetoothmanagerholder {private< /span> static  bluetoothmanager instance = new     Bluetoothmanager (); } public  static  bluetoothmanager getinstance  () {return  bluetoothmanagerholder.instance; }}

Bluetoothmanagerholder initialization is not triggered when the Bluetoothmanager class is initialized, The initialization of Bluetoothmanagerholder is triggered only if the internal static member variable of Bluetoothmanagerholder is invoked when getinstance is called, so that the effect of lazy loading can be achieved. If there are multiple threads calling getinstance at the same time, because instance is initialized at the Bluetoothmanagerholder class initialization, it is guaranteed to be thread-safe by the Java Virtual machine without additional synchronization, and this singleton mode is recommended.

Thinking about the loading time of Java classes caused by two bugs

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.