You are viewing a plain text version of this content. The canonical link for it is here.
Posted to log4j-dev@logging.apache.org by "朱孟柱 (JIRA)" <ji...@apache.org> on 2016/03/30 06:07:25 UTC
[jira] [Created] (LOG4J2-1338) Why don't use
"initialization-on-demand holder idiom" to implement lazy inialization
朱孟柱 created LOG4J2-1338:
---------------------------
Summary: Why don't use "initialization-on-demand holder idiom" to implement lazy inialization
Key: LOG4J2-1338
URL: https://issues.apache.org/jira/browse/LOG4J2-1338
Project: Log4j 2
Issue Type: Question
Components: Core
Affects Versions: 2.5
Reporter: 朱孟柱
I'm reading the source code of CachedClock in log4j-core, and I find that it uses the DCL pattern which is recommended in the *Item 71: Use lazy initialization judiciously* of *Effective Java*.
It works fine, but I wonder why don't just use the [Initialization-on-demand holder idiom|https://en.wikipedia.org/wiki/Initialization-on-demand_holder_idiom], it seems more elegant and efficient.
Here is an example.
{code:title=MyCachedClock.java|borderStyle=solid}
public class MyCachedClock implements Clock {
private static final int UPDATE_THRESHOLD = 1000;
private volatile long millis = System.currentTimeMillis();
private short count = 0;
private static class MyCachedClockHolder {
private static MyCachedClock INSTANCE = new MyCachedClock();
}
public static MyCachedClock instance() {
return MyCachedClockHolder.INSTANCE;
}
private MyCachedClock() {
final Thread updater = new Log4jThread(new Runnable() {
@Override
public void run() {
while (true) {
final long time = System.currentTimeMillis();
millis = time;
// avoid explicit dependency on sun.misc.Util
LockSupport.parkNanos(1000 * 1000);
}
}
}, "Clock Updater Thread");
updater.setDaemon(true);
updater.start();
}
@Override
public long currentTimeMillis() {
if (++count > UPDATE_THRESHOLD) {
millis = System.currentTimeMillis(); // update volatile field: store-store barrier
count = 0; // after a memory barrier: this change _is_ visible to other threads
}
return millis;
}
}
{code}
--
This message was sent by Atlassian JIRA
(v6.3.4#6332)
---------------------------------------------------------------------
To unsubscribe, e-mail: log4j-dev-unsubscribe@logging.apache.org
For additional commands, e-mail: log4j-dev-help@logging.apache.org