public class Task implements Runnable {
private final BlockingQueue queue = ...;
@Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
String result = getOrDefault(() -> queue.poll(1L, TimeUnit.MINUTES), "default");
//do smth with the result
}
}
T getOrDefault(Callable supplier, T defaultValue) {
try {
return supplier.call();
}
catch (Exception e) {
logger.error("Got exception while retrieving value.", e);
return defaultValue;
}
}
}
T getOrDefault(Callable 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;
}
}
@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());
}
);
}
2017-08-27 14:38:30,893 INFO [server-thread-0] [requestId=060d8c7f, userId=2928ea66] c.g.s.web.Controller - Message.
@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);
}
);
}
}
...
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
com.google.common.util.concurrent.ThreadFactoryBuilde+r in Guava. org.springframework.scheduling.concurrent.CustomizableThreadFactory in Spring. org.apache.commons.lang3.concurrent.BasicThreadFactory in Apache Commons Lang 3.
ThreadFactory threadFactory = new BasicThreadFactory.Builder()
.namingPattern("computation-thread-%d")
.build();
ExecutorService executorService = Executors.newFixedThreadPool(numberOfThreads, 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) ...
LongAdder counter = new LongAdder(); counter.increment(); ... long currentValue = counter.sum();
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2026 源码网商城 (www.ymwmall.com) 版权所有