【问题标题】:How to pass object across methods using Thread context?如何使用线程上下文跨方法传递对象?
【发布时间】:2021-06-07 15:33:36
【问题描述】:

我想在线程内的方法之间传递对象而不使用方法签名。

例子:

public class Controller {

    @GET
    public void requestController() {

        // set user data in the controller currentThread

    }

}

public class Service {
    
    public void serviceMethod() {

        // get user data in the service method from currentThread

    }

}

由于Controller 和Service 在同一个线程中,我应该能够访问在Service 中设置的Controller 中的对象。

MDC 使用 MDC.put 和 MDC.get 确实遵循相同的方法,但我不确定它使用哪种模式。

【问题讨论】:

标签: java dropwizard mdc


【解决方案1】:

您正在寻找ThreadLocal。 MDC 在内部使用它。

用法

用法很简单。您需要一个可供所有需要访问它的组件访问的 ThreadLocal 实例。在大多数情况下,它只是一个 public static final 变量。

public class SomeClass {

    // use whatever class you want here, String for example
    public static final ThreadLocal<String> TL_MESSAGE = new ThreadLocal<>();
}

public class Controller {

    @GET
    public void requestController() {
        SomeClass.TL_MESSAGE.set("hello world");
        try {
            // everything after set should be wrapped in this try-finally-block
            service.serviceMethod();// this can be anywhere in the code, it doesnt have to called here directly. As long as the thread is the same and the method is called between set and remove
        } finally {
            SomeClass.TL_MESSAGE.remove();
        }
    }
}

public class Service {
    
    public void serviceMethod() {
        String message = SomeClass.TL_MESSAGE.get();
    }
}

陷阱/内存泄漏的可能性!

确保您始终删除您设置的值。 更多信息请见:ThreadLocal & Memory Leak

【讨论】:

  • 感谢您添加示例,您知道为什么我们在写信给ThreadLocal 时必须跟踪上次操作吗?这是LogbackMDCput实现github.com/qos-ch/logback/blob/…
  • 这高度特定于 Logback 用例。查看您分享的课程中的评论和链接的票证。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多