Name: rmT116609 Date: 10/10/2000
java version "1.3.0"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.3.0-C)
Java HotSpot(TM) Client VM (build 1.3.0-C, mixed mode)
Compile and run following program on a dual processor machine:
import java.math.*;
public class ReadersAndWriters {
public static void main (String args[]) {
ReadersAndWriters tester = new ReadersAndWriters();
tester.test();
}
public ReadersAndWriters() {
customers = new Customer [NUM_CUSTOMERS] ;
threadGroup = new ThreadGroup("My threads");
for (int i = 0; customers.length > i; i++) {
customers[i] = new Customer(threadGroup);
}
}
public void test() {
for (int i = 0; customers.length > i; i++) {
customers[i].start();
}
threadGroup.interrupt();
while (0 < threadGroup.activeCount()) {
Thread.yield();
}
}
private Customer [] customers;
private ThreadGroup threadGroup;
private static final int NUM_CUSTOMERS = 15;
private class Customer extends Thread {
public Customer(ThreadGroup threadGroup) {
super(threadGroup, "Customer ");
}
public void run() {
while (!isInterrupted()) {
int seatNumber = new NumberAux().randomInteger();
}
}
private class NumberAux {
public int randomInteger () {
return Math.abs(10);
}
}
}
}
Following exception is thrown from one or more threads:
java.lang.InterruptedException
at ReadersAndWriters$Customer$NumberAux.randomInteger
(ReadersAndWriters.java:57)
at ReadersAndWriters$Customer.run(ReadersAndWriters.java:50)
Notes:
1. The test was carried out on a "Dell Precision 610" with two 500MHz Pentiums.
The problem occurs almost always, but the number of threads that crash can
change. The problem frequency was reduced when one processor was blocked.
2. The problem did not occur so readily on a machine with one 233MHz processor.
It happened only after a "Thread.yield()" was added before the
threadGroup.interrupt() and the number of threads were increased to 50. Even
then the test had to be carried out many times.
3. The problem was originally noticed in a larger program and parts of it were
stripped to provide a simpler case. The interrupt is always thrown in the Math
library call. (Different functions such as "random", "sin", "abs" were tried.)
Further reduction (E.g. removal of the inner class "NumberAux".) seems to hide
the problem.
4. My guess is that this happens when a recently started thread
is "interrupted" "too soon", i.e. before VM had a chance to do some
housekeeping. This is because the problem disappears when there is a sleep
before interrupt. Similar behaviour was noticed in the original program. The
other possibility is that Math static functions are not thread safe.
5. The downside is that this interruption leaves the thread objects data in an
indeterminate state. Also it is not allowed to catch the exception unless we
deliberately have a statement can legally throw the exception.
(Review ID: 110128)
======================================================================