Name: rl43681 Date: 04/18/2003
A DESCRIPTION OF THE PROBLEM :
In documentation, there is written (copy of this text is in EditBox bellow) that class SerialNum should return specific value for each thread. But it's returned only 0 (how expected, if you read the code of this class:-)). Problem is, that this class can't have "static" instance of ThreadLocal, because this class (which is actually called in method SerialNum.get()) remember only 0. If you want to correct this example, the method SerialNum.get() and attribute SerialNum.serialnum can't be static and each thread must create new instance of class SerialNum (There is one more bug in this class, this class has only static methods, so it has probably also private default constructor to nobody can make instance of this class - but it's not so important)
EXPECTED VERSUS ACTUAL BEHAVIOR :
some other example which works:-) but for e.g. this(but it's not good example, because the same functionality can be probably done easier without using class ThreadLocal)
my correction:
For example, in the class below, the private ThreadLocal instance (serialNum) maintains a "serial number" for each thread that creates an instance of class SerialNum and invokes the instance's SerialNum.get() method, which returns the current thread's serial number. (A thread's serial number is assigned the first time it invokes SerialNum.get(), and remains unchanged on subsequent calls.)
public class SerialNum {
// The next serial number to be assigned
private static int nextSerialNum = 0;
private ThreadLocal serialNum = new ThreadLocal() {
protected synchronized Object initialValue() {
return new Integer(nextSerialNum++);
}
};
public int get() {
return ((Integer) (serialNum.get())).intValue();
}
}
For example, in the class below, the private static ThreadLocal instance (serialNum) maintains a "serial number" for each thread that invokes the class's static SerialNum.get() method, which returns the current thread's serial number. (A thread's serial number is assigned the first time it invokes SerialNum.get(), and remains unchanged on subsequent calls.)
public class SerialNum {
// The next serial number to be assigned
private static int nextSerialNum = 0;
private static ThreadLocal serialNum = new ThreadLocal() {
protected synchronized Object initialValue() {
return new Integer(nextSerialNum++);
}
};
public static int get() {
return ((Integer) (serialNum.get())).intValue();
}
}
URL OF FAULTY DOCUMENTATION :
http://java.sun.com/j2se/1.4.2/docs/api/java/lang/ThreadLocal.html
(Review ID: 184093)
======================================================================