Skip to content

Instantly share code, notes, and snippets.

@rozaydin
Created March 12, 2020 07:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rozaydin/b5e246e570596ff16b7d6e642e9e5b0f to your computer and use it in GitHub Desktop.
Save rozaydin/b5e246e570596ff16b7d6e642e9e5b0f to your computer and use it in GitHub Desktop.
Hazelcast Demo
import java.util.HashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.IntStream;
public class HashMapRacer {
//
private final HashMap<String, Long> raceTrack;
private final ExecutorService execService;
private final String SHARED_KEY = "SUM";
//
private final int threadPoolSize;
private final int taskRepetitionCount;
//
private AtomicLong totalTaskExecutionCount;
public HashMapRacer(final int threadCount, final int taskRepetitionCount) {
this.raceTrack = new HashMap<>();
this.raceTrack.put(SHARED_KEY, 0L);
// init racers
this.threadPoolSize = threadCount;
this.taskRepetitionCount = taskRepetitionCount;
execService = Executors.newFixedThreadPool(threadCount);
}
public void initRacers() {
this.totalTaskExecutionCount = new AtomicLong(0L);
//
IntStream.range(0, this.threadPoolSize).forEach((int index) -> {
execService.execute(() -> {
for (int i = 0; i < taskRepetitionCount; i++) {
long sum = raceTrack.get(SHARED_KEY);
System.out.println("SUM value updated! [Thread: " + Thread.currentThread().getName() + " ]" + " sum -> " + sum + " sum+1 -> " + (sum + 1));
raceTrack.put(SHARED_KEY, (sum + 1));
//
totalTaskExecutionCount.incrementAndGet();
}
});
});
}
public void completeDemo() throws InterruptedException {
execService.shutdown();
this.execService.awaitTermination(10, TimeUnit.SECONDS);
//
System.out.println("Demo Completed");
final long sum = raceTrack.get(SHARED_KEY);
final long expectedSum = (this.threadPoolSize * this.taskRepetitionCount);
System.out.println( "[ SUM: " + sum + " ]" + " [ Expected Sum: " + expectedSum + " ] " + " [ Total Task Exec Count: " + totalTaskExecutionCount.get() + " ]");
totalTaskExecutionCount.set(0L);
}
public static void main(String[] args) throws Exception {
//
final int threadCount = 9;
final int taskRepetitionCount = 100;
//
HashMapRacer demo = new HashMapRacer(threadCount, taskRepetitionCount);
demo.initRacers();
demo.completeDemo();
}
}
class SharedObject {
private static final Object LOCK = new Object();
private static Object o = null;
public static Object retrieve() {
if (o == null) {
synchronized (LOCK) {
// double checked locking
if (o == null) {
o = create();
}
}
}
return o;
}
private static Object create() {
// mock implementation, would actually return a useful object
return new Object();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment