I have a main thread and a worker thread. The main thread adds tasks into a queue and the worker thread takes them to compute data. Before I put the objects into the queue I call lock on a ReentrantLock object (on the main thread) inside the task objects. When the worker thread is finished with working on a task from the queue I call unlock (on the worker thread). The problem is that I get an IllegalMonitorStateException because I call lock and unlock on different threads.
I am looking for an alternative lock system where I can do this on different threads.
Example:
public class Worker extends Thread {
public static Queue<Task> tasks = new ConcurrentLinkedQueue<Task>();
@Override
public void run() {
while (true) {
Task task = tasks.poll();
if (task != null) {
task.work();
task.lock.unlock(); // Here is the unlock, Task#i should not change up to now
}
}
}
}
public class Task {
private int i = 0;
public Lock lock;
public void setI(int i) {
lock.lock();
this.i = i;
lock.unlock();
}
public void work() {
System.out.println(i);
}
}
public class Test {
Task task = new Task();
public void addTask() {
task.lock.lock(); // Here is the lock, Task#i should not change
Worker.tasks.add(task);
}
}
It is not possible for two threads to hold the same lock at the same time. This could be due to the two threads exchanging the lock in between their data being displayed in the debugger.
A thread can safely acquire the same lock multiple times without running into deadlocks (e.g. a synchronized method calls another synchronized method on the same object).
A thread can have more than one lock. Each time a LOCK THREAD statement executes in the thread, the number of locks held by that thread increases by one. To allow other threads to run again, an equal number of UNLOCK THREAD statements must also execute.
Why not use a Semaphore with just one permit? Instead of the lock operation you acquire the single permit. You should always free the lock with the release().
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