Skip to content

Instantly share code, notes, and snippets.

@mheath
Created February 20, 2015 19:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mheath/547ce1044c282acd88e6 to your computer and use it in GitHub Desktop.
Save mheath/547ce1044c282acd88e6 to your computer and use it in GitHub Desktop.
Deadlock publishing event while creating listener bean.
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;
@SpringBootApplication
public class DeadlockTest {
private final CountDownLatch latch = new CountDownLatch(1);
@Bean
ThreadPoolTaskExecutor executor() {
return new ThreadPoolTaskExecutor();
}
@Bean
Future<?> publisherBean(ApplicationEventPublisher publisher) {
return executor().submit(() -> {
try {
latch.await();
publisher.publishEvent(new MyEvent("Hello deadlock world."));
} catch (InterruptedException e) {
throw new Error(e);
}
});
}
@Bean MyListener listenerBean() {
latch.countDown();
return new MyListener();
}
public static void main(String[] args) {
new SpringApplicationBuilder()
.sources(DeadlockTest.class)
.web(false)
.build().run(args);
System.out.println("Started, no deadlock!");
}
static class MyEvent extends ApplicationEvent {
public MyEvent(Object source) {
super(source);
}
}
static class MyListener implements ApplicationListener<MyEvent> {
@Override
public void onApplicationEvent(MyEvent event) {
System.out.println(event.getSource());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment