DO NOT MERGE: ConnectivityThread: use lazy holder idiom
This patch changes the way that the ConnectivityThread is lazily instantiated by using the "lazy initialization holder class idiom". The first code point that tries to obtain a reference to the unique ConnectivityThread instance will trigger the creation of the Singleton class, which will guarantee a thread-safe initialization of the static INSTANCE field inside Singleton according to the language specs. This is the Item #71 of Effective Java. The unique static instance of ConnectivityThread is not stored directly inside ConnectivityThread class but is stored in a static nested class. This is to avoid triggering the creation of that unique instance when Zygote does class preloading at phone startup. Otherwise this would lead to Zygote creating a new OS thread during preloading, which is a fatal error. Test: frameworks-wifi tests pass Bug: 26749700 Bug: 28537383 Bug: 32130437 (cherry picked from commit3ab84b087a) (cherry picked from commit8f201294fe) Change-Id: Ic9a31809ef19e618246f9aa17f5df29bd65f8510
This commit is contained in:
committed by
Lorenzo Colitti
parent
9954fbdb65
commit
e4f69293e9
@@ -27,25 +27,30 @@ import android.os.Looper;
|
||||
* @hide
|
||||
*/
|
||||
public final class ConnectivityThread extends HandlerThread {
|
||||
private static ConnectivityThread sInstance;
|
||||
|
||||
// A class implementing the lazy holder idiom: the unique static instance
|
||||
// of ConnectivityThread is instantiated in a thread-safe way (guaranteed by
|
||||
// the language specs) the first time that Singleton is referenced in get()
|
||||
// or getInstanceLooper().
|
||||
private static class Singleton {
|
||||
private static final ConnectivityThread INSTANCE = createInstance();
|
||||
}
|
||||
|
||||
private ConnectivityThread() {
|
||||
super("ConnectivityThread");
|
||||
}
|
||||
|
||||
private static synchronized ConnectivityThread getInstance() {
|
||||
if (sInstance == null) {
|
||||
sInstance = new ConnectivityThread();
|
||||
sInstance.start();
|
||||
}
|
||||
return sInstance;
|
||||
private static ConnectivityThread createInstance() {
|
||||
ConnectivityThread t = new ConnectivityThread();
|
||||
t.start();
|
||||
return t;
|
||||
}
|
||||
|
||||
public static ConnectivityThread get() {
|
||||
return getInstance();
|
||||
return Singleton.INSTANCE;
|
||||
}
|
||||
|
||||
public static Looper getInstanceLooper() {
|
||||
return getInstance().getLooper();
|
||||
return Singleton.INSTANCE.getLooper();
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user