Skip to content

Commit 8408e13

Browse files
committed
Save reference to the calling thread in each event
This way, even though publish and publishLater handle the event notification on the event dispatch thread, the original calling thread can still be gleaned from the event. This is useful for debugging. We also take a snapshot of the stack trace, so that it is crystal clear exactly where in the code the event publication took place.
1 parent 7538b25 commit 8408e13

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

src/main/java/org/scijava/event/DefaultEventService.java

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,12 +84,14 @@ public class DefaultEventService extends AbstractService implements
8484
@Override
8585
public <E extends SciJavaEvent> void publish(final E e) {
8686
e.setContext(getContext());
87+
e.setCallingThread(Thread.currentThread());
8788
eventBus.publishNow(e);
8889
}
8990

9091
@Override
9192
public <E extends SciJavaEvent> void publishLater(final E e) {
9293
e.setContext(getContext());
94+
e.setCallingThread(Thread.currentThread());
9395
eventBus.publishLater(e);
9496
}
9597

src/main/java/org/scijava/event/SciJavaEvent.java

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,8 +40,15 @@
4040
*/
4141
public abstract class SciJavaEvent extends AbstractContextual {
4242

43+
/** Whether the event has been handled already. */
4344
private boolean consumed;
4445

46+
/** The thread which published this event. */
47+
private Thread callingThread;
48+
49+
/** The stack trace of the calling thread when the event was published. */
50+
private StackTraceElement[] stackTrace;
51+
4552
// -- SciJavaEvent methods --
4653

4754
public boolean isConsumed() {
@@ -56,6 +63,25 @@ public void consume() {
5663
setConsumed(true);
5764
}
5865

66+
/** Gets the thread that published the event. */
67+
public Thread getCallingThread() {
68+
return callingThread;
69+
}
70+
71+
/** Sets the thread that published the event. */
72+
public void setCallingThread(final Thread callingThread) {
73+
this.callingThread = callingThread;
74+
stackTrace = callingThread.getStackTrace();
75+
}
76+
77+
/**
78+
* Gets the stack trace of the calling thread when the event was published.
79+
* This method is useful for debugging what triggered an event.
80+
*/
81+
public StackTraceElement[] getStackTrace() {
82+
return stackTrace;
83+
}
84+
5985
// Object methods --
6086

6187
@Override

0 commit comments

Comments
 (0)