<Swing Dev> Problem in Swing Timer
Roman Kennke
roman.kennke at aicas.com
Wed Dec 3 16:26:43 UTC 2008
Hi,
I see a small problem in the Swing timer. If you have a look in
TimerQueue.java, you'll see the following startup code:
synchronized void start() {
if (running) {
throw new RuntimeException("Can't start a TimerQueue " +
"that is already running");
}
else {
final ThreadGroup threadGroup =
AppContext.getAppContext().getThreadGroup();
java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction() {
public Object run() {
Thread timerThread = new Thread(threadGroup,
TimerQueue.this,
"TimerQueue");
timerThread.setDaemon(true);
timerThread.setPriority(Thread.NORM_PRIORITY);
timerThread.start();
return null;
}
});
running = true;
}
}
and the actual thread loop looks like this:
public void run() {
while (running) {
// Do stuff.
}
}
You see that the running field is set _after_ the thread has been
started. It can happen that the started thread kicks off immediately,
sees that running is (still) false, and stops again, and only then is
running set to true. I think it's safer to set the running field
_before_ actually starting the thread:
synchronized void start() {
if (running) {
throw new RuntimeException("Can't start a TimerQueue " +
"that is already running");
}
else {
final ThreadGroup threadGroup =
AppContext.getAppContext().getThreadGroup();
java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction() {
public Object run() {
Thread timerThread = new Thread(threadGroup,
TimerQueue.this,
"TimerQueue");
timerThread.setDaemon(true);
timerThread.setPriority(Thread.NORM_PRIORITY);
running = true;
timerThread.start();
return null;
}
});
}
}
What do you think?
/Roman
--
Dipl.-Inform. (FH) Roman Kennke, Software Engineer, http://kennke.org
aicas Allerton Interworks Computer Automated Systems GmbH
Haid-und-Neu-Straße 18 * D-76131 Karlsruhe * Germany
http://www.aicas.com * Tel: +49-721-663 968-48
USt-Id: DE216375633, Handelsregister HRB 109481, AG Karlsruhe
Geschäftsführer: Dr. James J. Hunt
More information about the swing-dev
mailing list