人们宁愿去关心一个蹩脚电影演员的吃喝拉撒和鸡毛蒜皮,而不愿了解一个普通人波涛汹涌的内心世界。——路遥《平凡的世界》

首先是依赖lang3

1
2
3
4
5
6
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.11</version>
</dependency>

然后是工具类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package com.ruben.utils;

import org.apache.commons.lang3.time.FastDateFormat;

import java.util.concurrent.atomic.AtomicReference;

/**
* DateFormat.format()消耗较大,如果时间戳是递增的,而且同一单位内有多次format(),使用用本类减少重复调用.
* <p>
* From Log4j2 DatePatternConverter,进行了优化,根据输出格式是否毫秒级,决定缓存在秒级还是毫秒级.
*
* @author calvin
*/
public class CachingDateFormatter {
private final FastDateFormat fastDateFormat;
private final AtomicReference<CachedTime> cachedTime;
private final boolean onSecond;// 根据时间格式,决定缓存在

public CachingDateFormatter(String pattern) {
this(FastDateFormat.getInstance(pattern));
}

public CachingDateFormatter(FastDateFormat fastDateFormat) {
this.fastDateFormat = fastDateFormat;
onSecond = fastDateFormat.getPattern().indexOf("SSS") == -1;

long current = System.currentTimeMillis();
this.cachedTime = new AtomicReference<CachedTime>(new CachedTime(current, fastDateFormat.format(current)));
}

public String format(final long timestampMillis) {
CachedTime cached = cachedTime.get();

long timestamp = onSecond ? timestampMillis / 1000 : timestampMillis;

if (timestamp != cached.timestamp) {
final CachedTime newCachedTime = new CachedTime(timestamp, fastDateFormat.format(timestampMillis));
if (cachedTime.compareAndSet(cached, newCachedTime)) {
cached = newCachedTime;
} else {
cached = cachedTime.get();
}
}

return cached.formatted;
}

static final class CachedTime {
public long timestamp;
public String formatted;

public CachedTime(final long timestamp, String formatted) {
this.timestamp = timestamp;
this.formatted = formatted;
}
}
}

实际测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
private static final String PATTERN = "yyyy-MM-dd HH:mm:SSS";

public static void main(String[] args) {
// 原始方式
long dateTimeStart = System.nanoTime();
Stream.generate(() -> LocalDateTime.now().format(DateTimeFormatter.ofPattern(PATTERN))).limit(10000).collect(Collectors.toList());
long dateTimeEnd = System.nanoTime();
System.out.println((dateTimeEnd - dateTimeStart) / (1000.0 * 1000.0) + "ms");

// 工具类,手动获取实例
long start = System.nanoTime();
Stream.generate(() -> new CachingDateFormatter(FastDateFormat.getInstance(PATTERN)).format(System.currentTimeMillis())).limit(10000).collect(Collectors.toList());
long end = System.nanoTime();
System.out.println((end - start) / (1000.0 * 1000.0) + "ms");

// 工具类,自动获取实例
long patternStart = System.nanoTime();
Stream.generate(() -> new CachingDateFormatter(PATTERN).format(System.currentTimeMillis())).limit(10000).collect(Collectors.toList());
long patternEnd = System.nanoTime();
System.out.println((patternEnd - patternStart) / (1000.0 * 1000.0) + "ms");
}

输出时间测试结果

image-20210128202829524

而且这个耗时是会越来越短的