主頁 > 後端開發 > 你還在用 Java 8?手把手教你從 Java 8 升級到 Java 17 全程序,真香!!

你還在用 Java 8?手把手教你從 Java 8 升級到 Java 17 全程序,真香!!

2022-11-16 06:30:47 後端開發

作者:挖坑的張師傅
來源:https://juejin.cn/user/430664257374270

Java 8 是舊時代的 Java 6,還不快升級,??,

最近在做 Java8 到 Java17 的遷移作業,前期做了一些準備,程序中的一些資訊記錄如下(持續更新,,,)

分為幾個部分:

  • 編譯相關
  • 引數遷移相關
  • 運行相關

編譯相關

JEP 320

在 Java11 中引入了一個提案 JEP 320: Remove the Java EE and CORBA Modules 提案,移除了 Java EE and CORBA 的模塊,如果專案中用到需要手動引入,比如代碼中用到了 javax.annotation.* 下的包:

import javax.annotation.PreDestroy;
public abstract class FridayAgent
    @PreDestroy
    public void destroy() {
        agentClient.close();
    }
}

在編譯時會找不到相關的類,這是因為 Java EE 已經在 Java 9 中被標記為 deprecated,Java 11 中被正式移除,可以手動引入 javax 的包:

<dependency>
    <groupId>javax.annotation</groupId>
    <artifactId>javax.annotation-api</artifactId>
    <version>1.3.2</version>
</dependency>

使用了 sun.misc.* 下的包

比如 sun.misc.BASE64Encoder,這個簡單,替換一下工具類即可,

[ERROR]   symbol:   class BASE64Encoder
[ERROR]   location: package sun.misc

netty 低版本使用了 sun.misc.*,編譯錯誤資訊如下

Caused by: java.lang.NoClassDefFoundError: Could not initialize class io.netty.util.internal.PlatformDependent0
        at io.netty.util.internal.PlatformDependent.getSystemClassLoader(PlatformDependent.java:694) ~[netty-all-4.0.42.Final.jar!/:4.0.42.Final]

對應的原始碼如下:

/**
 * The {@link PlatformDependent} operations which requires access to {@code sun.misc.*}.
 */
final class PlatformDependent0 {
}

https://github.com/netty/netty/issues/6855

lombok 使用了 com.sun.tools.javac.* 下的包

錯誤資訊如下:

Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.2:compile (default-compile) on project encloud-common: Fatal error compiling: java.lang.ExceptionInInitializerError: Unable to make field private com.sun.tools.javac.processing.JavacProcessingEnvironment$DiscoveredProcessors com.sun.tools.javac.processing.JavacProcessingEnvironment.discoveredProcs accessible: module jdk.compiler does not "opens com.sun.tools.javac.processing" to unnamed module

如果你的專案中使用 lombok,而且是低版本的話,就會出現,lombok 的原理是在編譯期做一些手腳,用到了 com.sun.tools.javac 下的檔案,升級到最新版可以解決,ps,個人很不喜歡 lombok, 除錯的時候代碼和 class 對不上真的很惡心,

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
   <!-- <version>1.16.4</version>-->
    <version>1.18.24</version>
</dependency>

kotlin 版本限制

我們后端在很多年前就 all-in Kotlin,Kotlin 的升級也是我們的重中之重,

[ERROR] Failed to execute goal org.jetbrains.kotlin:kotlin-maven-plugin:1.2.71:compile (compile) on project encloud-core: Compilation failure [ERROR] Unknown JVM target version: 17 [ERROR] Supported versions: 1.6, 1.8

Kotlin 在 1.6.0 版本開始支持 Java17 的位元組碼,低于 1.6.0 的編譯會直接報錯

廢棄依賴分析

可以用 jdeps --jdk-internals --multi-release 17 --class-path . encloud-api.jar 來做專案的依賴分析

這樣你就可以知道哪些庫需要做升級了,

推薦一個開源免費的 Spring Boot 最全教程:

https://github.com/javastacks/spring-boot-best-practice

引數遷移

什么是 Unified Logging

在 Java 領域,有廣為人知的日志框架,slf4j、log4j 等,這些框架提供了統一的編程介面,讓用戶可以通過簡單的配置實作日志輸出的個性化配置,比如日志 tag、級別(info、debug 等)、背景關系(執行緒 id、行號、時間等),在 JVM 內部之前一直缺乏這樣的規范,于是出來了 Unified Logging,實作了日志格式的大一統,這就是我們接下來要介紹的重點 Unified Logging

我們接觸最多的是 gc 的日志,在 java8 中,我們配置 gc 日志的引數是 -Xloggc:/tmp/gc.log,在 JVM 中除了 GC,還有大量的其它相關的日志,比如執行緒、os 等,在新的 Unified Logging 日志中,日志輸出的方式變更為了 java -Xlog:xxx,GC 不再特殊只是做為日志的一種存在形式,

java -Xlog -version

輸出結果如下:

