系统高并发直接调用System.currentTimeMillis()存在性能问题,因此统一个后台线程维护当前时间缓存。

    1. import org.jetbrains.annotations.NotNull;
    2. import java.sql.Timestamp;
    3. import java.time.Instant;
    4. import java.time.LocalDateTime;
    5. import java.time.ZoneId;
    6. import java.util.concurrent.ScheduledThreadPoolExecutor;
    7. import java.util.concurrent.ThreadFactory;
    8. import java.util.concurrent.TimeUnit;
    9. import java.util.concurrent.atomic.AtomicLong;
    10. /**
    11. * <p> 获取当前时间时钟时钟工具类 解决直接获取时间的性能问题 </p>
    12. *
    13. * @author mori
    14. * @since 2020/12/30 11:53
    15. */
    16. public final class SystemClock {
    17. private final long period;
    18. private final AtomicLong now;
    19. private SystemClock(long period) {
    20. this.period = period;
    21. this.now = new AtomicLong(System.currentTimeMillis());
    22. this.scheduleClockUpdating();
    23. }
    24. private static SystemClock instance() {
    25. return InstanceHolder.INSTANCE;
    26. }
    27. public static long now() {
    28. return instance().currentTimeMillis();
    29. }
    30. public static String nowDate() {
    31. return (new Timestamp(instance().currentTimeMillis())).toString();
    32. }
    33. /**
    34. * 现在当地的日期时间
    35. *
    36. * @return {@link LocalDateTime}
    37. */
    38. public static LocalDateTime nowLocalDateTime() {
    39. Instant instant = Instant.ofEpochMilli(instance().currentTimeMillis());
    40. ZoneId zone = ZoneId.systemDefault();
    41. return LocalDateTime.ofInstant(instant, zone);
    42. }
    43. private void scheduleClockUpdating() {
    44. new ScheduledThreadPoolExecutor(1, new UpdateThreadDaemonFactory()
    45. ).scheduleAtFixedRate(() -> {
    46. now.set(System.currentTimeMillis());
    47. }, this.period, this.period, TimeUnit.MILLISECONDS);
    48. }
    49. private long currentTimeMillis() {
    50. return this.now.get();
    51. }
    52. public static class UpdateThreadDaemonFactory implements ThreadFactory {
    53. private static int threadInitNumber = 0;
    54. private static synchronized int nextThreadNum() {
    55. return threadInitNumber++;
    56. }
    57. @Override
    58. public Thread newThread(@NotNull Runnable r) {
    59. Thread thread = new Thread(r, "Thread-System-Lock-" + nextThreadNum());
    60. thread.setDaemon(true);
    61. return thread;
    62. }
    63. }
    64. private static class InstanceHolder {
    65. private static final SystemClock INSTANCE = new SystemClock(1L);
    66. private InstanceHolder() {
    67. }
    68. }
    69. }