0

For synchronized access on an object, the following pattern is common:

Object lock = new Object();

@GuardedBy("lock")
Object sharedObject;

Where lock is used as synchronized(lock) {}. The annotation is nice but it's not enforced. I would like to do something like this:

class SyncedReference<T> {

  Object lock;

  T value;

  SyncedReference(Object lock) {}

  T get() {
    if (!isLocked(lock)) {
      throw new IllegalStateException();
    }
    return value;
  }

  boolean isLocked() {
    // How to do this?
  }
}

My question is how to implement the isLocked() method?

Xi 张熹
  • 10,492
  • 18
  • 58
  • 86
  • Intrinsic locks in Java are _[reentrant](https://en.wikipedia.org/wiki/Reentrant_mutex)_. Don't bother to _test_ the lock in the `get` method: Just _lock_ it. If `get()` was called in a thread that already had the object locked, then nothing special will happen. – Solomon Slow Aug 02 '19 at 18:31
  • 1
    "I would like to do something like this" - it's a wrong wish. – Alexei Kaigorodov Aug 02 '19 at 19:02
  • If you want to be able to do this, you need to use the classes from `java.util.concurrent.locks`. – Mark Rotteveel Aug 02 '19 at 19:51
  • Alexei, could you elaborate? I would like to learn about best practices. – Xi 张熹 Aug 02 '19 at 21:44

0 Answers0