本文主要是介绍优化System.currentTimeMillis()获取时间的性能问题,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
优化System.currentTimeMillis()获取时间的性能问题
import org.apache.commons.lang3.concurrent.BasicThreadFactory;import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;/*** @Description: 优化System.currentTimeMillis()获取时间的性能问题* @author: Be.insighted* @create: 2024/9/3 10:02* @since 1.0.0*/public class SystemClockUtil {private final long period;private final AtomicLong now;private SystemClockUtil(long period) {this.period = period;this.now = new AtomicLong(System.currentTimeMillis());scheduleClockUpdating();}private static class InstanceHolder {public static final SystemClockUtil INSTANCE = new SystemClockUtil(10);}private static SystemClockUtil instance() {return InstanceHolder.INSTANCE;}private void scheduleClockUpdating() {ScheduledExecutorService scheduler = new ScheduledThreadPoolExecutor(1,new BasicThreadFactory.Builder().namingPattern("System-Clock-%d").daemon(true).build());scheduler.scheduleAtFixedRate(() -> now.set(System.currentTimeMillis()), period, period, TimeUnit.MILLISECONDS);}private long currentTimeMillis() {return now.get();}public static long now() {return instance().currentTimeMillis();}
}
这篇关于优化System.currentTimeMillis()获取时间的性能问题的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!