[ 
https://issues.apache.org/jira/browse/LOG4J2-1338?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=15325268#comment-15325268
 ] 

Matt Sicker commented on LOG4J2-1338:
-------------------------------------

You can do the same thing in recent Java (since 5 I think) using volatile and 
double-checked locking. That's how we normally do lazy initialization.

> 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: 朱孟柱
>              Labels: lazy-initialization
>
> 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: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to