开发者

Determine whether it a lock type( read or write)

开发者 https://www.devze.com 2023-02-19 13:10 出处:网络
Is it possible to determi开发者_如何学编程ne what a lock type is like whether read or write in a readWritelock in java?

Is it possible to determi开发者_如何学编程ne what a lock type is like whether read or write in a readWritelock in java?

I have a function like below

  public Table getTableLocked(final Lock lock) throws FactFinderException {
     boolean loadTable = true;
       // Get the current table instance
    TableManagementInfo table = TABLES.get(mapKey);

     return table.instance;

}

In this situation I am passing a Lock (ReadWriteLock) . I need to determine first what type of lock it is..whether read or write...any idea how it can be done..?


You can use a lock for read, write or read and write. So there is no way to know if a Lock is one or the other because they are all the same.

Use of locks is typically static in code, so I don't believe there is a good reason to want to check this dynamically.

EDIT: For example you can use ReentrantReadWriteLock to support multiple reads with ReadLock and a single writer with WriteLock. This is a common pattern which explans the names. However say you want multiple writers and single reader? You can just use the ReadLock for writing and the WriteLock for reading.

When you perform a read or write you should know, and not have to check, what type of lock you are using. The lock must match the operation you are performing. no other option will give you correct behaviour.


You can use reflection to determine if you have a ReadLock or a WriteLock.

import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock;

...

if (lock instanceof ReadLock) {
  System.out.println("Read");
} else if (lock instanceof WriteLock) {
  System.out.println("Write");
}

Having said that, I agree with Peter that there is probably a better way of achieving what you want to do without checking dynamically.

0

精彩评论

暂无评论...
验证码 换一张
取 消