Synchronization of two methods which work on a List in Multi Thread Env without ConcurrentCollection
- rajasrikarraoj2ee
- Feb 14, 2021
- 1 min read
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
public class SynchronousListItems {
public static void main(String[] args) {
List<Item> items = new ArrayList<>();
CountDownLatch creatorLatch = new CountDownLatch(1);
CountDownLatch sumLatch = new CountDownLatch(1);
int numberOfItemsToCreate = 100;
Thread createrThread = new Thread(new Creator(items, creatorLatch, numberOfItemsToCreate));
createrThread.setDaemon(true);
Sum sumObj = new Sum(items, sumLatch);
Thread sumThread = new Thread(sumObj);
sumThread.setDaemon(true);
createrThread.start();
sumThread.start();
try {
creatorLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
sumObj.setStopSignal(true);
}
try {
sumLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class Creator implements Runnable {
private List<Item> items;
private CountDownLatch creatorLatch;
private int numberOfItemsToCreate;
public Creator(List<Item> items, CountDownLatch creatorLatch, int numberOfItemsToCreate) {
this.items = items;
this.creatorLatch = creatorLatch;
this.numberOfItemsToCreate = numberOfItemsToCreate;
}
@Override
public void run() {
Random random = new Random(10L);
while (numberOfItemsToCreate > 0) {
int wage = random.nextInt();
System.out.println(wage);
items.add(new Item(wage));
numberOfItemsToCreate--;
}
creatorLatch.countDown();
}
}
class Item {
private int wage;
public Item(int wage) {
this.wage = wage;
}
public int getWage() {
return wage;
}
}
class Sum implements Runnable {
private boolean stopSignal;
private List<Item> items;
private int total;
private int itemsCounter;
private CountDownLatch sumLatch;
public Sum(List<Item> items, CountDownLatch sumLatch) {
this.items = items;
this.sumLatch = sumLatch;
}
@Override
public void run() {
try {
while (!stopSignal) {
if (items != null && !items.isEmpty() && items.size() > itemsCounter) {
System.out.println("Itemes are not empty");
System.out.println("Itemes Counter " + itemsCounter);
while (itemsCounter < items.size()) {
Item item = items.get(itemsCounter);
System.out.println("Item Pulled");
total = total + item.getWage();
itemsCounter++;
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println("Final Items Counter :" + itemsCounter);
System.out.println("Total :" + total);
sumLatch.countDown();
}
}
public void setStopSignal(boolean stopSignal) {
this.stopSignal = stopSignal;
}
}


Comments