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.