I run into this problem most of the times but don't know how to resolve it. The following code works fine, runs on a quad core processor. Almost every thread in my code will execute changeMember()
. Thread waits till another thread completes write (and releases lock).
public class Helper {
private static SomeObject obj;
private static final Object mutex = new Object();
public static void changeMember() {
// This is a bottleneck in my code. Many threads try to access it but only one can edit it.
synchronized (mutex) {
// ONLY the write method to obj is locked
obj.changeValue();
}
// Some other code
}
}
Is there a way to increase the performance of the code?
Some related links: