本文來自于HeapDump性能社區(qū)! !有性能問題,上HeapDump性能社區(qū)!
1.永遠不要忽略InterruptedException
讓我們檢查以下代碼片段:
public class Task implements Runnable {
private final BlockingQueue<String> queue = ...;
@Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
String result = getOrDefault(() -> queue.poll(1L, TimeUnit.MINUTES), "default");
//do smth with the result
}
}
<T> T getOrDefault(Callable<T> supplier, T defaultValue) {
try {
return supplier.call();
} catch (Exception e) {
logger.error("Got exception while retrieving value.", e);
return defaultValue;
}
}
}
代碼的問題是不可能終止線程,因為它正在等待隊列中的新元素,所以中斷標志永遠不會恢復:
正在運行代碼的線程被中斷。
BlockingQueue#poll() 拋出 InterruptedException 并清除中斷標志。
當標志被清除時, while 循環(huán)條件 ( !Thread.currentThread().isInterrupted()) 為ture。
為防止這種行為,請始終讀取 InterruptedException 并在方法顯式(通過聲明 throwing InterruptedException)或隱式(通過聲明/拋出原始 Exception)拋出時恢復中斷標志:
<T> T getOrDefault(Callable<T> supplier, T defaultValue) {
try {
return supplier.call();
} catch (InterruptedException e) {
logger.error("Got interrupted while retrieving value.", e);
Thread.currentThread().interrupt();
return defaultValue;
} catch (Exception e) {
logger.error("Got exception while retrieving value.", e);
return defaultValue;
}
}
2. 注意使用專用的執(zhí)行器進行阻塞操作
開發(fā)人員通常不希望因為一個“慢動作”而使整個服務器無響應。不幸的是,對于 RPC,響應時間通常是不可預測的。
假設一臺服務器有 100 個工作線程,并且有一個端點,它以 100 RPS 調用。它在內部進行 RPC 調用,通常需要 10 毫秒。在某個時間點,這個 RPC 的響應時間變成了 2 秒,而服務器在尖峰期間唯一能做的就是等待這些調用,而其他端點根本無法訪問。
@GET
@Path("/genre/{name}")
@Produces(MediaType.APPLICATION_JSON)
public Response getGenre(@PathParam("name") String genreName) {
Genre genre = potentiallyVerySlowSynchronousCall(genreName);
return Response.ok(genre).build();
}
解決問題的最簡單方法是將進行阻塞調用的代碼提交到線程池:
@GET
@Path("/genre/{name}")
@Produces(MediaType.APPLICATION_JSON)
public void getGenre(@PathParam("name") String genreName, @Suspended AsyncResponse response) {
response.setTimeout(1L, TimeUnit.SECONDS);
executorService.submit(() -> {
Genre genre = potentiallyVerySlowSynchronousCall(genreName);
return response.resume(Response.ok(genre).build());
});
}
3. 注意MDC值的傳播
MDC(映射診斷上下文)通常用于存儲單個任務的特定值。例如,在 Web 應用程序中,它可能為每個請求存儲一個請求 ID 和一個用戶 ID,因此 MDC 使查找與單個請求或整個用戶活動相關的日志條目變得更加容易。
2017-08-27 14:38:30,893 INFO [server-thread-0] [requestId=060d8c7f, userId=2928ea66] c.g.s.web.Controller - Message.
不幸的是,如果代碼的某些部分在專用線程池中執(zhí)行,則來自提交任務的線程的 MDC 值不會傳播。在以下示例中,第 7 行的日志條目包含“requestId”,而第 9 行的日志條目不包含:
@GET
@Path("/genre/{name}")
@Produces(MediaType.APPLICATION_JSON)
public void getGenre(@PathParam("name") String genreName, @Suspended AsyncResponse response) {
try (MDC.MDCCloseable ignored = MDC.putCloseable("requestId", UUID.randomUUID().toString())) {
String genreId = getGenreIdbyName(genreName); //Sync call
logger.trace("Submitting task to find genre with id '{}'.", genreId); //'requestId' is logged
executorService.submit(() -> {
logger.trace("Starting task to find genre with id '{}'.", genreId); //'requestId' is not logged
Response result = getGenre(genreId) //Async call
.map(artist -> Response.ok(artist).build())
.orElseGet(() -> Response.status(Response.Status.NOT_FOUND).build());
response.resume(result);
});
}
}
這可以通過使用 MDC#getCopyOfContextMap() 來解決:
public void getGenre(@PathParam("name") String genreName, @Suspended AsyncResponse response) {
try (MDC.MDCCloseable ignored = MDC.putCloseable("requestId", UUID.randomUUID().toString())) {
...
logger.trace("Submitting task to find genre with id '{}'.", genreId); //'requestId' is logged
withCopyingMdc(executorService, () -> {
logger.trace("Starting task to find genre with id '{}'.", genreId); //'requestId' is logged
...
});
}
}
private void withCopyingMdc(ExecutorService executorService, Runnable function) {
Map<String, String> mdcCopy = MDC.getCopyOfContextMap();
executorService.submit(() -> {
MDC.setContextMap(mdcCopy);
try {
function.run();
} finally {
MDC.clear();
}
});
}
4.關于線程的重命名
自定義線程名稱以簡化讀取日志和線程轉儲。這可以通過 在創(chuàng)建ExecutorService期間傳遞ThreadFactory來完成。流行的實用程序庫中有很多 ThreadFactory接口的實現(xiàn):
com.google.common.util.concurrent.ThreadFactoryBuilder in Guava。
Spring 中的org.springframework.scheduling.concurrent.CustomizableThreadFactory。
Apache Commons Lang 3 中的org.apache.commons.lang3.concurrent.BasicThreadFactory。
ThreadFactory threadFactory = new BasicThreadFactory.Builder()
.namingPattern("computation-thread-%d")
.build();
ExecutorService executorService = Executors.newFixedThreadPool(numberOfThreads, threadFactory);
雖然ForkJoinPool沒有使用ThreadFactory接口,但也支持線程的重命名:
ForkJoinPool.ForkJoinWorkerThreadFactory forkJoinThreadFactory = pool -> {
ForkJoinWorkerThread thread = ForkJoinPool.defaultForkJoinWorkerThreadFactory.newThread(pool);
thread.setName("computation-thread-" + thread.getPoolIndex());
return thread;
};
ForkJoinPool forkJoinPool = new ForkJoinPool(numberOfThreads, forkJoinThreadFactory, null, false);
只需將線程轉儲與默認名稱進行比較:
"pool-1-thread-3" #14 prio=5 os_prio=31 tid=0x00007fc06b19f000 nid=0x5703 runnable [0x0000700001ff9000]
java.lang.Thread.State: RUNNABLE
at com.github.sorokinigor.article.tipsaboutconcurrency.setthreadsname.TaskHandler.compute(TaskHandler.java:16)
...
"pool-2-thread-3" #15 prio=5 os_prio=31 tid=0x00007fc06aa10800 nid=0x5903 runnable [0x00007000020fc000]
java.lang.Thread.State: RUNNABLE
at com.github.sorokinigor.article.tipsaboutconcurrency.setthreadsname.HealthCheckCallback.recordFailure(HealthChecker.java:21)
at com.github.sorokinigor.article.tipsaboutconcurrency.setthreadsname.HealthChecker.check(HealthChecker.java:9)
...
"pool-1-thread-2" #12 prio=5 os_prio=31 tid=0x00007fc06aa10000 nid=0x5303 runnable [0x0000700001df3000]
java.lang.Thread.State: RUNNABLE
at com.github.sorokinigor.article.tipsaboutconcurrency.setthreadsname.TaskHandler.compute(TaskHandler.java:16)
...
對于名稱有特指的線程:
"task-handler-thread-1" #14 prio=5 os_prio=31 tid=0x00007fb49c9df000 nid=0x5703 runnable [0x000070000334a000]
java.lang.Thread.State: RUNNABLE
at com.github.sorokinigor.article.tipsaboutconcurrency.setthreadsname.TaskHandler.compute(TaskHandler.java:16)
...
"authentication-service-ping-thread-0" #15 prio=5 os_prio=31 tid=0x00007fb49c9de000 nid=0x5903 runnable [0x0000700003247000]
java.lang.Thread.State: RUNNABLE
at com.github.sorokinigor.article.tipsaboutconcurrency.setthreadsname.HealthCheckCallback.recordFailure(HealthChecker.java:21)
at com.github.sorokinigor.article.tipsaboutconcurrency.setthreadsname.HealthChecker.check(HealthChecker.java:9)
...
"task-handler-thread-0" #12 prio=5 os_prio=31 tid=0x00007fb49b9b5000 nid=0x5303 runnable [0x0000700003144000]
java.lang.Thread.State: RUNNABLE
at com.github.sorokinigor.article.tipsaboutconcurrency.setthreadsname.TaskHandler.compute(TaskHandler.java:16)
...
并想象可能有超過 3 個線程。
5. 使用 LongAdder 作為計數(shù)器
考慮使用 java.util.concurrent.atomic.LongAdder而不是 AtomicLong / AtomicInteger 用于高爭用的計數(shù)器。LongAdder維護多個單元的值并在需要時增加它們的數(shù)量,這會導致更高的吞吐量,但與 AtomicXX 系列類相比,也會導致更高的內存消耗。
ongAdder counter = new LongAdder();
counter.increment();
...
long currentValue = counter.sum();
更多高并發(fā)案例:
高并發(fā)服務優(yōu)化篇:JVM--工程師進階的必經(jīng)之路
淺談JDK并發(fā)包下面的分治思想及分治思想在高并發(fā)場景的運用