可以看到日志輸出里,不僅有 GC 相關的日志,還有 os 執行緒相關的資訊,事實上 java 的日志的生產者有非常多部分,比如 thread、class load、unload、safepoint、cds 等,

歸根到底,日志列印,需要回答清楚三個問題:

  • what:要輸出什么資訊(tag),以什么日志級別輸出(level)
  • where:輸出到哪里(console 還是 file)
  • decorators:日志如何

輸出什么資訊(selectors)

首先來看 what 的部分,如何指定要輸出哪些資訊,這個在 JVM 內部被稱之為 selectors,

JVM 采用的是 <tag-set>=<level>的形式來表示 selectors,默認情況下,tag 為all,表示所有的 tag,level 為 INFOjava -Xlog -version 等價于下面的形式

java -Xlog:all=info -version

如果我們想輸出tag 為 gc,日志級別為 debug 的日志,可以用 java -Xlog:gc=debug 的形式:

$ java -Xlog:gc=debug -version
[0.023s][info][gc] Using G1
[0.023s][debug][gc] ConcGCThreads: 3 offset 22
[0.023s][debug][gc] ParallelGCThreads: 10
[0.024s][debug][gc] Initialize mark stack with 4096 chunks, maximum 524288

這樣就輸出了 tag 為 gc,級別為 debug 的日志資訊,

不過這里有一個比較坑的點是,這里的 tag 匹配規則是精確匹配,如果某條日志的 tag 是 gc,metaspace,通過上面的規則是匹配不到的,我們可以手動指定的方式來輸出,

$ java -Xlog:gc+metaspace -version

[0.022s][info][gc,metaspace] CDS archive(s) mapped at: ... size 12443648.
[0.022s][info][gc,metaspace] Compressed class space mapped at: reserved size:...
[0.022s][info][gc,metaspace] Narrow klass base:..., Narrow
klass shift: 0, Narrow klass range: 0x100000000

這里的 selector 也是可以進行組合的,不同的 selector 之間用逗號分隔即可,比如同時輸出 gcgc+metaspace 這兩類 tag 的日志,就可以這么寫:

$ java -Xlog:gc=debug,gc+metaspace -version

[0.020s][info][gc] Using G1
[0.020s][debug][gc] ConcGCThreads: 3 offset 22
[0.020s][debug][gc] ParallelGCThreads: 10
[0.020s][debug][gc] Initialize mark stack with 4096 chunks, maximum 524288
[0.022s][info ][gc,metaspace] CDS archive(s) mapped at:
[0.022s][info ][gc,metaspace] Compressed class space mapped at:
[0.022s][info ][gc,metaspace] Narrow klass base: 0x0000000800000000

當然這么搞是很麻煩的,JVM 提供了通配符 * 來解決精確匹配的問題,比如我們想要所有 tag 為 gc 的日志,可以這么寫:

$ java -Xlog:gc*=debug -version

[0.024s][debug][gc,heap] Minimum heap 8388608
[0.024s][info ][gc     ] Using G1
[0.024s][debug][gc,heap,coops] Heap address: 0x0000000707400000
[0.024s][debug][gc           ] ConcGCThreads: 3 offset 22
[0.024s][debug][gc           ] ParallelGCThreads: 10
[0.024s][debug][gc           ] Initialize mark stack with 4096 chunks
[0.024s][debug][gc,ergo,heap ] Expand the heap. requested expansion amount:
[0.025s][debug][gc,heap,region] Activate regions [0, 125)[0.025s][debug][gc,ihop       ] Target occupancy update: old: 0B, new: 262144000B
[0.025s][debug][gc,ergo,refine] Initial Refinement Zones: green: 2560
[0.026s][debug][gc,task       ] G1 Service Thread
[0.026s][debug][gc,task       ] G1 Service Thread (Periodic GC Task) (register)
[0.026s][info ][gc,init       ] Version: 17.0.3+7 (release)
...

如果只想要 INFO 級別的日志,則可以省略 level 的設定,使用 java -Xlog:gc* -version 即可,

如果想知道有哪些個性化的 tag 可以選擇,可以用 java -Xlog:help 來找到所有可用的 tag,

階段性小結

第二部分:輸出到哪里(output)

默認情況下,日志會輸出到 stdout,jvm 支持以下三種輸出方式:

  • stdout
  • stderr
  • file

一般而言我們會把日志輸出到檔案中,方便后續進一步分析

-Xlog:all=debug:file=/path_to_logs/app.log

還可以指定日志切割的大小和方式

-Xlog:gc*:file=/path_to_logs/app.log:filesize=104857600,filecount=5

第三部分:日志 decorators

每條日志除了正常的資訊以外,還有不少日志相關的背景關系資訊,在 jvm 中被稱為 decorators,有下面這些可選項,

