简体   繁体   English

如何使用线程上下文跨方法传递 object?

[英]How to pass object across methods using Thread context?

I want to pass objects between methods within a thread without using a method signature.我想在不使用方法签名的情况下在线程内的方法之间传递对象。

Example:例子:

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

    }

}

as Controller and Service are in the same thread, I should be able to access the object in Service that was set in the Controller .由于ControllerService在同一个线程中,我应该能够访问 Controller 中设置的Service中的Controller

MDC does follow the same approach using MDC.put and MDC.get but I am not sure which pattern it uses. MDC确实使用MDC.putMDC.get遵循相同的方法,但我不确定它使用哪种模式。

Youre looking for a ThreadLocal .您正在寻找ThreadLocal MDC uses that internally. MDC 在内部使用它。

Usage用法

The usage is pretty simple.用法很简单。 You need one ThreadLocal Instance that is accessable by all components that need access to it.您需要一个可供所有需要访问它的组件访问的 ThreadLocal 实例。 In most cases its simply a public static final variable.在大多数情况下,它只是一个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();
    }
}

Pitfall / Memory leak possibility!陷阱/Memory 泄漏可能性!

Ensure that you always remove the value you set.确保始终删除您设置的值。 For more information, see: ThreadLocal & Memory Leak有关更多信息,请参阅: ThreadLocal 和 Memory 泄漏

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM