for(int ii = 0; ii < 3; ii++)
executor.execute(new someClass);
vs
someFunction();
someFunction();
someFunction();
where
public static void someFunction(){
synchronized(lock){
for(int ii = 0; ii < long.MAX_VALUE; ii++);
}
}
private class someClass implements Runnable {
public void run() {
someFunction(); //someFunction() is a synchronized function
}
}
Sorry if this may be a rather vague question. I have a synchronized someFunction() that I want to call 3 times sequentially and another time with 3 threads where each one runs the task of someFunction(). Since, it is synchronized, only 1 thread can access at time, the speed difference is almost the same with 3 threads vs 1 thread. I’m also not allowed to modify or unsynchronized someFunction(). I was wondering if there is any way to speed it up the mult-threaded way from how I am using the threads? Maybe through how the threads queue or something? Thanks for any help.
No. There is no way to run a synchronized method (on the same object) more than once at the same time. That is kind of the point of the synchronized keyword.
Synchronization can become a performance bottleneck, but the only way to reduce that is to reduce the amount of work that needs to be done in those critical sections. Often code is overly conservative, and maybe not everything needs to be in that synchronized block. But this is something that requires a deep understanding and rewriting of the code, nothing that you can just tune via some magic setting (and if you remove too much synchronization, you might break things; getting multi-threaded code right is difficult).