001 /* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache license, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the license for the specific language governing permissions and 015 * limitations under the license. 016 */ 017 package org.apache.logging.log4j.core.util; 018 019 import java.util.concurrent.locks.LockSupport; 020 021 /** 022 * This Clock implementation is similar to CachedClock. It is slightly faster at 023 * the cost of some accuracy. 024 */ 025 public final class CoarseCachedClock implements Clock { 026 private static volatile CoarseCachedClock instance; 027 private static final Object INSTANCE_LOCK = new Object(); 028 // ignore IDE complaints; volatile long is fine 029 private volatile long millis = System.currentTimeMillis(); 030 031 private final Thread updater = new Thread("Clock Updater Thread") { 032 @Override 033 public void run() { 034 while (true) { 035 millis = System.currentTimeMillis(); 036 037 // avoid explicit dependency on sun.misc.Util 038 LockSupport.parkNanos(1000 * 1000); 039 } 040 } 041 }; 042 043 private CoarseCachedClock() { 044 updater.setDaemon(true); 045 updater.start(); 046 } 047 048 /** 049 * Returns the singleton instance. 050 * 051 * @return the singleton instance 052 */ 053 public static CoarseCachedClock instance() { 054 // LOG4J2-819: use lazy initialization of threads 055 CoarseCachedClock result = instance; 056 if (result == null) { 057 synchronized (INSTANCE_LOCK) { 058 result = instance; 059 if (result == null) { 060 instance = result = new CoarseCachedClock(); 061 } 062 } 063 } 064 return result; 065 } 066 067 /** 068 * Returns the value of a private long field that is updated by a background 069 * thread once every millisecond. Because timers on most platforms do not 070 * have millisecond granularity, the returned value may "jump" every 10 or 071 * 16 milliseconds. 072 * @return the cached time 073 */ 074 @Override 075 public long currentTimeMillis() { 076 return millis; 077 } 078 }