Java Multithreading: Synchronizing Access to Shared Resources

light2

Recruit
I'm working on a Java multithreading project where multiple threads need to access and modify a shared resource. I've encountered synchronization issues and need guidance on how to ensure thread safety. Here's a simplified version of my code:

Java:
public class SharedResource {
    private int value = 0;

    public int getValue() {
        return value;
    }

    public void increment() {
        value++;
    }
}

public class MyThread extends Thread {
    private SharedResource sharedResource;

    public MyThread(SharedResource sharedResource) {
        this.sharedResource = sharedResource;
    }

    @Override
    public void run() {
        for (int i = 0; i < 1000; i++) {
            sharedResource.increment();
        }
    }
}

public class Main {
    public static void main(String[] args) {
        SharedResource sharedResource = new SharedResource();
        MyThread thread1 = new MyThread(sharedResource);
        MyThread thread2 = new MyThread(sharedResource);

        thread1.start();
        thread2.start();

        // Wait for both threads to finish
        try {
            thread1.join();
            thread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("Final value: " + sharedResource.getValue());
    }
}

In this code, two threads (thread1 and thread2) are concurrently incrementing a shared value in the SharedResource class. However, I'm experiencing unexpected results due to race conditions.

How can I modify this code to ensure that access to the increment method is synchronized, preventing race conditions and guaranteeing the correct final value of value? Please provide a Java code example with explanations for achieving thread safety in this scenario. Thank you for your assistance!
 
There are multiple ways to prevent other threads from accessing data/methods/functions, when a thread is working on it. For instance, you can make the increment() block 'synchronized' by adding the modifier. Try,
Java:
public synchronized void increment() {
    value++;
}

To learn about other ways read up on 'Locking mechanisms in Java'.

Edit- I now realise that searching "Locking mechanisms in Java' on seems to show about the Lock interface. But as others have added, there are multiple ways that basically achieve this. I suggest reading about all of them, as one approach may have an advantage over the other depending on the application and structure of your code.
 
Last edited:
Back
Top