Option Description
time Current time and date in ISO-8601 format.
uptime Time since the start of the JVM in seconds and milliseconds (e.g., 6.567s).
timemillis The same value as generated by System.currentTimeMillis().
uptimemillis Milliseconds since the JVM started.
timenanos The same value as generated by System.nanoTime().
uptimenanos Nanoseconds since the JVM started.
pid The process identifier.
tid The thread identifier.
level The level associated with the log message.
tags The tag-set associated with the log message.

比如可以用 java -Xlog:all=debug:stdout:level,tags,time,uptime,pid -version 選項來列印日志,

[2022-06-15T19:54:01.529+0800][0.001s][5235][info ][os,thread] Thread attached
[2022-06-15T19:54:01.529+0800][0.001s][5235][debug][os,thread] Thread 5237 stack...
[2022-06-15T19:54:01.529+0800][0.001s][5235][debug][perf,datacreation]

Unified Logging 小結

輸出格式如下:

-Xlog:[selectors]:[output]:[decorators][:output-options]
  • selectors 是多個 tag 和 level 的組合,起到了 what(過濾器)的作用,格式為 tag1[+tag2...][*][=level][,...]
  • decorators 是日志相關的描述資訊,也可以理解為背景關系
  • output 是輸出相關的選項,一般我們會配置為輸出到檔案,按檔案大小切割

這里補充一個知識點,就是默認值:

  • tag:all
  • level:info
  • output:stdout
  • decorators: uptime, level, tags

GC 引數遷移

可以看到 GC 相關的引數都已經收攏到 Xlog 下,以前的很多 Java8 下的引數已經被移除或者標記為過期,

比如 PrintGCDetails 已經被 -Xlog:gc* 取代:

java -XX:+PrintGCDetails -version

[0.001s][warning][gc] -XX:+PrintGCDetails is deprecated. Will use -Xlog:gc* instead.

常見的標記為廢棄的引數還有 -XX:+PrintGC-Xloggc:<filepath>,遷移前后的引數如下:

舊引數 新引數
-XX:+PrintGCDetails -Xlog:gc*
-XX:+PrintGC -Xlog:gc
-Xloggc:<filepath> -Xlog:gc:file=<filepath>

除此之外,大量的 GC 的引數被移除,比如常用的引數 -XX:+PrintTenuringDistribution,Java17 會拒絕啟動

java -XX:+PrintTenuringDistribution -version
Unrecognized VM option 'PrintTenuringDistribution'
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.

更詳細的移除的引數如下

CMSDumpAtPromotionFailure,
CMSPrintEdenSurvivorChunks,
GlLogLevel,
G1PrintHeapRegions,
G1PrintRegionLivenessInfo,
G1SummarizeConcMark,
G1SummarizeRSetStats,
G1TraceConcRefinement,
G1TraceEagerReclaimHumongousObjects,
G1TraceStringSymbolTableScrubbing,
GCLogFileSize, NumberofGCLogFiles,
PrintAdaptiveSizePolicy,
PrintclassHistogramAfterFullGC,
PrintClassHistogramBeforeFullGC,
PrintCMSInitiationStatistics
PrintCMSStatistics,
PrintFLSCensus,
PrintFLSStatistics,
PrintGCApplicationConcurrentTime
PrintGCApplicationStoppedTime,
PrintGCCause,
PrintGCDateStamps,
PrintGCID,
PrintGCTaskTimeStamps,
PrintGCTimeStamps,
PrintHeapAtGC,
PrintHeapAtGCExtended,
PrintJNIGCStalls,
PrintOldPLAB
PrintParallel0ldGCPhaseTimes,
PrintPLAB,
PrintPromotionFailure,
PrintReferenceGC,
PrintStringDeduplicationStatistics,
PrintTaskqueue,
PrintTenuringDistribution,
PrintTerminationStats,
PrintTLAB,
TraceDynamicGCThreads,
TraceMetadataHumongousAllocation,
UseGCLogFileRotation,
VerifySilently

這些移除的引數大部分都能在新的日志體系下找到對應的引數,比如 PrintHeapAtGC 這個引數可以用 -Xlog:gc+heap=debug 來替代

$ java -Xlog:gc+heap=debug -cp . G1GCDemo01

[0.004s][debug][gc,heap] Minimum heap 8388608  Initial heap 268435456  Maximum heap
hello, g1gc!
[12.263s][debug][gc,heap] GC(0) Heap before GC invocations=0 (full 0):
[12.265s][debug][gc,heap] GC(0)  garbage-first heap
[12.265s][debug][gc,heap] GC(0)   region size 2048K, 1 young (2048K)
[12.265s][debug][gc,heap] GC(0)  Metaspace       used 3678K
[12.265s][debug][gc,heap] GC(0)   class space    used 300K
[12.280s][debug][gc,heap] GC(0) Uncommittable regions after shrink: 124

雖然理解起來不太直觀,不過要記住 -XX:+PrintGCApplicationStoppedTime-XX+PrintGCApplicationConcurrentTime 這兩個引數一起被 -Xlog:safepoint 取代,

