Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

不修饰Runnable也能传参? #434

Closed
Dreamroute opened this issue Oct 11, 2022 · 2 comments
Closed

不修饰Runnable也能传参? #434

Dreamroute opened this issue Oct 11, 2022 · 2 comments
Assignees
Labels
🔰 first nice issue 👍 ❓question Further information is requested

Comments

@Dreamroute
Copy link

Dreamroute commented Oct 11, 2022

看到使用说明中说,需要修饰RunnableCallable方能传参,那么我这种使用,是不是意味着不修饰也能传?
还是说我理解有问题?

class TtlTest {

    private static final ThreadLocal<String> TL = new TransmittableThreadLocal<>();
    private static final ExecutorService pool = Executors.newFixedThreadPool(10);

    @Test
    void ttl() throws Exception {
        TL.set("Jay");
        pool.submit(() -> {
            String name = TL.get();
            System.err.println(name);
            // 也能获取到参数
        });
        SECONDS.sleep(2000);
    }

}
@oldratlee oldratlee added ❓question Further information is requested 🔰 first nice issue 👍 labels Oct 11, 2022
@oldratlee
Copy link
Member

oldratlee commented Oct 11, 2022

看到使用说明中说,需要修改RunnableCallable方能传参,那么我这种使用,是不是意味着不修饰也能传?

@Dreamroute
如果不修饰,TransmittableThreadLocal的效果/功能就退化成 JDKInheritableThreadLocal

InheritableThreadLocal的功能是你的Demo能取到参数的原因。


具体一些的说明参见项目的用户使用文档:

  • TransmittableThreadLocal类继承并加强InheritableThreadLocal类。
    • aka. TransmittableThreadLocal is a InheritableThreadLocal.
  • 修饰方式有3种
    • 2.1 修饰RunnableCallable
    • 2.2 修饰线程池
    • 2.3 使用Java Agent来修饰JDK线程池实现类

进一步系统理解或确认,请看

@oldratlee oldratlee self-assigned this Oct 11, 2022
@Dreamroute
Copy link
Author

Dreamroute commented Oct 27, 2022

果然,如果提前为线程池预热,比如执行若干次pool.submit(() -> {});,那么就无法获取到值了。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
🔰 first nice issue 👍 ❓question Further information is requested
Projects
None yet
Development

No branches or pull requests

2 participants