If you are interviewing, consider buying our number#1 course for Java Multithreading Interviews.

Overview

In this lesson, we’ll explore the various Java annotations that are related to concurrency. These are:

  1. @ThreadSafe
  2. @NotThreadSafe
  3. @Immutable
  4. @GuardedBy(lock)

Class-level annotations

Note that these annotations serve as documentation about class behavior but don’t change the ability or functionality of class in any way. Also, these class-level annotations become part of the public documentation of a class.

@ThreadSafe

The annotation @ThreadSafe can be applied to a class to indicate to users and maintainers that the class is thread safe and multiple threads can concurrently interact with an instance of the class without worrying about synchronization. Newbies should not confuse the annotation to mean that it makes a class thread safe. The annotation only serves as documentation.

@NotThreadSafe

The @NotThreadSafe annotation is the opposite of @ThreadSafe and is intended to explicitly communicate to the users and maintainers that the class requires synchronization effort on part of the users to ensure thread-safe concurrent access to instances of the class.

@Immutable

The @Immutable annotation indicates that once an object of the class is instantiated, it can’t be changed. All operations on such an instance of the class become read-only operations and consequently the class becomes thread safe. In other words, @Immutable implies @ThreadSafe. The String class is, perhaps, the most well-known Java immutable class. Other examples include wrapper classes such as Integer, Byte, Short, and Boolean` Java classes.

Field and method-level annotations

Unlike class-level annotations the field and method-level annotations don’t appear in the public documentation of a class and are targeted towards informing the maintainers and extenders of a class.

@GuardedBy(lock)

The annotation @GuardedBy(lock) can be used to document that a certain field or method should only be accessed while holding the lock argument in the annotation. The lock argument passed-in to the annotation can take-on different values which we’ll discuss below:

Consider the class AnnotationsExampleClass in the widget below:

Create a free account to view this lesson.

By signing up, you agree to Educative's Terms of Service and Privacy Policy