简体   繁体   中英

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

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

}

Below is my 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();

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.

What you can and should do is remove Context clearing action from Parent and delegate it to the Child itself. You can write your AsyncTaskDecorator as below;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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