0

In my project I have to use a class X which offers lots of methods, but the document doesn't mention if these methods are thread-safe, and I don't have the source code either.

So I have encapsulated X in an other class with a mutex:

public class MyX {
    private X instance;
    public final Object mutex = new Object();
    public MyX () {
        this.instance = new X();
    }
    public X getMethods () {
        return this.instance;
    }
}

When I need to call methods of X, I use a synchronized block:

MyX myX = new MyX();
synchronized (myX.mutex) {
    X methods = myX.getMethods();
    methods.method1();
    methods.method2();
    ... ... ...
}

Or, maybe I can synchronize directly on an instance of class X:

X instance = new X();
synchronized(instance) {
    instance.method1();
    instance.method2();
    ... ... ...
}

I'd like to know which way is better to go, and is there a better design for this problem.

Thanks.

vesontio
  • 381
  • 1
  • 7
  • 19

1 Answers1

3

If you want to synchronize between two methods of the same class, then mutex is something you should opt for.

exposing mutex as a public variable is against object oriented principles, and hence of course not recommended.

While working from outside the class, acquiring lock on the object you are working on is the best option, I would say.

X instance = new X();
synchronized(instance) {
instance.method1();
instance.method2();
... ... ...
}
Anand Vaidya
  • 1,374
  • 11
  • 26
  • Thank you very much @Anand Vaidya. In my program, several threads will share the same instance of the class `X`. I will pick the second way then. – vesontio Apr 06 '16 at 09:20
  • One more question, is `synchronized(instance)` equivalent to `public synchronized void method1()` ? – vesontio Apr 06 '16 at 11:27
  • yes. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object. http://stackoverflow.com/questions/9196723/learning-java-use-of-synchronized-keyword – Anand Vaidya Apr 06 '16 at 13:09
  • Thank you again @Anand Vaidya. – vesontio Apr 07 '16 at 06:20