简体   繁体   English

如何保留多线程所需的公共数据

[英]How to keep common data required for multiple thread

I have a multi threaded environment.我有一个多线程环境。 Within those threads I need to make some http call.在这些线程中,我需要进行一些 http 调用。 This is an existing code.这是现有的代码。 Now the new requirement is that I need to pass a token to those call.现在的新要求是我需要将令牌传递给这些调用。 So I need to keep this token to some where and need to get it during the call.所以我需要将此令牌保存在某个地方,并且需要在通话期间获取它。

So my question is what will be the best implementation to keep the token.所以我的问题是保留令牌的最佳实施方式是什么。

I can store the token in some singleton class and get the value from there.我可以将令牌存储在一些 singleton class 中并从那里获取值。 What will be the merit / demerit of this approach.这种方法的优点/缺点是什么。

Thanx in advance.提前谢谢。

Wherever you store it, you need to store it in thread safe memory.无论您将其存储在何处,都需要将其存储在线程安全的 memory 中。 For example, you could declare the variable used to store it volatile .例如,您可以声明用于存储它的变量volatile

For ease of access, you could use a singleton, but a static variable in a convenient class might be easier.为了便于访问,您可以使用 singleton,但在方便的 class 中使用 static 变量可能更容易。

If I understand your problem correctly, you want to generate some token from parent thread then you can use in child threads in during Http request.如果我正确理解您的问题,您想从父线程生成一些令牌,那么您可以在 Http 请求期间在子线程中使用。

The below approach can be used.可以使用以下方法。 You can use the InheritableThreadLocal variable to store the token and then it can be used safely by the child threads.您可以使用 InheritableThreadLocal 变量来存储令牌,然后子线程可以安全地使用它。

public class ThreadContext {
    private static ThreadLocal<String> currentThread = new InheritableThreadLocal<>();

    public static String getCurrentThread() {
        return currentThread.get();
    }

    public static void setCurrentThread(String tenant) {
        currentThread.set(tenant);
    }

    public static void clear() {
        currentThread.set(null);
    }
}

You can set the token using the ThreadContext.setCurrentThread(String tenant) method.您可以使用 ThreadContext.setCurrentThread(String tenant) 方法设置令牌。 And in the child thread, you can use ThreadContext.getCurrentThread();而在子线程中,可以使用 ThreadContext.getCurrentThread();

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

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