Search code examples
javaspring-integrationspring-amqpspring-rabbit

spring-rabitmq and thread local - when is a good moment to invoke clean method


I have a @RabbitListener and properly working consuming from queue. In my listener I set context.

I know that there are many (configurable) threads consuming the same queue (so in real executing the same lisener code).

Now, I consdier when is good time to clear context ?

To be more precisely, it is problem for me to express:

"When you end consuming (no matter with exception or not) do clear context)"

Below, you can see a scheme of my problem:

public class CustomContextHolder {

   private static final ThreadLocal<DatabaseType> contextHolder = 
            new ThreadLocal<DatabaseType>();

   public static void setContext(DatabaseType databaseType) {
      contextHolder.set(databaseType);
   }

   public static CustomerType getContext() {
      return (CustomerType) contextHolder.get();
   }

   public static void clearContext() {
      contextHolder.remove();
   }
}


@RabbitListener
void listenMessage(Message message) {
  ...
  CustomContextHolder.set(...);

}

Solution

  • It's generally better to use stateless objects as listeners rather than using ThreadLocal.

    However, if you are forced to keep state this way, you can implement ApplicationListener<AmqpEvent>.

    The ApplicationListener will receive several events; specifically, the AsyncConsumerStoppedEvent when the consumer is stopped normally and ListenerContainerConsumerFailedEvent if the consumer stops abnormally. These two events are published on the listener thread, so you can clear your ThreadLocal there.

    Other events may or may not be published on the listener thread.