1. 环境

Java: jdk1.8.0_144

2. 背景

Java多线程执行任务时,Logback输出的主线程和各个子线程的业务日志需要区分时,可以根据线程池和执行的线程来区分,但若要把它们联系起来只能根据时间线,既麻烦又无法保证准确性。

2018-10-27 23:09:22 [INFO][com.lxp.tool.log.LogAndCatchExceptionRunnableTest][main][testRun][38] -> test start
2018-10-27 23:09:22 [INFO][com.lxp.tool.log.RunnabeTestHelper][pool-1-thread-1][lambda$getRunnable$0][16] -> This is runnable.
2018-10-27 23:09:22 [INFO][com.lxp.tool.log.RunnabeTestHelper][pool-1-thread-2][lambda$getRunnable$0][16] -> This is runnable.
2018-10-27 23:09:22 [INFO][com.lxp.tool.log.RunnabeTestHelper][pool-1-thread-1][lambda$getRunnable$0][16] -> This is runnable.
2018-10-27 23:09:22 [INFO][com.lxp.tool.log.RunnabeTestHelper][pool-1-thread-2][lambda$getRunnable$0][16] -> This is runnable.
2018-10-27 23:09:22 [INFO][com.lxp.tool.log.RunnabeTestHelper][pool-1-thread-1][lambda$getRunnable$0][16] -> This is runnable.
2018-10-27 23:09:22 [INFO][com.lxp.tool.log.LogAndCatchExceptionRunnableTest][main][testRun][48] -> test finish

org.slf4j.MDC类提供了一个极好的解决方案,它可以为各个线程设置独有的上下文,当有必要时也可以把主线程的上下文复制给子线程,此时子线程可以拥有主线程+子线程的信息,在子线程退出前恢复到主线程上下文,如此一来,日志信息可以极大地便利定位问题,org.slf4j.MDC类在线程上下文切换上的应用记录本文的目的之一。

另一个则是过去一直被自己忽略的多线程时退出的问题,任务需要多线程执行有两种可能场景

  • 多个任务互相独立,某个任务失败并不应该影响其它的任务继续执行
  • 多个子任务组成一个完整的主任务,若某个子任务失败它应该直接退出,不需要等所有子任务完成

3. org.slf4j.MDC类在线程上下文切换时的应用

3.1 实现包装线程

  • AbstractLogWrapper
public class AbstractLogWrapper<T> {
private final T job;
private final Map<?, ?> context; public AbstractLogWrapper(T t) {
this.job = t;
this.context = MDC.getCopyOfContextMap();
} public void setLogContext() {
if (this.context != null) {
MDC.setContextMap(this.context);
}
} public void clearLogContext() {
MDC.clear();
} public T getJob() {
return this.job;
}
}
  • LogRunnable
public class LogRunnable extends AbstractLogWrapper<Runnable> implements Runnable {
public LogRunnable(Runnable runnable) {
super(runnable);
} @Override
public void run() {
// 把主线程上下文复到子线程
this.setLogContext();
try {
getJob().run();
} finally {
// 恢复主线程上下文
this.clearLogContext();
}
}
}
  • LogAndCatchExceptionRunnable
public class LogAndCatchExceptionRunnable extends AbstractLogWrapper<Runnable> implements Runnable {
private static final Logger LOGGER = LoggerFactory.getLogger(LogAndCatchExceptionRunnable.class); public LogAndCatchExceptionRunnable(Runnable runnable) {
super(runnable);
} @Override
public void run() {
// 把主线程上下文复到子线程
this.setLogContext();
try {
getJob().run();
} catch (Exception e) { // Catch所有异常阻止其继续传播
LOGGER.error(e.getMessage(), e);
} finally {
// 恢复主线程上下文
this.clearLogContext();
}
}
}