還有一個常見的引數 -XX:+PrintAdaptiveSizePolicy-Xlog:gc+ergo*=trace 取代,

[0.122s][debug][gc, ergo, refine] Initial Refinement Zones: green: 23, yellow:
69, red: 115, min yellow size: 46
[0.142s ][debug][gc, ergo, heap ] Expand the heap. requested expansion amount: 268435456B expansion amount: 268435456B
[2.475s][trace][gc, ergo, cset] GC(0) Start choosing CSet. pending cards: 0 predicted base time: 10.00ms remaining time:
190.00ms target pause time: 200.00ms
[2.476s][trace][gc, ergo, cset ] GC(9) Add young regions to CSet. eden: 24 regions, survivors: 0 regions, predicted young
region time: 367.19ms, target pause time: 200.00ms
[2.476s ][debug][gc, ergo, cset ] GC(0) Finish choosing CSet. old: 0 regions, predicted old region time: 0.00ms, time
remaining: 0.00
[2.826s][debug][gc, ergo] GC(0) Running G1 Clear Card Table Task using 1 workers for 1 units of work for 24 regions.
[2.827s][debug][gc, ergo] GC (0) Running G1 Free Collection Set using 1 workers for collection set length 24
[2.828s][trace][gc, ergo, refine] GC(0) Updating Refinement Zones: update rs time: 0.004ms, update rs buffers: 0, update rs
goal time: 19.999ms
[2.829s][debug][gc, ergo, refine] GC(0) Updated Refinement Zones: green: 23, yellow: 69, red: 115
[3.045s][trace][gc, ergo, set ] GC(1) Start choosing CSet. pending cards: 5898 predicted base time: 26.69ms remaining
time: 173.31ms target pause time: 200.00ms
[3.045s][trace][gc, ergo, cset ] GC(1) Add young regions to Set. eden: 9 regions, survivors: 3 regions, predicted young
region time: 457.38ms, target pause time: 200.00ms
[3.045s][debug](gc, ergo, set ] GC(1) Finish choosing CSet. old: @ regions, predicted old region time: 0.00ms, time
remaining: 0.00
[3.090s ][debug][gc, ergo
] GC (1) Running G1 Clear Card Table Task using 1 workers for 1 units of work for 12 regions.
[3.091s][debug][gc, ergo
GC (1) Running G1 Free Collection Set using 1 workers for collection set length 12
[3.093s][trace][gc, ergo, refine] GC(1) Updating Refinement Zones: update rs time: 2.510ms, update rs buffers: 25, update rs
goal time: 19.999ms
[3.093s ][debug][gc, ergo, refine] GC(1) Updated Refinement Zones: green: 25, yellow: 75, red: 125

看一下這部分的原始碼的變遷,就可以知道確實是如此了,在 Java8 中,PSYoungGen::resize_spaces代碼如下:

在 Java17 中,這部分日志列印被 gc+ergo 的標簽日志取代:

還有一個分代 GC 中非常有用的引數 -XX:+PrintTenuringDistribution,現在被 gc+age=trace 取代

完整的引數變遷對應表如下:

舊 GC 引數 -XX:+… 對應新 GC 引數 GC 引數含義
PrintGC -Xloggc: gc Print message at garbage collection
PrintGCDetails -Xloggc: gc* Print more details at garbage collection
-verbose:gc gc=trace gc+heap=trace gc+heap+exit=trace gc+metaspace=trace gc+sweep=debug gc+heap+ergo=debug Verbose GC
PrintGCCause GC cause is now always logged Include GC cause in GC logging
PrintGCID GC ID is now always logged Print an identifier for each garbage collection
PrintGCApplicationStoppedTime safepoint Print the time the application has been stopped
PrintGCApplicationConcurrentTime safepoint Print the time the application has been running
PrintTenuringDistribution gc+age*=trace Print tenuring age information
PrintAdaptiveSizePolicy gc+ergo*=trace Print information about AdaptiveSizePolicy
PrintHeapAtGC gc+heap=debug Print heap layout before and after each GC
PrintHeapAtGCExtended gc+heap=trace Print extended information about the layout of the heap when -XX:+PrintHeapAtGC is set
PrintClassHistogramBeforeFullGC classhisto*=trace Print a class histogram before any major stop-world GC
PrintClassHistogramAfterFullGC classhisto*=trace Print a class histogram after any major stop-world GC
PrintStringDeduplicationStatistics gc+stringdedup*=debug Print string deduplication statistics
PrintJNIGCStalls gc+jni=debug Print diagnostic message when GC is stalled by JNI critical section
PrintReferenceGC gc+ref=debug Print times spent handling reference objects during GC
PrintGCTaskTimeStamps task*=debug Print timestamps for individual gc worker thread tasks
PrintTaskQueue gc+task+stats=trace Print taskqueue statistics for parallel collectors
PrintPLAB gc+plab=trace Print (survivor space) promotion LAB’s sizing decisions
PrintOldPLAB gc+plab=trace Print (old gen) promotion LAB’s sizing decisions
PrintPromotionFailure gc+promotion=debug Print additional diagnostic information following promotion failure
PrintTLAB gc+tlab=trace Print various TLAB related information (augmented with -XX:+TLABStats)
PrintTerminationStats gc+task+stats=debug Print termination statistics for parallel collectors
G1PrintHeapRegions gc+region=trace If set G1 will print information on which regions are being allocated and which are reclaimed
G1PrintRegionsLivenessInfo gc+liveness=trace Prints the liveness information for all regions in the heap at the end of a marking cycle
G1SummarizeConcMark gc+marking=trace Summarize concurrent mark info
G1SummarizeRSets gc+remset*=trace Summarize remembered set processing info
G1TraceConcRefinement gc+refine=debug Trace G1 concurrent refinement
G1TraceEagerReclaimHumongousObjects gc+humongous=debug Print some information about large object liveness at every young GC
G1TraceStringSymbolTableScrubbing gc+stringdedup=trace Trace information string and symbol table scrubbing
PrintParallelOldGCPhaseTimes gc+phases=trace Print the time taken by each phase in ParallelOldGC
CMSDumpAtPromotionFailure gc+promotion=trace Dump useful information about the state of the CMS old generation upon a promotion failure (complemented by flags CMSPrintChunksInDump or CMSPrintObjectsInDump)
CMSPrintEdenSurvivorChunks gc+heap=trace Print the eden and the survivor chunks used for the parallel initial mark or remark of the eden/survivor spaces
PrintCMSInitiationStatistics gc=trace Statistics for initiating a CMS collection
PrintCMSStatistics gc=debug (trace) gc+task=trace gc+survivor=trace log+sweep=debug (trace) Statistics for CMS (complemented by CMSVerifyReturnedBytes)
PrintFLSCensus gc+freelist+census=debug Census for CMS' FreeListSpace
PrintFLSStatistics gc+freelist+stats=debug (trace) gc+freelist*=debug (trace) Statistics for CMS' FreeListSpace
TraceCMSState gc+state=debug Trace the state of the CMS collection
TraceSafepoint safepoint=debug Trace application pauses due to VM operations in safepoints
TraceSafepointCleanupTime safepoint+cleanup=info break down of clean up tasks performed during safepoint
TraceAdaptativeGCBoundary heap+ergo=debug Trace young-old boundary moves
TraceDynamicGCThreads gc+task=trace Trace the dynamic GC thread usage
TraceMetadataHumongousAllocation gc+metaspace+alloc=debug Trace humongous metadata allocations
VerifySilently gc+verify=debug

舉例

-XX:+PrintGCDetails                           \  // gc*
-XX:+PrintGCApplicationStoppedTime            \  // safepoint
-XX:+PrintGCApplicationConcurrentTime         \  // safepoint
-XX:+PrintGCCause                             \  // 默認會輸出
-XX:+PrintGCID                                \  // 默認會輸出
-XX:+PrintTenuringDistribution                \  // gc+age*=trace
-XX:+PrintGCDateStamps                        \  // :time,tags,level
-XX:+UseGCLogFileRotation                     \  // :filecount=5,filesize=10M
-XX:NumberOfGCLogFiles=5                      \  // :filecount=5,filesize=10M
-XX:GCLogFileSize=10M                         \  // :filecount=5,filesize=10M
-Xloggc:/var/log/`date +%FT%H-%M-%S`-gc.log   \  // -Xlog::file=/var/log/%t-gc.log

變遷后:

-Xlog:
  gc*,
  safepoint,
  gc+heap=debug,
  gc+ergo*=trace,
  gc+age*=trace,
  :file=/var/log/%t-gc.log
  :time,tags,level
  :filecount=5,filesize=10M

推薦的配置

-Xlog:
		// selections
    codecache+sweep*=trace,
    class+unload,                      // TraceClassUnloading
    class+load,                        // TraceClassLoading
    os+thread,
    safepoint,                        // TraceSafepoint
    gc*,                              // PrintGCDetails
    gc+stringdedup=debug,             // PrintStringDeduplicationStatistics
    gc+ergo*=trace,
    gc+age=trace,                     // PrintTenuringDistribution
    gc+phases=trace,
    gc+humongous=trace,
    jit+compilation=debug
// output
:file=/path_to_logs/app.log
// decorators
:level,tags,time,uptime,pid
// output-options
:filesize=104857600,filecount=5

運行相關

反射+私有 API 呼叫之傷

在 Java8 中,沒有人能阻止你訪問特定的包,比如 sun.misc,對反射也沒有限制,只要 setAccessible(true) 就可以了,Java9 模塊化以后,一切都變了,只能通過 --add-exports--add-opens 來打破模塊封裝

  • --add-opens 匯出特定的包
  • --add-opens 允許模塊中特定包的類路徑深度反射訪問

比如:

--add-opens java.base/java.lang=ALL-UNNAMED
--add-opens java.base/java.io=ALL-UNNAMED
--add-opens java.base/java.math=ALL-UNNAMED
--add-opens java.base/java.net=ALL-UNNAMED
--add-opens java.base/java.nio=ALL-UNNAMED
--add-opens java.base/java.security=ALL-UNNAMED
--add-opens java.base/java.text=ALL-UNNAMED
--add-opens java.base/java.time=ALL-UNNAMED
--add-opens java.base/java.util=ALL-UNNAMED
--add-opens java.base/jdk.internal.access=ALL-UNNAMED
--add-opens java.base/jdk.internal.misc=ALL-UNNAMED

關于 GC 演算法的選擇

CMS 正式退出歷史舞臺,G1 正式接棒,ZGC 蓄勢待發,在GC 演算法的選擇上,目前來看 G1 還是最佳的選擇,ZGC 因為有記憶體占用被 OS 標記過高(三倍共享記憶體)虛高的問題,行程可能被 OOM-killer 殺掉,

ZGC 三倍 RES 記憶體

ZGC 底層用到了一個稱之為染色指標的技術,使用三個視圖(Marked0、Marked1 和 Remapped)來映射到同一塊共享記憶體區域,原理如下:

#include <iostream>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <cstdio>
#include <cstdlib>

int main() {
    // shm_open()函式用來打開或者創建一個共享記憶體區,兩個行程可以通過給shm_open()函式傳遞相同的名字以達到操作同一共享記憶體的目的
    int fd = ::shm_open("/test", O_RDWR | O_CREAT | O_EXCL, 0600);
    if (fd < 0) {
        shm_unlink("/test");
        perror("shm open failed");
        return 0;
    }

    size_t size = 1 * 1024 * 1024 * 1024;
    // 創建一個共享記憶體后,默認大小為0,所以需要設定共享記憶體大小,ftruncate()函式可用來調整檔案或者共享記憶體的大小
    ::ftruncate(fd, size);
    int prot = PROT_READ | PROT_WRITE;
    // 創建共享記憶體后,需要將共享記憶體映射到呼叫行程的地址空間,可通過mmap()函式來完成
    uint32_t *p1 = (uint32_t *) (mmap(nullptr, size, prot, MAP_SHARED, fd, 0));
    uint32_t *p2 = (uint32_t *) (mmap(nullptr, size, prot, MAP_SHARED, fd, 0));
    uint32_t *p3 = (uint32_t *) (mmap(nullptr, size, prot, MAP_SHARED, fd, 0));
    ::close(fd);
    *p1 = 0xcafebabe;
    ::printf("Address of addr1: %p, value is 0x%x\n", p1, *p1);
    ::printf("Address of addr2: %p, value is 0x%x\n", p2, *p2);
    ::printf("Address of addr3: %p, value is 0x%x\n", p3, *p3);
    ::getchar();
    *p2 = 0xcafebaba;
    ::printf("Address of addr1: %p, value is 0x%x\n", p1, *p1);
    ::printf("Address of addr2: %p, value is 0x%x\n", p2, *p2);
    ::printf("Address of addr3: %p, value is 0x%x\n", p3, *p3);
    ::getchar();
    munmap(p1, size);
    munmap(p2, size);
    munmap(p3, size);
    shm_unlink("/test");
    std::cout << "hello" << std::endl;
}

你可以想象 p1、p2、p3 這三塊記憶體區域就是 ZGC 中三種視圖,

但是在 linux 統計中,雖然是共享記憶體,但是依然會統計三次,比如 RES,

同一個應用,使用 G1 RES 顯示占用 2G,ZGC 則顯示占用 6G

java -XX:+AlwaysPreTouch -Xms2G -Xmx2G -XX:+UseZGC MyTest
java -XX:+AlwaysPreTouch -Xms2G -Xmx2G -XX:+UseG1GC MyTest

接下面我們討論的都是 G1 相關的,

G1 引數調整

不要配置新生代的大小

這個在《JVM G1 原始碼分析和調優》一書里有詳細的介紹,有兩個主要的原因:

  • G1對記憶體的管理是不連續的,重新分配一個磁區代價很低
  • G1 的需要根據目標停頓時間動態調整搜集的磁區的個數,如果不能調整新生代的大小,那么 G1 可能不能滿足停頓時間的要求

諸如 -Xmn, -XX:NewSize, -XX:MaxNewSize, -XX:SurvivorRatio 都不要在 G1 中出現,只需要控制最大、最小堆和目標暫停時間即可

調整 -XX:InitiatingHeapOccupancyPercent 到合適的值

IHOP 默認值為 45,這個值是啟動并發標記的先決條件,只有當老年代記憶體堆疊總空間的 45% 之后才會啟動并發標記任務,

增加這個值:導致并發標記可能花費更多的時間,同時導致 YGC 和 Mixed-GC 收集時的磁區數變少,可以根據整體應用占用的平均記憶體來設定,

近期熱文推薦:

1.1,000+ 道 Java面試題及答案整理(2022最新版)

2.勁爆!Java 協程要來了,,,

3.Spring Boot 2.x 教程,太全了!

4.別再寫滿屏的爆爆爆炸類了,試試裝飾器模式,這才是優雅的方式!!

5.《Java開發手冊(嵩山版)》最新發布,速速下載!

覺得不錯,別忘了隨手點贊+轉發哦!

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/534076.html

標籤:Java

上一篇:每日演算法題之構建乘積陣列

下一篇:this和super關鍵字

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 【C++】Microsoft C++、C 和匯編程式檔案

    ......

    uj5u.com 2020-09-10 00:57:23 more
  • 例外宣告

    相比于斷言適用于排除邏輯上不可能存在的狀態,例外通常是用于邏輯上可能發生的錯誤。 例外宣告 Item 1:當函式不可能拋出例外或不能接受拋出例外時,使用noexcept 理由 如果不打算拋出例外的話,程式就會認為無法處理這種錯誤,并且應當盡早終止,如此可以有效地阻止例外的傳播與擴散。 示例 //不可 ......

    uj5u.com 2020-09-10 00:57:27 more
  • Codeforces 1400E Clear the Multiset(貪心 + 分治)

    鏈接:https://codeforces.com/problemset/problem/1400/E 來源:Codeforces 思路:給你一個陣列,現在你可以進行兩種操作,操作1:將一段沒有 0 的區間進行減一的操作,操作2:將 i 位置上的元素歸零。最終問:將這個陣列的全部元素歸零后操作的最少 ......

    uj5u.com 2020-09-10 00:57:30 more
  • UVA11610 【Reverse Prime】

    本人看到此題沒有翻譯,就附帶了一個自己的翻譯版本 思考 這一題,它的第一個要求是找出所有 $7$ 位反向質數及其質因數的個數。 我們應該需要質數篩篩選1~$10^{7}$的所有數,這里就不慢慢介紹了。但是,重讀題,我們突然發現反向質數都是 $7$ 位,而將它反過來后的數字卻是 $6$ 位數,這就說明 ......

    uj5u.com 2020-09-10 00:57:36 more
  • 統計區間素數數量

    1 #pragma GCC optimize(2) 2 #include <bits/stdc++.h> 3 using namespace std; 4 bool isprime[1000000010]; 5 vector<int> prime; 6 inline int getlist(int ......

    uj5u.com 2020-09-10 00:57:47 more
  • C/C++編程筆記:C++中的 const 變數詳解,教你正確認識const用法

    1、C中的const 1、區域const變數存放在堆疊區中,會分配記憶體(也就是說可以通過地址間接修改變數的值)。測驗代碼如下: 運行結果: 2、全域const變數存放在只讀資料段(不能通過地址修改,會發生寫入錯誤), 默認為外部聯編,可以給其他源檔案使用(需要用extern關鍵字修飾) 運行結果: ......

    uj5u.com 2020-09-10 00:58:04 more
  • 【C++犯錯記錄】VS2019 MFC添加資源不懂如何修改資源宏ID

    1. 首先在資源視圖中,添加資源 2. 點擊新添加的資源,復制自動生成的ID 3. 在解決方案資源管理器中找到Resource.h檔案,編輯,使用整個專案搜索和替換的方式快速替換 宏宣告 4. Ctrl+Shift+F 全域搜索,點擊查找全部,然后逐個替換 5. 為什么使用搜索替換而不使用屬性視窗直 ......

    uj5u.com 2020-09-10 00:59:11 more
  • 【C++犯錯記錄】VS2019 MFC不懂的批量添加資源

    1. 打開資源頭檔案Resource.h,在其中預先定義好宏 ID(不清楚其實ID值應該設定多少,可以先新建一個相同的資源項,再在這個資源的ID值的基礎上遞增即可) 2. 在資源視圖中選中專案資源,按F7編輯資源檔案,按 ID 型別 相對路徑的形式添加 資源。(別忘了先把檔案拷貝到專案中的res檔案 ......

    uj5u.com 2020-09-10 01:00:19 more
  • C/C++編程筆記:關于C++的參考型別,專供新手入門使用

    今天要講的是C++中我最喜歡的一個用法——參考,也叫別名。 參考就是給一個變數名取一個變數名,方便我們間接地使用這個變數。我們可以給一個變數創建N個參考,這N + 1個變數共享了同一塊記憶體區域。(參考型別的變數會占用記憶體空間,占用的記憶體空間的大小和指標型別的大小是相同的。雖然參考是一個物件的別名,但 ......

    uj5u.com 2020-09-10 01:00:22 more
  • 【C/C++編程筆記】從頭開始學習C ++:初學者完整指南

    眾所周知,C ++的學習曲線陡峭,但是花時間學習這種語言將為您的職業帶來奇跡,并使您與其他開發人員區分開。您會更輕松地學習新語言,形成真正的解決問題的技能,并在編程的基礎上打下堅實的基礎。 C ++將幫助您養成良好的編程習慣(即清晰一致的編碼風格,在撰寫代碼時注釋代碼,并限制類內部的可見性),并且由 ......

    uj5u.com 2020-09-10 01:00:41 more
最新发布
  • Rust中的智能指標:Box<T> Rc<T> Arc<T> Cell<T> RefCell<T> Weak

    Rust中的智能指標是什么 智能指標(smart pointers)是一類資料結構,是擁有資料所有權和額外功能的指標。是指標的進一步發展 指標(pointer)是一個包含記憶體地址的變數的通用概念。這個地址參考,或 ” 指向”(points at)一些其 他資料 。參考以 & 符號為標志并借用了他們所 ......

    uj5u.com 2023-04-20 07:24:10 more
  • Java的值傳遞和參考傳遞

    值傳遞不會改變本身,參考傳遞(如果傳遞的值需要實體化到堆里)如果發生修改了會改變本身。 1.基本資料型別都是值傳遞 package com.example.basic; public class Test { public static void main(String[] args) { int ......

    uj5u.com 2023-04-20 07:24:04 more
  • [2]SpinalHDL教程——Scala簡單入門

    第一個 Scala 程式 shell里面輸入 $ scala scala> 1 + 1 res0: Int = 2 scala> println("Hello World!") Hello World! 檔案形式 object HelloWorld { /* 這是我的第一個 Scala 程式 * 以 ......

    uj5u.com 2023-04-20 07:23:58 more
  • 理解函式指標和回呼函式

    理解 函式指標 指向函式的指標。比如: 理解函式指標的偽代碼 void (*p)(int type, char *data); // 定義一個函式指標p void func(int type, char *data); // 宣告一個函式func p = func; // 將指標p指向函式func ......

    uj5u.com 2023-04-20 07:23:52 more
  • Django筆記二十五之資料庫函式之日期函式

    本文首發于公眾號:Hunter后端 原文鏈接:Django筆記二十五之資料庫函式之日期函式 日期函式主要介紹兩個大類,Extract() 和 Trunc() Extract() 函式作用是提取日期,比如我們可以提取一個日期欄位的年份,月份,日等資料 Trunc() 的作用則是截取,比如 2022-0 ......

    uj5u.com 2023-04-20 07:23:45 more
  • 一天吃透JVM面試八股文

    什么是JVM? JVM,全稱Java Virtual Machine(Java虛擬機),是通過在實際的計算機上仿真模擬各種計算機功能來實作的。由一套位元組碼指令集、一組暫存器、一個堆疊、一個垃圾回收堆和一個存盤方法域等組成。JVM屏蔽了與作業系統平臺相關的資訊,使得Java程式只需要生成在Java虛擬機 ......

    uj5u.com 2023-04-20 07:23:31 more
  • 使用Java接入小程式訂閱訊息!

    更新完微信服務號的模板訊息之后,我又趕緊把微信小程式的訂閱訊息給實作了!之前我一直以為微信小程式也是要企業才能申請,沒想到小程式個人就能申請。 訊息推送平臺🔥推送下發【郵件】【短信】【微信服務號】【微信小程式】【企業微信】【釘釘】等訊息型別。 https://gitee.com/zhongfuch ......

    uj5u.com 2023-04-20 07:22:59 more
  • java -- 緩沖流、轉換流、序列化流

    緩沖流 緩沖流, 也叫高效流, 按照資料型別分類: 位元組緩沖流:BufferedInputStream,BufferedOutputStream 字符緩沖流:BufferedReader,BufferedWriter 緩沖流的基本原理,是在創建流物件時,會創建一個內置的默認大小的緩沖區陣列,通過緩沖 ......

    uj5u.com 2023-04-20 07:22:49 more
  • Java-SpringBoot-Range請求頭設定實作視頻分段傳輸

    老實說,人太懶了,現在基本都不喜歡寫筆記了,但是網上有關Range請求頭的文章都太水了 下面是抄的一段StackOverflow的代碼...自己大修改過的,寫的注釋挺全的,應該直接看得懂,就不解釋了 寫的不好...只是希望能給視頻網站開發的新手一點點幫助吧. 業務場景:視頻分段傳輸、視頻多段傳輸(理 ......

    uj5u.com 2023-04-20 07:22:42 more
  • Windows 10開發教程_編程入門自學教程_菜鳥教程-免費教程分享

    教程簡介 Windows 10開發入門教程 - 從簡單的步驟了解Windows 10開發,從基本到高級概念,包括簡介,UWP,第一個應用程式,商店,XAML控制元件,資料系結,XAML性能,自適應設計,自適應UI,自適應代碼,檔案管理,SQLite資料庫,應用程式到應用程式通信,應用程式本地化,應用程式 ......

    uj5u.com 2023-04-20 07:22:35 more