0

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:

bcsb1001
  • 2,834
  • 3
  • 24
  • 35
matuda
  • 195
  • 2
  • 16
  • 7
    Without knowing anything about what `changeValue()` does: NO. Since the primary purpose of `synchronized` is to grant exclusive access and that’s the only thing of your code you have shown, we have to assume that this is exactly what you want, hence unavoidable. – Holger Jun 16 '16 at 18:14
  • 1
    There are the various Atomic classes -- AtomicInteger, etc. You could use those to do a compare-and-set. But that requires that all of the state can be encoded in a single thing; and more importantly, if there's high contention then it could well be _slower_, since it means threads will have to retry their actions rather than just politely waiting in a line. – yshavit Jun 16 '16 at 18:19
  • Re, "ONLY the write method to obj is locked." That's could be a mistake. If `obj.changeValue()` could temporarily put `obj` into a bad state, then readers could see the bad state unless they are all `synchronized` on the same `mutex` too. – Solomon Slow Jun 16 '16 at 20:30
  • If new state of the object doesn't depend on prev state, in `changeMember` you can create new immutable object and just set it without synchronization. – Abylay Sabirgaliyev Jun 17 '16 at 04:28

0 Answers0