Skip to content

Make API for Monitor work better with Java 8 #2853

Closed

Description

The SafeBox example for Monitor is much more verbose than expected. We can do better:

public class SafeBox<V> {
  private V value;
  private final Monitor monitor = new Monitor();
  private final Monitor.Guard valuePresent = guard(monitor, () -> value != null);
  private final Monitor.Guard valueAbsent = guard(monitor, () -> value == null);

  public V get() throws InterruptedException {
    try (LockedMonitor ignored = monitor.autoEnterWhen(valuePresent)) {
      V result = value;
      value = null;
      return result;
    }
  }

  public void set(V newValue) throws InterruptedException {
    try (LockedMonitor ignored = monitor.autoEnterWhen(valueAbsent)) {
      value = newValue;
    }
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions