Java Reference
In-Depth Information
herently thread-safe; once they are fully constructed, they may be published via a referen-
ce and shared safely among multiple threads.
The following example shows an immutable
Point
class:
@Immutable
public final class Point {
private final int f_x;
private final int f_y;
public Point(int x, int y) {
f_x = x;
f_y = y;
}
public int getX() {
return f_x;
}
public int getY() {
return f_y;
}
}
According to Joshua Bloch [Bloch 2008],
It is not necessary to document the immutability of
enum
types. Unless it is obvious
from the return type, static factories must document the thread safety of the returned
object, as demonstrated by
Collections.synchronizedMap
.
The
@NotThreadSafe
annotation is applied to classes that are not thread-safe. Many
classes fail to document whether they are safe for multithreaded use. Consequently, a pro-
grammer has no easy way to determine whether the class is thread-safe. This annotation
provides clear indication of the class's lack of thread-safety.
For example, most of the collection implementations provided in
java.util
are not
thread-safe. The class
java.util.ArrayList
could document this as follows:
package java.util.ArrayList;