Open In App

Pessimistic Technique of Locking in Java with Examples

Improve
Improve
Like Article
Like
Save
Share
Report

Pessimistic locking is a technique used in concurrent programming to ensure that critical sections of code are executed atomically. It is called “Pessimistic” because it assumes that multiple threads will try to access the critical section and therefore lock it to prevent conflicts.

In Java, the synchronized keyword is used to create a Pessimistic lock. When a method is marked with the synchronized keyword, it can only be accessed by one thread at a time. If another thread tries to access the method while it is already being accessed by another thread, the second thread will be blocked until the first thread has finished executing the method.

Pessimistic locking can be useful in situations where multiple threads are likely to conflict with each other and it is important to ensure that critical sections of code are executed atomically. However, it can also lead to performance issues if it is used excessively, as it can cause threads to block and wait for locks to be released, leading to reduced concurrency.

It is important to carefully consider the trade-offs between Pessimistic locking and other approaches, such as optimistic locking or non-blocking synchronization, in order to choose the best approach for a given situation.

Pessimistic locking is used in concurrent programming to ensure that critical sections of code are executed atomically. This is important in situations where multiple threads may be accessing shared resources and it is necessary to prevent conflicts between them.

For Example:

Consider a bank account with a balance that can be accessed and modified by multiple threads. Without proper synchronization, it is possible for two threads to simultaneously read the balance, perform some operation on it, and write the new balance back to the account, leading to an incorrect final balance. Pessimistic locking can be used to prevent this type of conflict by ensuring that only one thread can access the critical section of code that modifies the balance at a time.

Pessimistic locking is also useful in situations where it is important to maintain the consistency of data or the integrity of a system. For example, a database may use Pessimistic locking to ensure that data is not modified in an inconsistent or inconsistent manner by multiple threads.

Overall, Pessimistic locking is a useful tool for ensuring the consistency and integrity of shared resources in concurrent programming, but it can also lead to performance issues if it is used excessively. It is important to carefully consider the trade-offs between Pessimistic locking and other approaches, such as optimistic locking or non-blocking synchronization, in order to choose the best approach for a given situation.

Here is a detailed example of how to use Pessimistic Locking in Java:

Java




class Counter {
    private int count = 0;
    public synchronized void increment() { count++; }
    public synchronized int getCount() { return count; }
}
  
class Main {
    public static void main(String[] args) {
        Counter counter = new Counter();
  
        Runnable task = () -> {
            for (int i = 0; i < 1000; i++) {
                counter.increment();
            }
        };
  
        Thread t1 = new Thread(task);
        Thread t2 = new Thread(task);
  
        t1.start();
        t2.start();
  
        try {
            t1.join();
            t2.join();
        }
        catch (InterruptedException e) {
            e.printStackTrace();
        }
  
        System.out.println("Final count: " + counter.getCount());
    }
}


Output

Final count: 2000

In this example, we have a Counter class with an increment method that increments a count by 1, and a getCount method that returns the current count. Both of these methods are marked with the synchronized keyword, which means that they can only be accessed by one thread at a time.

In the main method, we create two threads that run a task that increments the count 1000 times. We start both threads and then wait for them to finish using the join method.

When we run this program, the final count will be 2000, because both threads were able to increment the count 1000 times each. However, because the increment method is synchronized, only one thread was able to execute it at a time, which prevented any conflicts between the threads.



Last Updated : 01 Jan, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads