Sobes.tech
Junior — Middle

How are access control mechanisms implemented to prevent thread or process conflicts when sharing resources?

sobes.tech AI

Answer from AI

To prevent conflicts when accessing shared resources in multi-threaded or multi-process systems, synchronization mechanisms are used. The main ones include:

  • Mutexes (mutex) — ensure exclusive access to a resource by blocking other threads.
  • Semaphores — limit the number of threads that can work with a resource simultaneously.
  • Monitors and synchronized blocks in Java — simplify synchronization by automatically managing locks.
  • Atomic operations — ensure safe modification of variables without locks.

Example in Java using synchronized:

public class Counter {
    private int count = 0;

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

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

Here, synchronized methods guarantee that only one thread can modify or read the value of count at a time.