I need to lock class objects (which handles a socket connection) and pass those objects to threads for processing.
public class Client{
protected Socket socket;
...
public Lock lock = new ReentrantLock();
}
I have a simple worker class that handles the work.
public class ClientWriterWorker extends Runnable{
protected Client client;
protected String data;
public ClientWriterWorker(Client client, String data){
this.client = client;
this.data = data;
}
@Override
public void run(){
// do the processing
this.client.write(this.data);
// release the lock?
this.client.lock.unlock(); // does not work
}
}
Then I have a loop that gets unlocked client, locks it, and passes it to thread.
Client currentClient = null;
while(true){
for(Client client : clients){
if(client.lock.tryLock()){
// we have the lock
currentClient = client;
break;
}
}
if(currentClient != null){
break;
}
}
new Thread(new ClientWriterWorker(currentClient, "some data")).start();
Is it possible to unlock locks in another thread? Is my design flawed?
If you don't want to write your own class, you can use a Semaphore.
From the documentation page:
A semaphore initialized to one, and which is used such that it only has at most one permit available, can serve as a mutual exclusion lock. This is more commonly known as a binary semaphore, because it only has two states: one permit available, or zero permits available. When used in this way, the binary semaphore has the property (unlike many Lock implementations), that the "lock" can be released by a thread other than the owner (as semaphores have no notion of ownership). This can be useful in some specialized contexts, such as deadlock recovery.
Just initialize the semaphore with 1 permit:
semaphore = new Semaphore(1);
Then use semaphore.acquire() and semaphore.release() instead of lock.lock() and lock.unlock().
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