Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mutilthreading with N threads

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()
like image 695
anish Avatar asked Dec 16 '22 05:12

anish


2 Answers

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 Exceptions 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().

like image 192
Sotirios Delimanolis Avatar answered Dec 27 '22 11:12

Sotirios Delimanolis


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
   }
}
like image 21
Lior Ohana Avatar answered Dec 27 '22 11:12

Lior Ohana