I'm doing some benchmarking in Java with thread pool and HashMap. I've a HashMap containing KVPs (let say 5000) and I created a thread pool having fixed Size(let say 5).
Now for each thread, I'm performing put operation on HashMap twice in synchronization block and calculating the Avg time taken by each thread. However, when I'm increasing the put operation on HashMap the Avg time taken by each thread is decreasing, which should not be the case.
Here is my code snippet.
class WorkerThread3 implements Runnable {
public static double sum;
public static int threadPoolSize = 0;
public static int operationSize = 0;
public static int childHashMapSize = 0;
public static int delay = 2;
public static HashMap<String, SiGenesysLockApp3> childHashMap = new HashMap<>();
public WorkerThread3() {
}
public void run() {
processmessage();
}
private void processmessage() {
long time = 0;
double mseconds = 0;
try {
Thread.sleep(WorkerThread3.delay);
} catch (Exception e) {
}
for (int j = 0; j < WorkerThread3.operationSize; j++) {
long startTime = System.nanoTime();
try {
synchronized (childHashMap) {
childHashMap.put(Thread.currentThread().getName() + j, new SiGenesysLockApp3());
}
long stopTime = System.nanoTime();
time += (stopTime - startTime);
Thread.sleep(WorkerThread3.delay);
} catch (Exception e) {
}
}
mseconds = (double) time / 1_000_000.0;
System.out.println(Thread.currentThread().getName() + " avg elapsed: " + mseconds / WorkerThread3.operationSize);
}
// childHashMap
void initChildMap(int size, HashMap<String, SiGenesysLockApp3> childHashMap) {
for (int i = 0; i < size; i++) {
childHashMap.put("key" + i, new SiGenesysLockApp3());
}
}
}
For example.
- Init HashMap with 5000 KVPs
- Thread pool size: 5
- Operation size: 2
pool-1-thread-1 Avg time (mili seconds) 25.032314
pool-1-thread-2 Avg time (mili seconds) 29.8605755
pool-1-thread-3 Avg time (mili seconds) 22.4244215
pool-1-thread-4 Avg time (mili seconds) 22.725929
pool-1-thread-5 Avg time (mili seconds) 21.2752405
- Init HashMap with 5000 KVPs
- Thread pool size: 5
- Operation size: 2000
pool-1-thread-4 Avg time (mili seconds) 0.0361571885
pool-1-thread-1 Avg time (mili seconds) 0.041867667500000004
pool-1-thread-2 Avg time (mili seconds) 0.0383657525
pool-1-thread-3 Avg time (mili seconds) 0.041476348999999996
pool-1-thread-5 Avg time (mili seconds) 0.032176814