注意了!System.currentTimeMillis() 存在性能問題...

Java技術(shù)棧
www.javastack.cn
關(guān)注閱讀更多優(yōu)質(zhì)文章
作者:LittleMagic
鏈接:https://www.jianshu.com/p/d2039190b1cb
System.currentTimeMillis()是極其常用的基礎(chǔ)Java API,廣泛地用來獲取時(shí)間戳或測(cè)量代碼執(zhí)行時(shí)長(zhǎng)等,在我們的印象中應(yīng)該快如閃電。
但實(shí)際上在并發(fā)調(diào)用或者特別頻繁調(diào)用它的情況下(比如一個(gè)業(yè)務(wù)繁忙的接口,或者吞吐量大的需要取得時(shí)間戳的流式程序),其性能表現(xiàn)會(huì)令人大跌眼鏡。
直接看下面的Demo:
public?class?CurrentTimeMillisPerfDemo?{
????private?static?final?int?COUNT?=?100;
????public?static?void?main(String[]?args)?throws?Exception?{
????????long?beginTime?=?System.nanoTime();
????????for?(int?i?=?0;?i?????????????System.currentTimeMillis();
????????}
????????long?elapsedTime?=?System.nanoTime()?-?beginTime;
????????System.out.println("100?System.currentTimeMillis()?serial?calls:?"?+?elapsedTime?+?"?ns");
????????CountDownLatch?startLatch?=?new?CountDownLatch(1);
????????CountDownLatch?endLatch?=?new?CountDownLatch(COUNT);
????????for?(int?i?=?0;?i?????????????new?Thread(()?->?{
????????????????try?{
????????????????????startLatch.await();
????????????????????System.currentTimeMillis();
????????????????}?catch?(InterruptedException?e)?{
????????????????????e.printStackTrace();
????????????????}?finally?{
????????????????????endLatch.countDown();
????????????????}
????????????}).start();
????????}
????????beginTime?=?System.nanoTime();
????????startLatch.countDown();
????????endLatch.await();
????????elapsedTime?=?System.nanoTime()?-?beginTime;
????????System.out.println("100?System.currentTimeMillis()?parallel?calls:?"?+?elapsedTime?+?"?ns");
????}
}
執(zhí)行結(jié)果如下圖。

可見,并發(fā)調(diào)用System.currentTimeMillis()一百次,耗費(fèi)的時(shí)間是單線程調(diào)用一百次的250倍。
如果單線程的調(diào)用頻次增加(比如達(dá)到每毫秒數(shù)次的地步),也會(huì)觀察到類似的情況。關(guān)注公眾號(hào)Java技術(shù)棧可以獲取 JVM 和多線程及更多面試題及答案。
實(shí)際上在極端情況下,System.currentTimeMillis()的耗時(shí)甚至?xí)葎?chuàng)建一個(gè)簡(jiǎn)單的對(duì)象實(shí)例還要多,看官可以自行將上面線程中的語句換成new HashMap<>之類的試試看。
為什么會(huì)這樣呢?
來到HotSpot源碼的hotspot/src/os/linux/vm/os_linux.cpp文件中,有一個(gè)javaTimeMillis()方法,這就是System.currentTimeMillis()的native實(shí)現(xiàn)。
jlong?os::javaTimeMillis()?{
??timeval?time;
??int?status?=?gettimeofday(&time,?NULL);
??assert(status?!=?-1,?"linux?error");
??return?jlong(time.tv_sec)?*?1000??+??jlong(time.tv_usec?/?1000);
}
挖源碼就到此為止,因?yàn)橐呀?jīng)有國外大佬深入到了匯編的級(jí)別來探究,詳情可以參見 The Slow currentTimeMillis() 這篇文章,我就不班門弄斧了。
http://pzemtsov.github.io/2017/07/23/the-slow-currenttimemillis.html
簡(jiǎn)單來講就是:
調(diào)用gettimeofday()需要從用戶態(tài)切換到內(nèi)核態(tài); gettimeofday()的表現(xiàn)受Linux系統(tǒng)的計(jì)時(shí)器(時(shí)鐘源)影響,在HPET計(jì)時(shí)器下性能尤其差; 系統(tǒng)只有一個(gè)全局時(shí)鐘源,高并發(fā)或頻繁訪問會(huì)造成嚴(yán)重的爭(zhēng)用。
HPET計(jì)時(shí)器性能較差的原因是會(huì)將所有對(duì)時(shí)間戳的請(qǐng)求串行執(zhí)行。TSC計(jì)時(shí)器性能較好,因?yàn)橛袑S玫募拇嫫鱽肀4鏁r(shí)間戳。缺點(diǎn)是可能不穩(wěn)定,因?yàn)樗羌冇布挠?jì)時(shí)器,頻率可變(與處理器的CLK信號(hào)有關(guān))。
關(guān)于HPET和TSC的細(xì)節(jié)可以參見:
https://en.wikipedia.org/wiki/High_Precision_Event_Timer
https://en.wikipedia.org/wiki/Time_Stamp_Counter
另外,可以用以下的命令查看和修改時(shí)鐘源。
~?cat?/sys/devices/system/clocksource/clocksource0/available_clocksource
tsc?hpet?acpi_pm
~?cat?/sys/devices/system/clocksource/clocksource0/current_clocksource
tsc
~?echo?'hpet'?>?/sys/devices/system/clocksource/clocksource0/current_clocksource
如何解決這個(gè)問題?
最常見的辦法是用單個(gè)調(diào)度線程來按毫秒更新時(shí)間戳,相當(dāng)于維護(hù)一個(gè)全局緩存。其他線程取時(shí)間戳?xí)r相當(dāng)于從內(nèi)存取,不會(huì)再造成時(shí)鐘資源的爭(zhēng)用,代價(jià)就是犧牲了一些精確度。
具體代碼如下:
public?class?CurrentTimeMillisClock?{
????private?volatile?long?now;
????private?CurrentTimeMillisClock()?{
????????this.now?=?System.currentTimeMillis();
????????scheduleTick();
????}
????private?void?scheduleTick()?{
????????new?ScheduledThreadPoolExecutor(1,?runnable?->?{
????????????Thread?thread?=?new?Thread(runnable,?"current-time-millis");
????????????thread.setDaemon(true);
????????????return?thread;
????????}).scheduleAtFixedRate(()?->?{
????????????now?=?System.currentTimeMillis();
????????},?1,?1,?TimeUnit.MILLISECONDS);
????}
????public?long?now()?{
????????return?now;
????}
????
????public?static?CurrentTimeMillisClock?getInstance()?{
????????return?SingletonHolder.INSTANCE;
????}
????private?static?class?SingletonHolder?{
????????private?static?final?CurrentTimeMillisClock?INSTANCE?=?new?CurrentTimeMillisClock();
????}
}
使用的時(shí)候,直接CurrentTimeMillisClock.getInstance().now()就可以了。
不過,在System.currentTimeMillis()的效率沒有影響程序整體的效率時(shí),就不必忙著做優(yōu)化,這只是為極端情況準(zhǔn)備的。






關(guān)注Java技術(shù)棧看更多干貨


