I am trying to find out time needed for thread creation and synchronization. I know that I should use ThreadMXBean, but I can't find simple example that demonstrate this using ThreadMXBean and Callable interface.
package teststckofw;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class TestStckOfw {
public static void main(String[] args) throws ExecutionException {
int i = 0;
int processed = 0;
while (i < 10) {
Parallel parallel1 = new Parallel();
Parallel parallel2 = new Parallel();
ExecutorService exec1 = Executors.newCachedThreadPool();
List<Callable<Integer>> tasks1 = new ArrayList<>();
try {
tasks1.add(parallel1);
tasks1.add(parallel2);
try {
List<Future<Integer>> futures = exec1.invokeAll(tasks1);
int flag = 0;
for (Future<Integer> f : futures) {
Integer res = f.get();
if (res != 0) {
processed = res;
}
if (!f.isDone()) {
flag = 1;
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
} finally {
exec1.shutdown();
}
i++;
}
}
/**************************************/
static class Parallel implements Callable<Integer> {
@Override
public Integer call() throws Exception {
int a = 2 + 2; // do something...
return a;
}
}
}
Edit: I need information for all threads during the long while loop with many iterations (much more than 10). Can I get summary information for all threads in all iterations by using thread dump?
Unless you want to know it out of curiosity, you may assume thread creation time is negligible, if you don't create excessive number of threads (that is, you use Executor
framework properly or do it by hand correctly).
Regarding time spent due to lock contention, it varies together with app load. Best way to get useful info is to take thread dumps while loading your app with a load you expect to support, and look for threads that are in BLOCKED state and for threads in RUNNABLE state. This way you'll get idea how good is your program regarding lock contention.