#could you explain what this code is doing in terms of implementing the problem in the picture?

1 messages · Page 1 of 1 (latest)

halcyon hull
#

like what is the logic is

unborn quailBOT
#

<@&987246399047479336> please have a look, thanks.

halcyon hull
#
 
    private int count = 0;  
 
   
 
    public int getCount() {  
 
        return count;  
 
    }  
 
   
 
    public void increment() {  
 
        count++;  
 
    }  
 
   
 
    //The synchronized keyword makes this method thread-safe.  
 
    public synchronized void synchronizedIncrement() {  
 
        count++;  
 
    }  
 
   
 
   
 
    public void brokenIncrement() {  
 
        int temp = count; // Read  
 
        count = temp + 1; // Write  
 
    }  
 
   
 
    public void betterIncrement() {  
 
        count++;  
 
    }  
 
} ```
#
 
   
 
    public static void main(String[] args) throws InterruptedException {  
 
        int numThreads = 1000;  
 
        int numIncrements = 1000;  
 
   
 
        // Example 1: Demonstrating the race condition with brokenIncrement()  
 
        Counter counter1 = new Counter();  
 
        Thread[] threads1 = new Thread[numThreads];  
 
   
 
        for (int i = 0; i < numThreads; i++) {  
 
            threads1[i] = new Thread(() -> {  
 
                for (int j = 0; j < numIncrements; j++) {  
 
                    counter1.brokenIncrement();  
 
                }  
 
            });  
 
            threads1[i].start();  
 
        }  
 
   
 
        for (Thread thread : threads1) {  
 
            thread.join(); // Wait for all threads to finish  
 
        }  
 
   
 
        System.out.println("Race Condition Example (brokenIncrement): Expected: " + (numThreads * numIncrements) + ", Actual: " + counter1.getCount());```
#
 
        Counter counter2 = new Counter();  
 
        Thread[] threads2 = new Thread[numThreads];  
 
   
 
        for (int i = 0; i < numThreads; i++) {  
 
            threads2[i] = new Thread(() -> {  
 
                for (int j = 0; j < numIncrements; j++) {  
 
                    counter2.synchronizedIncrement();  
 
                }  
 
            });  
 
            threads2[i].start();  
 
        }  
 
   
 
        for (Thread thread : threads2) {  
 
            thread.join();  
 
        }  
 
   
 
        System.out.println("Synchronized Example: Expected: " + (numThreads * numIncrements) + ", Actual: " + counter2.getCount()); 

// Example 3: Showing a correct implementation with betterIncrement() (atomic)  
 
        Counter counter3 = new Counter();  
 
        Thread[] threads3 = new Thread[numThreads];  
 
   
 
        for (int i = 0; i < numThreads; i++) {  
 
            threads3[i] = new Thread(() -> {  
 
                for (int j = 0; j < numIncrements; j++) {  
 
                    counter3.betterIncrement();  
 
                }  
 
            });  
 
            threads3[i].start();  
 
        }  
 
   
 
        for (Thread thread : threads3) {  
 
            thread.join();  
 
        }  
 
   
 
        System.out.println("Atomic Example: Expected: " + (numThreads * numIncrements) + ", Actual: " + counter3.getCount());  
 
   
 
    }  
 
}```
#

^thats all one code, discord was saying it is too long to be in one block]

shy perch
# halcyon hull like what is the logic is

it is trying to illustrate what happens when you access a variable concurrently from multiple threads, assuming the objective is to increment private int count = 0; 1000000 times

the 1st example launches 1000 threads and just lets all of them call brokenIncrement() at once, which results in a race condition because 2 threads might read the same variable at the same time and overwrite each other's attempted increment like t1: read t2: read t1: increment and write t2: increment and write so you egt something like 997908 increments instead of 100K every single time

2nd example makes the code meet the objective by wrapping the increment in a synchronized block

3rd example doesn't seem complete but it's hinting at using java.util.concurrent.atomic.AtomicInteger https://www.baeldung.com/java-atomic-variables with thread-safe methods like incrementAndGet()

Baeldung

Learn how to use atomic variables for solving concurrency issues.