Bad EventQueue IDs

I have a problem with the following code example that shows inconsistent behavior for EventQueue:

public static void main( String[] args ) throws InvocationTargetException, InterruptedException { final long[] id1 = new long[ 1 ]; final long[] id2 = new long[ 1 ]; EventQueue.invokeAndWait( new Runnable() { @Override public void run() { id1[ 0 ] = Thread.currentThread().getId(); } } ); Thread.sleep( 5000 ); EventQueue.invokeAndWait( new Runnable() { @Override public void run() { id2[ 0 ] = Thread.currentThread().getId(); } } ); System.out.println( "id1 = " + id1[0] ); System.out.println( "id2 = " + id2[0] ); if(id1[0]!=id2[0]){ System.out.println("These ID don't match, even though they were retrieved from the same thread."); } } 

Basically, it gets the eventqueue thread id, waits 5 seconds, and then gets the id again.

For some reason, the identifier will not match. EventQueue seems to have been destroyed and recreated. Is this normal behavior? Is this somewhere documented? This is mistake? Even if it was a different instance, should it not have the same ID?

If I do not execute Thread.sleep , the identifier will match.

My other question is: how can I get around this? I am using an object that can only be accessed when creating a stream. If this is an eventqueue event (which does not have to be), I should be able to check if this is an eventqueue event.

+4
java concurrency swing
Aug 25 '11 at 12:25
source share
1 answer

This AWT Event Dispatch can be disabled when it is no longer needed ( this page describes both the view and the behavior of the actual implementation in JDK 7).

This happens here: you use the EventQueue system to handle a single event. Then nothing is needed (no AWT / Swing components, ...). After a while, it will turn off.

Then, when you use EventQueue again, another thread begins to take on this role.

So what happens is that your Runnable.run() do methods execute in two different threads. Both threads are an "AWT event dispatch thread", only at different times in the JVM life cycle.

Perhaps a special wrapper using EventQueue.isDispatchThread() would be a possible solution.

+2
Aug 25 '11 at 12:35
source share



All Articles