Daily Archives: May 25, 2024

Java ParallelStream


import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

public class ParallelStreamTest {
    public static void main(String[] args) {
        List<BigInteger> integers = new ArrayList<>();
// fill data
        integers.add(new BigInteger("134123124325234234"));
        integers.add(new BigInteger("1341231243252"));
        integers.add(new BigInteger("134123124325234234"));
        integers.add(new BigInteger("134123124325234234"));
        integers.add(new BigInteger("134123124"));
        integers.add(new BigInteger("134123124"));
        integers.add(new BigInteger("134123124"));
        integers.add(new BigInteger("134123124"));
        integers.add(new BigInteger("134123124"));

        BigInteger result = integers.parallelStream()
                .reduce(BigInteger.ONE, (a, e) -> a.multiply(e));
        System.out.println(result);

    }
}

synchronized locks

synchronized locks all methods in one object
These are both methods of the same object, and both are marked as synchronized. If even one method is being executed, all other synchronized methods of the same object become inaccessible to other threads

public class Main {
    public static void main(String [] args) {
        SharedClass sharedObject = new SharedClass();
 
        Thread thread1 = new Thread(() -> {
            while (true) {
                sharedObject.increment();
            }
        });
 
        Thread thread2 = new Thread(() -> {
            while (true) {
                sharedObject.decrement();
            }
        });
 
        thread1.start();
        thread2.start();
    }
 
    static class SharedClass {
        private int counter = 0;
 
        public synchronized void increment() {
            this.counter++;
        }
 
        public synchronized void decrement() {
            this.counter--;
        }
    }
}

synchronized lock different object
thread could execute both critical sections at same time.

public class Main {
    public static void main(String [] args) {
        SharedClass sharedObject = new SharedClass();
 
        Thread thread1 = new Thread(() -> {
            while (true) {
                sharedObject.incrementCounter1();
            }
        });
 
        Thread thread2 = new Thread(() -> {
            while (true) {
                sharedObject.incrementCounter2();
            }
        });
 
        thread1.start();
        thread2.start();
    }
 
    static class SharedClass {
        private int counter1 = 0;
        private int counter2 = 0;
 
        private Object lock1 = new Object();
        private Object lock2 = new Object();
 
        public void incrementCounter1() {
            synchronized (lock1) {
                this.counter1++;
            }
        }
 
        public void incrementCounter2() {
            synchronized (lock2) {
                this.counter2++;
            }
        }
    }
}