-
Notifications
You must be signed in to change notification settings - Fork 27
Closed
Description
The static methods Client.getInstance()
and getRawClient()
do not perform safe lazy initialization:
Java-Objective-C-Bridge/src/main/java/ca/weblite/objc/Client.java
Lines 46 to 51 in 473221a
public static Client getInstance(){ | |
if ( instance == null ){ | |
instance = new Client(); | |
} | |
return instance; | |
} |
To correct this perform these steps:
- Make
instance
andrawClient
volatile - In the access methods, do double checked locking:
- Check if
instance == null
(for increased performance store current value in local var) - If
null
:- Synchronize
- Check again if
instance == null
(and overwrite local var, see 2.1) - If
null
: Initialize (and update local var, see 2.1)
- Return
instance
(or local var) value
- Check if
E.g.:
private static volatile Client instance;
public Client getInstance() {
Client localInstance = instance;
if (localInstance == null) {
// Could also use dedicated lock for `instance` and `rawClient`, but likely not worth it
synchronized (Client.class) {
localInstance = instance;
if (localInstance == null) {
instance = localInstance = new Client();
}
}
}
return localInstance;
}
Or alternatively making these methods synchronized
would also suffice and the performance decrease (if any) would likely be negligible.
See also "LCK10-J. Use a correct form of the double-checked locking idiom"
For sanity I would also recommend:
- Implementing a
private
constructor, currentlyClient
has the public default constructor - Making fields
coerceInputs
andcoerceOutputs
final
and initializing them from the constructor
Metadata
Metadata
Assignees
Labels
No labels