textbender.g.lang
Annotation Type ThreadSafe


@Documented
@Retention(value=RUNTIME)
@Target(value={CONSTRUCTOR,FIELD,METHOD,TYPE})
public @interface ThreadSafe

Indicates thread safety of fields, constructors and methods.

Access to thread-safe fields, and calls to thread-safe constructors and methods, will never put the program into an invalid state, regardless of how the runtime interleaves those actions, and without requiring any additional synchronization or coordination on the part of the caller.

The indication of thread safety applies to a field, constructor or method. It never applies to an object read from the field, or created by the constructor, or returned by the method. Thread-safe fields, constructors and methods are not constrained to dispense only thread-safe objects. The object's own thread safety is formally indicated by its own API.

The opposite of ThreadSafe is ThreadRestricted.

Fields

An unannotated field is assumed to be thread safe only if it is final.

Note that thread safety of access (read or write) to non-final fields is fundamentally limited by the language rules, particularly by its memory model (specification, 17). Strictly speaking, only certain types of volatile field (and their equivalents in java.util.concurrent.atomic) can be thread safe. All others are subject to read/write caching of their values, between synchronization points.

Constructors

An unannotated constructor is assumed to be thread safe.

Methods (and Types)

Annotation of a type (class or interface) specifies the default thread safety of its public methods. An unannotated public method aquires the annotation of its declaring type, or, failing that, its runtime object's type. Only methods have defaults; not fields or contructors.

A method's thread safety depends on the runtime type of the object on which it is called. To determine a method's thread safety:

  1. Look at the API of the runtime type (e.g. its javadoc page).
  2. Find the method and its thread-safety or thread-restriction annotation (this may take you to a supertype page).
    Or, if the method is unannotated:
  3. Find the annotation of the method's declaring type (top of that same page).
    Or, if that type is unannotated:
  4. If the object's runtime type is different, find its annotation (top of original page).
    Failing that, unless you know otherwise:
  5. Assume the method is not thread safe.

Or use ThreadSafe.U to perform these same tests at runtime.