简体   繁体   English

让主线程等待直到上下文被子线程复制

[英]Make main thread wait until the context is copied by child threads

I am working on a process which does the following task:我正在处理执行以下任务的流程:

1.Kafka Consumer consumes kafka message and does some task A
2.It then starts an async process using @Async in spring boot
3.It clears the context and exits

I am passing context to Async using a TaskDecorator我正在使用 TaskDecorator 将上下文传递给 Async

public class AsyncTaskDecorator implements TaskDecorator {
   ContextProvider provider = ContextProvider.getContext();

} }

Below is my ContextProvider class下面是我的 ContextProvider class

private static final ThreadLocal<CountryContextProvider> CONTEXT = new ThreadLocal<>();
 public static void clear() {
     CONTEXT.clear();
 }

The problem I am facing is the parent thread invokes clear on the context before the child thread could copy it using ContextProvider provider = ContextProvider.getContext();我面临的问题是在子线程可以使用ContextProvider provider = ContextProvider.getContext();复制它之前,父线程在上下文上调用 clear

How do I make sure that the child thread is able to get the context before parent thread calls clear.Also,I cannot make main thread wait for child thread, whole point of using Async is to allow child thread to execute independently.如何确保子线程能够在父线程调用clear之前获取上下文。另外,我不能让主线程等待子线程,使用Async的全部意义在于让子线程独立执行。

What you can and should do is remove Context clearing action from Parent and delegate it to the Child itself.您可以而且应该做的是从 Parent 中删除上下文清除操作并将其委托给 Child 本身。 You can write your AsyncTaskDecorator as below;您可以如下编写 AsyncTaskDecorator;

public class AsyncTaskDecorator implements TaskDecorator {
   public Runnable decorate(Runnable runnable) {
      return () -> {
          try {
              ContextProvider provider = ContextProvider.getContext();
              // Use it here
          } finally {
              ContextProvider.getContext().clear();
          }
      };
   }
}

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

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