vesontio
vesontio

Reputation: 381

Public final mutex for Java thread safety

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.

Upvotes: 0

Views: 511

Answers (1)

Anand Vaidya
Anand Vaidya

Reputation: 1461

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();
... ... ...
}

Upvotes: 3

Related Questions