In a multi-threaded application, a mutex (short for "mutual exclusion") is a synchronization construct that is used to prevent multiple threads from accessing a shared resource at the same time. A mutex provides a way to protect critical sections of code from simultaneous access by multiple threads, which can lead to resource conflicts and data corruption.
A mutex works by allowing a thread to acquire a lock on a resource before accessing it, and requiring other threads to wait until the lock is released before they can access the resource. When a thread is finished using the resource, it releases the lock to allow other threads to acquire it.
Here’s an example of how a mutex can be used in Java:
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class MutexExample {
private static Lock lock = new ReentrantLock();
public static void main(String[] args) {
Thread thread1 = new Thread(() -> {
lock.lock();
System.out.println("Thread 1 acquired lock");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
lock.unlock();
System.out.println("Thread 1 released lock");
});
Thread thread2 = new Thread(() -> {
lock.lock();
System.out.println("Thread 2 acquired lock");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
lock.unlock();
System.out.println("Thread 2 released lock");
});
thread1.start();
thread2.start();
}
}
In this example, we define a ReentrantLock object that is used as a mutex to protect a critical section of code. We then define two threads that try to acquire the lock on the mutex. When a thread acquires the lock, it prints a message to indicate that it has acquired the lock, sleeps for 1 second, and then releases the lock.
The output of this program will show that only one thread can acquire the lock on the mutex at any given time. When one thread acquires the lock, the other thread will wait until the lock is released before it can acquire the lock.
Overall, a mutex is an important tool for preventing resource conflicts and data corruption in a multi-threaded application. By providing a way to protect critical sections of code, a mutex ensures that threads can access shared resources safely and efficiently.