The cause of the bug
When sending messages, this interface needs to be rewritten. If the rewritten method throws an exception and does not capture it, the program will be stuck and will not execute the
Destroy source code
package com.lmax.disruptor;
public interface EventTranslatorVararg<T> {
void translateTo(T var1, long var2, Object... var4);
}
Problem code
public class Main {
public static void main(String[] args) {
Disruptor<Message> disruptor = new Disruptor<>(
Message::new,
1024,
(ThreadFactory) Thread::new);
disruptor.handleEventsWith((EventHandler<Message>) (message, l, b) -> {
System.out.println("Handling messages " + message);
});
disruptor.start();
RingBuffer<Message> ringBuffer = disruptor.getRingBuffer();
for(int i = 0; i<10; i++){
Message message = new Message(String.valueOf(i));
ringBuffer.publishEvent((m, l) ->
throw new RuntimeException();
);// Throwing exceptions without catching and finding that the program cannot be terminated
}
System.out.println("hi"); //hi Will not output
disruptor.shutdown();//shutdown the disruptor, the method will block until all events have been handled.
}
}
result:
The main thread exits, but the program continues to run without stopping
solve:
Handle exceptions on call
public class Main {
public static void main(String[] args) {
Disruptor<Message> disruptor = new Disruptor<>(
Message::new,
1024,
(ThreadFactory) Thread::new);
disruptor.handleEventsWith((EventHandler<Message>) (message, l, b) -> {
System.out.println("Handling messages " + message);
});
disruptor.start();
RingBuffer<Message> ringBuffer = disruptor.getRingBuffer();
for(int i = 0; i<10; i++){
Message message = new Message(String.valueOf(i));
ringBuffer.publishEvent((m, l, m2) -> {
try {
throw new RuntimeException();
}catch (Exception e){
e.printStackTrace();
}
});// Handle exceptions, find program print exceptions and can end
}
System.out.println("hi");
disruptor.shutdown();//Close the disruptor and the method will block until all events have been processed.
}
}
Message.java
public class Message {
String id;
public Message(String id) {
this.id = id;
}
public Message() {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@Override
public String toString() {
return "Message{" +
"id='" + id + '\'' +
'}';
}
}