All Downloads are FREE. Search and download functionalities are using the official Maven repository.

cn.vonce.sql.uitls.SystemClock Maven / Gradle / Ivy

There is a newer version: 1.7.0-beta1
Show newest version
package cn.vonce.sql.uitls;

import java.sql.Timestamp;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

/**
 * System Clock
 * 

* 利用ScheduledExecutorService实现高并发场景下System.curentTimeMillis()的性能问题的优化. * * @author lry */ public enum SystemClock { // ==== INSTANCE(1); private final long period; private final AtomicLong nowTime; private boolean started = false; private ScheduledExecutorService executorService; SystemClock(long period) { this.period = period; this.nowTime = new AtomicLong(System.currentTimeMillis()); } /** * The initialize scheduled executor service */ public void initialize() { if (started) { return; } this.executorService = new ScheduledThreadPoolExecutor(1, new ThreadFactory() { @Override public Thread newThread(Runnable r) { Thread thread = new Thread(r, "system-clock"); thread.setDaemon(true); return thread; } }); executorService.scheduleAtFixedRate(new Runnable() { @Override public void run() { nowTime.set(System.currentTimeMillis()); } }, this.period, this.period, TimeUnit.MILLISECONDS); Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { @Override public void run() { destroy(); } })); started = true; } /** * The get current time milliseconds * * @return long time */ public long currentTimeMillis() { return started ? nowTime.get() : System.currentTimeMillis(); } /** * The get string current time * * @return string time */ public String currentTime() { return new Timestamp(currentTimeMillis()).toString(); } /** * The destroy of executor service */ public void destroy() { if (executorService != null) { executorService.shutdown(); } } }





© 2015 - 2025 Weber Informatics LLC | Privacy Policy