Search code examples
javamultithreadinglockingreentrantlock

Java lock and unlock on different thread


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

Solution

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