Accessdenier
Accessdenier

Reputation: 195

java, multithreading, how to block another method

I have one class having 2 method, Read method and Write method. I want multi-thread can get access the read method and only 1 thread get access the read method. And when the write method is accessed, the read method will be blocked. How should I do it?

Note: after reading the answers I wrote a little piece of code for this, I used concurrent package lock.

public class ConcurrentLock {
private Lock wLock = new Lock();
private Lock rLock = new Lock();
private int i;
public static void main(String[] args){

}
public int Read(){
    try {
        rLock.lock();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }finally{
        rLock.unlock();
    }
    return i;
}

public void Write(){
    try {
        wLock.lock();
        rLock.lock();
        ++i;
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }finally{
        wLock.unlock();
        rLock.unlock();
    }

}

}

Upvotes: 1

Views: 158

Answers (3)

SkyWalker
SkyWalker

Reputation: 14309

This is the Readers-Writer pattern, you can directly in Java 5+ use the ReadersWriteLock.java possible implementations to achieve exactly that. You have to acquire and release the appropriate readers and writer locks. See the Javadoc for examples.

Note that even though it is not very clear in your OP, blocking threads that try to read because another is already reading does not make sense and only increases contention. Two readers should be allowed to read concurrently. However, writers should have exclusive access.

Upvotes: 3

cybye
cybye

Reputation: 1171

the native way ;)

public void read() {
      synchronized(readLock) {
           // critical operations like resource.get(Some)
      }
}
public void write() {
      synchronized(writeLock) {
           synchronized(readLock) {
              // critical operations like resource.put(Some, Some)
           }
      }
}

// for the academic

public void onlyOneReaderAndOnlyOneWriter() {
      writeLock = readLock;
}

public void multipleReadersAndOnlyOneWriter() {
     synchronized(readLock) { // grr, tricky
         writeLock = new Object();
     }
}

Upvotes: 1

anoopelias
anoopelias

Reputation: 9548

Mark both of them as synchronized.

Upvotes: 0

Related Questions