3.2 配置%X输出当前线程相关联的NDC

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="stdot" class="ch.qos.logback.core.ConsoleAppender">
<layout class="ch.qos.logback.classic.PatternLayout">
<pattern>%d{yyyy-MM-dd HH:mm:ss} [%p][%c][%t][%M][%L] %replace(Test_Method=%X{method} runn-able=%X{runn_able}){'.+=( |$)', ''} -> %m%n</pattern>
</layout>
</appender>
<root level="debug">
<appender-ref ref="stdot"/>
</root>
</configuration>

3.3 配置线程相关信息并测试

class RunnabeTestHelper {
private static final Logger LOGGER = LoggerFactory.getLogger(RunnabeTestHelper.class);
private static final String RUNNABLE = "runn_able"; static Runnable getRunnable() {
return () -> {
MDC.put(RUNNABLE, String.valueOf(System.currentTimeMillis()));
LOGGER.info("This is runnable.");
};
}
}
  • 测试方法
    @Test
public void testRun() {
try {
MDC.put("method", "testRun");
LOGGER.info("test start");
LogAndCatchExceptionRunnable logRunnable = spy(new LogAndCatchExceptionRunnable(RunnabeTestHelper.getRunnable()));
Set<String> set = new HashSet<>();
doAnswer(invocation -> set.add(invocation.getMethod().getName())).when(logRunnable).setLogContext();
doAnswer(invocation -> set.add(invocation.getMethod().getName())).when(logRunnable).clearLogContext(); List<CompletableFuture<Void>> futures = IntStream.rangeClosed(0, 4).mapToObj(index -> CompletableFuture.runAsync(logRunnable, executorService)).collect(Collectors.toList());
futures.forEach(CompletableFuture::join);
assertEquals("[setLogContext, clearLogContext]", set.toString());
LOGGER.info("test finish");
} finally {
MDC.clear();
}
}
  • 测试结果
2018-11-01 01:08:04 [INFO][com.lxp.tool.log.LogRunnableTest][main][testRun][41]  -> test start
2018-11-01 01:08:05 [INFO][com.lxp.tool.log.RunnabeTestHelper][pool-1-thread-1][lambda$getRunnable$0][16] Test_Method=testRun runn-able=1541005685003 -> This is runnable.
2018-11-01 01:08:05 [INFO][com.lxp.tool.log.RunnabeTestHelper][pool-1-thread-1][lambda$getRunnable$0][16] Test_Method=testRun runn-able=1541005685004 -> This is runnable.
2018-11-01 01:08:05 [INFO][com.lxp.tool.log.RunnabeTestHelper][pool-1-thread-1][lambda$getRunnable$0][16] Test_Method=testRun runn-able=1541005685004 -> This is runnable.
2018-11-01 01:08:05 [INFO][com.lxp.tool.log.RunnabeTestHelper][pool-1-thread-2][lambda$getRunnable$0][16] Test_Method=testRun runn-able=1541005685003 -> This is runnable.
2018-11-01 01:08:05 [INFO][com.lxp.tool.log.RunnabeTestHelper][pool-1-thread-2][lambda$getRunnable$0][16] Test_Method=testRun runn-able=1541005685005 -> This is runnable.
2018-11-01 01:08:05 [INFO][com.lxp.tool.log.LogRunnableTest][main][testRun][50] -> test finish

4. 多线程执行子线程出现异常时的处理

class RunnabeTestHelper {
private static final Logger LOGGER = LoggerFactory.getLogger(RunnabeTestHelper.class); static Runnable getRunnable(AtomicInteger counter) {
return () -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
LOGGER.error(e.getMessage(), e);
}
if (counter.incrementAndGet() == 2) {
throw new NullPointerException();
}
LOGGER.info("This is {} runnable.", counter.get());
};
} static Runnable getRunnableWithCatchException(AtomicInteger counter) {
return () -> {
try {
Thread.sleep(1000);
if (counter.incrementAndGet() == 2) {
throw new NullPointerException();
}
LOGGER.info("This is {} runnable.", counter.get());
} catch (Exception e) {
LOGGER.error("error", e);
}
};
}
}

