I'm trying to solve a problem, whether this can be feasible or not trying to understand with the experts there in in this forum, the problem is with inter-thread communication using java.
I have a class:
class A {
public void setX() {}
public void setY() {}
}
I have 4 or more threads, for example:
T1,T2,T3,T4 are the threads that operates on this Class
I have to design the synchronization in such a manner if at any time if a thread is setting one method all other thread will operate on other method
e.g.:
if thread T1 is operating on setX() methods then T2,T3,T4 can work on setY()
if thread T2 is operating on setX() methods then T1,T3,T4 can work on setY()
if thread T3 is operating on setX() methods then T1,T2,T4 can work on setY()
if thread T4 is operating on setX() methods then T1,T2,T3 can work on setY()
You will have to do this externally.
Share a ReentrantLock
between the Runnable
instances.
A a = new A();
ReentrantLock lock = new ReentrantLock();
...
// in each run()
if (lock.tryLock()) {
try {
a.setX(); // might require further synchronization
} finally {
lock.unlock();
}
} else {
a.setY(); // might require further synchronization
}
Handle Exception
s accordingly. When tryLock()
runs it returns
true if the lock was free and was acquired by the current thread, or the lock was already held by the current thread; and false otherwise
It returns immediately, no blocking involved. If it returns false
, you can use the other method. You cannot forget to release the lock once you are finished operating on setX()
.
Nice question. You can use tryLock.
You should do something like:
class A
{
public void setX() {
if (tryLock(m_lock))
{
// Your stuff here
} else {
setY();
}
}
public void setY() {
// Your stuff here
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With