Is the order in which the 2 messages are shown guaranteed or aren't they?
// the current thread is not the event thread
SwingUtilities.invokeLater(new MyRunnable("first call") );
SwingUtilities.invokeLater(new MyRunnable("second call") );
// they are both called in the same non-event thread
public class MyRunnable implements Runnable{
private String message;
public MyRunnable(String message) {
this.message = message;
}
public void run() {
System.out.println(message);
}
}
Is it possible that sometimes this will output:
second call
first call
instead of:
first call
second call
So basiccally if I presume that an earlier invokeLater will always be called
before a later invokeLater, will this cause race conditions or not?
Thanks for any help.
With kind regards,
Geoffrey
If the API documentation doesn't guarantee this (and I haven't seen
anything that specifies it), then it wouldn't be wise to depend on such
a behaviour. The order could very well change in the next version
released and your application that depended on it might break.
So if the order of execution is critical to your application it would be
better to code your own method that performs this in sequence. For
instance : (Warning ! uncompiled & untested)
private LinkedList queue = new LinkedList();
private boolean taskActive;
private Runnable taskRunner = new Runnable()
{
public void run()
{
while (true)
{
Runnable current=null;
synchronized (queue)
{
if (queue.isEmpty)
{
taskActive = false;
return;
} else
{
current = (Runnable)queue.removeFirst();
}
}
if (current != null) current.run();
}
}
};
public void SubmitRunnable(Runnable r)
{
synchronized (queue)
{
queue.addLast(r);
if (!taskActive)
{
taskActive = true;
SwingUtilities.invokeLater(taskRunner);
}
}
}
BK