Sobes.tech
Junior

What is thread safety?

sobes.tech AI

Answer from AI

Thread safety is a property of code that guarantees its correct execution when multiple threads access shared resources concurrently.

Main aspects:

  • Atomicity of operations: Guarantee that an operation is completed fully or not at all.
  • Visibility: Changes made by one thread are visible to other threads.
  • Ordering: Guarantee of a certain order of operation execution between threads.

To achieve thread safety in Java, the following are used:

  • synchronized keyword: For synchronizing blocks of code or methods, ensuring locking on an object.
    class Counter {
        private int count = 0;
    
        public synchronized void increment() {
            count++;
        }
    
        public synchronized int getCount() {
            return count;
        }
    }
    
  • volatile: To ensure visibility of a variable between threads, but not atomicity of operations.
    class SharedResource {
        public volatile boolean flag = false;
    
        public void setFlag() {
            flag = true; // Changes will be visible to other threads
        }
    }
    
  • Classes from the java.util.concurrent package: Provide thread-safe collections, atomic variables, task executors, and other tools.
    import java.util.concurrent.atomic.AtomicInteger;
    
    class AtomicCounter {
        private AtomicInteger count = new AtomicInteger(0);
    
        public void increment() {
            count.incrementAndGet(); // Atomic operation
        }
    
        public int getCount() {
            return count.get();
        }
    }
    
  • Immutability: Creating objects whose state cannot be changed after creation. Such objects are inherently thread-safe.

Violations of thread safety can lead to issues such as race conditions, deadlocks, and livelocks.

What is thread safety? — Java - sobes.tech