
Signature
Knute Johnson
email s/nospam/knute/
...
> public void run() {
> while (true) {
[quoted text clipped - 4 lines]
>
> if (!runFlag) {
**** Point A ***** (see below)
> synchronized (lock) {
> try {
[quoted text clipped - 7 lines]
> }
> }
...
> b.addActionListener(new ActionListener() {
> public void actionPerformed(ActionEvent ae) {
[quoted text clipped - 4 lines]
> }
> });
...
There is a low probability bug in this code. Suppose a worker thread T
runs to Point A, and then gets interrupted. Before T's next time slice,
the event handler thread E runs, and completely executes the
actionPerformed method.
This is possible, because T is not synchronized on lock at point A.
When T gets its next timeslice, it goes into a wait on the lock, without
having checked runFlag since it was changed by E. T is then stuck
waiting for a condition that has already happened.
The following modified version of the program demonstrates this. I have
added some output statements and one sleep, but not changed the
operations on lock or runFlag. To see the effect, click on the "GO"
button less than 10 seconds after clicking "Stop", and then watch for at
least 10 seconds. Changing the length of the added sleep call changes
that time limit.
In the original program the bug is low probability, because each thread
spends most of its time sleeping, and reaches point A very soon after
the start of its first time slice after coming out of a sleep, a period
when it is unlikely to be interrupted. The need for human interaction in
the critical window reduces the number of tests that can be done, as
well as reducing the probability of failure.
However, it should not be used as a pattern for writing multi-threaded
code. In a different context it this structure could have an annoyingly
high failure rate.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class test8 implements Runnable {
static volatile boolean runFlag = true; // only one of these
int name;
static Object lock = new Object(); // only one of these too
public test8(int name) {
this.name = name;
new Thread(this).start(); // start thread when created
}
public void run() {
while (true) {
System.out.println(name);
try {
Thread.sleep(1000);
} catch (InterruptedException ie) {
}
if (!runFlag) {
try {
Thread.sleep(10000);
} catch (InterruptedException ie) {
}
System.err.printf(
"Thread %s waiting for runFlag true%n", name);
synchronized (lock) {
try {
lock.wait();
} catch (InterruptedException ie) {
// wait is interruptible
ie.printStackTrace();
}
}
System.err.printf("Thread %s restarted%n", name);
}
}
}
public static void main(String[] args) {
Runnable r = new Runnable() {
public void run() {
// make 8 test8s and name them 0 - 7
for (int i = 0; i < 8; i++) {
new test8(i);
}
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLayout(new FlowLayout());
JButton b = new JButton("Stop");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
runFlag = false;
System.out.println();
}
});
f.add(b);
b = new JButton(" GO ");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
runFlag = true; // so it will run again
synchronized (lock) {
lock.notifyAll();
}
System.err.printf("Threads restarted%n");
}
});
f.add(b);
f.pack();
f.setVisible(true);
}
};
EventQueue.invokeLater(r);
}
}
repairman2003@gmail.com - 07 Mar 2007 22:54 GMT
Thank you very much! I never really got concurrency down pact during
school but this helped out alot. All the tutorials I found on
concurrency really weren't too much of a help, just needed an example
of how to use it in my own problem. Cheers!
Knute Johnson - 08 Mar 2007 07:58 GMT
> There is a low probability bug in this code. Suppose a worker thread T
> runs to Point A, and then gets interrupted. Before T's next time slice,
[quoted text clipped - 24 lines]
> code. In a different context it this structure could have an annoyingly
> high failure rate.
Patricia:
Your right! That was stupid on my part. The flag check should have
been in the synchronized block to prevent just that sort of thing from
happening. That will teach me for getting in a hurry.
For the OP, timing is always an issue with wait/notify. If you call
notify before wait, the waiting threads may wait for ever.
For your problem I like the semaphore solution better anyway. See the
second example.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class test8 implements Runnable {
int name;
static boolean runFlag = true; // only one of these
static Object lock = new Object(); // only one of these too
public test8(int name) {
this.name = name;
new Thread(this).start();
}
public void run() {
while (true) {
System.out.println(name);
synchronized (lock) {
if (!runFlag) {
try {
lock.wait();
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
}
}
}
public static void main(String[] args) {
Runnable r = new Runnable() {
public void run() {
for (int i=0; i<8; i++) {
new test8(i);
}
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLayout(new FlowLayout());
JButton b = new JButton("Stop");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
synchronized (lock) {
runFlag = false;
}
}
});
f.add(b);
b = new JButton(" GO ");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
synchronized (lock) {
runFlag = true;
lock.notifyAll();
}
}
});
f.add(b);
f.pack();
f.setVisible(true);
}
};
EventQueue.invokeLater(r);
}
}
import java.awt.*;
import java.awt.event.*;
import java.util.concurrent.*;
import javax.swing.*;
public class test7 implements Runnable {
int name;
static Semaphore sem = new Semaphore(8,true);
public test7(int name) {
this.name = name;
new Thread(this).start();
}
public void run() {
while (true) {
sem.acquireUninterruptibly(1);
// normal thread processing here
System.out.println(name);
sem.release(1);
}
}
public static void main(String[] args) {
Runnable r = new Runnable() {
public void run() {
for (int i=0; i<8; i++) {
new test7(i);
}
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLayout(new FlowLayout());
JButton b = new JButton("Stop");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if (ae.getActionCommand().equals("Stop")) {
sem.acquireUninterruptibly(8);
((JButton)ae.getSource()).setText(" GO ");
} else {
sem.release(8);
((JButton)ae.getSource()).setText("Stop");
}
}
});
f.add(b);
f.pack();
f.setVisible(true);
}
};
EventQueue.invokeLater(r);
}
}

Signature
Knute Johnson
email s/nospam/knute/