微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决如何使用线程上下文跨方法传递对象?

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

示例:

MacBook-Air-alkhas-b-rjayy:new app 19:2 rjayy$ cd my-app
MacBook-Air-alkhas-b-rjayy:my-app rjayy$ npm start

> my-app@0.1.0 start /Users/rjayy/Desktop/react/my-app/src/new app 19:2/my-app
> react-scripts start

sh: react-scripts: command not found
npm ERR! code ELIFECYCLE
npm ERR! syscall spawn
npm ERR! file sh
npm ERR! errno ENOENT
npm ERR! my-app@0.1.0 start: `react-scripts start`
npm ERR! spawn ENOENT
npm ERR! 
npm ERR! Failed at the my-app@0.1.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/rjayy/.npm/_logs/2021-03-09T17_37_55_559Z-debug.log
MacBook-Air-alkhas-b-rjayy:my-app rjayy$

由于 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 确实使用 MDCMDC.put 遵循相同的方法,但我不确定它使用哪种模式。

解决方法

您正在寻找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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?