java synchronization tutorial part 1 the problems of unsynchronized code

In Java, the concept of synchronization is used to prevent multiple threads from accessing the same data at the same time, which can lead to inconsistent or incorrect results. When two or more threads are accessing a shared resource at the same time, it is possible for one thread to modify the resource while another thread is in the process of reading or modifying it, which can lead to unpredictable behavior.

Here's an example of a problem that can occur when multiple threads access a shared resource:

refer to:‮editfigi‬a.com
class UnsynchronizedCounter {
    private int count = 0;

    public void increment() {
        count++;
    }

    public int getCount() {
        return count;
    }
}

class UnsynchronizedCounterTest {
    public static void main(String[] args) throws InterruptedException {
        UnsynchronizedCounter counter = new UnsynchronizedCounter();
        for (int i = 0; i < 1000; i++) {
            new Thread(() -> {
                counter.increment();
            }).start();
        }
        Thread.sleep(1000);
        System.out.println("Final count: " + counter.getCount());
    }
}

In this example, we have a simple UnsynchronizedCounter class with two methods: increment() and getCount(). The increment() method simply increments the count variable by 1, while the getCount() method returns the current value of count.

In the UnsynchronizedCounterTest class, we create a new instance of UnsynchronizedCounter and then start 1000 threads, each of which calls the increment() method on the counter object. Finally, we wait for one second and then print the final value of count.

If we run this code, we might expect the final value of count to be 1000, since we started 1000 threads and each thread called the increment() method once. However, because the code is not synchronized, it is possible for multiple threads to access the count variable at the same time, which can lead to unpredictable results.

In fact, when we run this code, we may see that the final value of count is less than 1000, because some of the threads are overwriting each other's updates to the count variable. This is because multiple threads can be reading and writing to the count variable at the same time, which can lead to inconsistent or incorrect results.

To solve this problem, we need to add synchronization to the increment() and getCount() methods, to ensure that only one thread can access the count variable at a time. We'll explore how to do this in the next part of this tutorial.