Sobes.tech
Junior — Middle

How is thread safety ensured when using static methods?

sobes.tech AI

Answer from AI

Thread safety of static methods in Java is not guaranteed automatically, since a static method is simply a method associated with a class, not an instance. If a static method modifies shared (static) data, synchronization must be ensured manually.

To do this, you can use:

  • The synchronized keyword for the method or a block of code within the method to ensure exclusive access.
  • Thread-safe data structures (e.g., ConcurrentHashMap).
  • Immutable objects to avoid state changes by multiple threads.

Example of synchronizing a static method:

public class Counter {
    private static int count = 0;

    public static synchronized void increment() {
        count++;
    }

    public static int getCount() {
        return count;
    }
}

Here, increment is thread-safe because the method is synchronized.