4.1 选择一:放充执行未执行的其它子线程

  • 调用LogRunnable,允许子线程的异常继续传播
    @Test
public void testRunnableWithoutCatchException() {
Logger logger = Mockito.mock(Logger.class);
AtomicInteger counter = new AtomicInteger(0);
List<CompletableFuture<Void>> futures = IntStream.rangeClosed(0, 4).mapToObj(index -> CompletableFuture.runAsync(new LogRunnable(RunnabeTestHelper.getRunnable(counter)), executorService)).collect(Collectors.toList());
try {
futures.forEach(CompletableFuture::join);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
// 由于子线程的异常导致主线程退出,并不是所有任务都得到执行机会
assertEquals(2, counter.get());
verify(logger, Mockito.times(1)).error(anyString(), any(Throwable.class));
}

4.2 选择二:执行完所有无异常的子线程

  • 调用LogRunnable,在线程内部阻止异常扩散
    @Test
public void testRunnableWithCatchException() {
AtomicInteger counter = new AtomicInteger(0);
List<CompletableFuture<Void>> futures = IntStream.rangeClosed(0, 4).mapToObj(index -> CompletableFuture.runAsync(new LogRunnable(RunnabeTestHelper.getRunnableWithCatchException(counter)), executorService)).collect(Collectors.toList());
futures.forEach(CompletableFuture::join);
// 由于子线程的异常被阻止,所有线程都得到执行机会
assertEquals(5, counter.get());
}
  • 调用LogAndCatchExceptionRunnable,在包装类阻止异常扩散
    @Test
public void testRunnableWithoutCatchException() {
AtomicInteger counter = new AtomicInteger(0);
List<CompletableFuture<Void>> futures = IntStream.rangeClosed(0, 4).mapToObj(index -> CompletableFuture.runAsync(new LogAndCatchExceptionRunnable(RunnabeTestHelper.getRunnable(counter)), executorService)).collect(Collectors.toList());
futures.forEach(CompletableFuture::join);
// 由于子线程的异常被阻止,所有线程都得到执行机会
assertEquals(5, counter.get());
} @Test
public void testRunnableWithCatchException() {
AtomicInteger counter = new AtomicInteger(0);
List<CompletableFuture<Void>> futures = IntStream.rangeClosed(0, 4).mapToObj(index -> CompletableFuture.runAsync(new LogAndCatchExceptionRunnable(RunnabeTestHelper.getRunnableWithCatchException(counter)), executorService)).collect(Collectors.toList());
futures.forEach(CompletableFuture::join);
// 由于子线程的异常被阻止,所有线程都得到执行机会
assertEquals(5, counter.get());
}

使用CompletableFuture+ExecutorService+Logback的多线程测试的更多相关文章

  1. Junit使用GroboUtils进行多线程测试

    写过Junit单元测试的同学应该会有感觉,Junit本身是不支持普通的多线程测试的,这是因为Junit的底层实现上,是用System.exit退出用例执行的.JVM都终止了,在测试线程启动的其他线程自 ...

  2. ExecutorService 建立一个多线程的线程池的步骤

    ExecutorService 建立一个多线程的线程池的步骤: 线程池的作用: 线程池功能是限制在系统中运行的线程数. 依据系统的环境情况,能够自己主动或手动设置线程数量.达到执行的最佳效果:少了浪费 ...

  3. testng入门教程12 TestNG执行多线程测试

    testng入门教程 TestNG执行多线程测试 testng入门教程 TestNG执行多线程测试 并行(多线程)技术在软件术语里被定义为软件.操作系统或者程序可以并行地执行另外一段程序中多个部分或者 ...

  4. 关于JUnit4无法支持多线程测试的解决方法

    转自:https://segmentfault.com/a/1190000003762719 其实junit是将test作为参数传递给了TestRunner的main函数.并通过main函数进行执行. ...

  5. TestNG多线程测试-注解方式实现

    用@Test(invocationCount = x,threadPoolSize = y)声明,invocationCount表示执行次数,threadPoolSize表示线程池大小. packag ...

  6. TestNg之XMl形式实现多线程测试

    为什么要使用多线程测试? 在实际测试中,为了节省测试时间,提高测试效率,在实际测试场景中经常会采用多线程的方式去执行,比如爬虫爬数据,多浏览器并行测试. 关于多线程并行测试 TestNG中实现多线程并 ...

  7. JUNIT4 GroboUtils多线程测试

    阅读更多 利用JUNIT4,GroboUtils进行多线程测试 多线程编程和测试一直是比较难搞的事情,特别是多线程测试.只用充分的测试,才可以发现多线程编码的潜在BUG.下面就介绍一下我自己在测试多线 ...

  8. TestNG 多线程测试

    TestNG以注解的方式实现多线程测试 import org.testng.annotations.Test; public class TreadDemo { // invocationCount ...

  9. 【多线程】java多线程 测试例子 详解wait() sleep() notify() start() join()方法 等

    java实现多线程,有两种方法: 1>实现多线程,继承Thread,资源不能共享 2>实现多线程  实现Runnable接口,可以实现资源共享 *wait()方法 在哪个线程中调用 则当前 ...

随机推荐

  1. Go -- 通过GOTRACEBACK生成程序崩溃后core文件的方法(gcore gdb)

    写一个错误的c程序   package dlsym import "testing" func Test_intercept(t *testing.T) { Intercept(& ...

  2. pycharm、idea插件代理设置,插件安装

    pycharm和idea都是intellij的,所以插件安装是设置代理方法相似, 以pycharm举例: 1.已经安装的插件列表: 2.查找要安装的插件,没有,会给出下载插件的链接地址: 3.打开链接 ...

  3. python中pymysql使用

    python中pymysql使用 https://blog.csdn.net/johline/article/details/69549131 import pymysql # 连接数据库 conne ...

  4. 转:Twemproxy——针对MemCached与Redis的代理

    转自: http://www.infoq.com/cn/news/2012/12/twemproxy Twemproxy是一个代理服务器,可以通过它减少Memcached或Redis服务器所打开的连接 ...

  5. 用C++实现一个Log系统

    提要 近期在写一些C++的图形代码,在调试和測试过程中都会须要在终端打印一些信息出来. 之前的做法是直接用 std::cout<<"Some Word"<< ...

  6. Android四大组件的生命周期

    介绍生命周期之前,先提一下任务的概念 任务其实就是activity 的栈它由一个或多个Activity组成的共同完成一个完整的用户体验, 换句话说任务就是” 应用程序” (可以是一个也可以是多个,比如 ...

  7. 常用linux系统监控命令

    一.内存监控 监控内存的使用状态是非常重要的,通过监控有助于了解内存的使用状态,比如内存占用是否正常,内存是否紧缺等等,监控内存最常使用的命令有free.vmstat.top等 1.1 free $ ...

  8. docker (2)---存储、网络(利用docker容器上线静态网站)

    一.docker底层依赖的核心技术 1.命名空间 (Namespaces) 2.控制组 (Control Groups) 3.联合文件系统 (Union File System) 4.Linux 虚拟 ...

  9. directdraw 显示yuv

    http://www.cnblogs.com/lidan/archive/2012/03/23/2413772.html http://www.yirendai.com/msd/

  10. Snail—iOS网络学习之得到网络上的数据

    在开发项目project中,尤其是手机APP,一般都是先把界面给搭建出来.然后再从网上down数据 来填充 那么网上的数据是怎么得来的呢,网络上的数据无非就经常使用的两种JSON和XML 如今 大部分 ...