Class Lock

All Implemented Interfaces:
Serializable, ReadWriteLock

public class Lock extends ReentrantReadWriteLock
Ghidra synchronization read/write lock that provides read and write methods for acquiring either a shared read access or an exclusive write access.

It extends Java's ReentrantReadWriteLock, but adds convenient methods to get either a read or write lock that returns an AutoCloseable object that can be used in a try with resources block that will auto release the lock when the try block is exited.

To use a lock for share read access the general pattern is something like:

int getSize() {
    try (Closeable c = lock.read()) {
        return record.getIntValue(SIZE);
    }
}

Similarly, to get exclusive access for modification:

int getSize() {
    try (Closeable c = lock.write()) {
               return record.setIntValue(SIZE);
        database.updateRecord(record);  
    }
}
See Also:
  • Constructor Details

    • Lock

      public Lock(String name)
      Creates an instance of a lock for synchronization within Ghidra.
      Parameters:
      name - the name of this lock
  • Method Details

    • toString NEW

      public String toString()
      Overrides:
      toString in class ReentrantReadWriteLock
    • read NEW

      public Lock.Closeable read()
      Acquires the read lock that can allow simultaneous access by all read threads. Will block if any thread already has a write lock.
      Returns:
      An AutoCloseable handle to the lock that be used in a try with resources block to automatically release the lock when the block is exited.
    • write NEW

      public Lock.Closeable write()
      Acquires the exclusive write lock that prevents any other thread, reader or writer, from getting a lock while the write lock is held. Will block if any other thread has either a read or write lock. VERY IMPORTANT, any thread that attempts to acquire the write lock while already holding the read lock, will cause an immediate deadlock.
      Returns:
      An AutoCloseable handle to the lock that be used in a try with resources block to automatically release the lock when the block is exited.
    • getOwner

      public Thread getOwner()
      Gets the thread that currently owns the lock.
      Overrides:
      getOwner in class ReentrantReadWriteLock
      Returns:
      the thread that owns the lock or null.
    • withRead

      public <T> T withRead(Supplier<T> supplier)
      A convenience method for acquiring a read lock, executing a supplier object, then releasing the lock.
      Type Parameters:
      T - the supplier return type
      Parameters:
      supplier - the supplier to execute while holding a read lock.
      Returns:
      the result from the supplier
    • withWrite NEW

      public void withWrite(Callback callback)
      A convenience method for acquiring a write lock, executing a callback object, then releasing the lock.
      Parameters:
      callback - the callback to execute while holding a write lock.