I'm trying to protect an object with a lock.
I didn't choose mutexes because of ugly syntax of "try..catch".
Browsing stackoverflow, I came to a conclusion that this is how to properly achieve my goal:
class MyClass {
private final Object lock = new Object();
private Channel channel = null;
public void setChannel() {
synchronized (lock) {
channel = new Channel();
synchronized (channel) {
// setup channel
}
}
}
public void unsetChannel() {
synchronized (lock) {
synchronized (channel) {
channel.close();
}
channel = null;
}
}
public boolean isSet() {
synchronized (lock) {
if (channel == null)
return false;
synchronized (channel) {
return channel.isActive();
}
}
}
}
But it seems ugly and hard to read...
How can I improve readability of my solution?