Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
    }
}
like image 724
stonar96 Avatar asked Apr 15 '16 16:04

stonar96


People also ask

Can multiple threads hold a lock on the same object?

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.

Can a thread acquire multiple locks?

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

How do you lock and unlock a thread?

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.


1 Answers

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

like image 66
borjab Avatar answered Sep 29 '22 06:09

borjab