为应用程序中的所有线程设置ThreadContext [英] Setting ThreadContext for all threads in application

查看:1303
本文介绍了为应用程序中的所有线程设置ThreadContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过此答案 https://stackoverflow.com/a/25125159/4367326 我有routingAppender工作,但我想为程序中的每个线程设置ThreadContext.

From this answer https://stackoverflow.com/a/25125159/4367326 I have routingAppender working but I want to set the ThreadContext for every thread in the program.

设置后

ThreadContext.put("logFileName", "TestLogFile");

它适用于主线程并按预期方式记录日志,但不适用于我的应用程序中的任何其他线程.我该如何实现?

it works for the main thread and logs as expected but not for any other threads in my application. How can I achieve this?

推荐答案

如果将系统属性 isThreadContextMapInheritable 设置为true,则每个子线程都将继承父级ThreadContext状态.但这对执行者不起作用,因此您需要手动将数据从一个线程复制到另一个线程.

Every child thread will inherit fathers ThreadContext state if you set up system property isThreadContextMapInheritable to true. But this will not work for Executors so you need to manually copy data from one thread to another.

更新#2

您可以执行以下操作:

public abstract class ThreadContextRunnable implements Runnable {

  private final Map context = ThreadContext.getContext();

  @Override
  public final void run() {
    if (context != null) {
      ThreadContext.putAll(context);
    }
    try {
      runWithContext();
    } finally {
      ThreadContext.clearAll();
    }
  }

  protected abstract void runWithContext();
}

然后您只需要实现runWithContext方法.

And then you only need to implement runWithContext method.

这篇关于为应用程序中的所有线程设置ThreadContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