[slf4j-user] Recommendation for library writers: use thiscopy and paste wrapper around SLF4j to avoid default static initialization

Joachim Durchholz jo at durchholz.org
Sat Mar 18 22:10:34 CET 2017


Am 18.03.2017 um 20:45 schrieb Ceki Gülcü:
 > Getting a NOPLogger involves reading the value of
> INITIALIZATION_STATE which is a volatile int. Unless reading volatile
> variables is expensive in Android,

They can be.

If the CPU has first-level caches that are not shared between all cores, 
then it can happen that the value gets read into two caches, then 
updated in one cache.
Smart cores keep track of what addresses are currently in other cores' 
caches, and if they update a value, they first ask the other cores to 
evict the cached address, so the standard case (shared data is mostly 
just read) can run at full speed.
Dumb cores need a lock instruction, causing the core to pull any updated 
value from other cores' caches.

Smart JVM implementors, coding the JVM in C, will find out whether the 
CPU they are porting the JVM to is smart or dumb, and generate a lock 
instruction if the CPU is dumb - or if they don't know what they're 
doing, or if they cannot be sure because a few CPU batches had bugs in 
their cache implementation, or if they cannot be sure because they 
aren't given enough time to properly test everything.

If you can make SLF4J's initialization idempotent, i.e. running it twice 
doesn't matter, then you can keep the "initialized" status in a normal 
variable. The update from "not initialized" to "initialized" may not 
already be set for all threads, so multiple threads may run the 
initialization, and one of them may overwrite the other's result, but 
that doesn't matter...

The other option would be to forfeit laziness and do all SLF4J 
initialization in class initialization code, i.e. inside of static{} blocks.
The JVM semantics guarantees that static{} code is executed once and 
exactly once, which is exactly what's needed.
Of course the "initialized" flag is still present, it's just in the 
class data of the JVM - however, since class loading is so important, 
this is going to be the most-optimized code path.


More information about the slf4j-user mailing list