PsyLock.java

  1. package coneforest.psylla.core;

  2. import coneforest.psylla.runtime.*;
  3. import java.util.concurrent.locks.ReentrantLock;

  4. /**
  5. *   The representation of {@code lock}.
  6. */
  7. @Type("lock")
  8. public class PsyLock
  9.     implements PsyObject
  10. {
  11.     /**
  12.     *   Context action of the {@code condition} operator.
  13.     */
  14.     @OperatorType("condition")
  15.     public static final ContextAction PSY_CONDITION
  16.         =ContextAction.<PsyLock>ofFunction(PsyLock::psyCondition);

  17.     /**
  18.     *   Context action of the {@code lock} operator.
  19.     */
  20.     @OperatorType("lock")
  21.     public static final ContextAction PSY_LOCK
  22.         =ContextAction.ofSupplier(PsyLock::new);

  23.     private final ReentrantLock lock=new ReentrantLock();

  24.     public PsyLock()
  25.     {
  26.     }

  27.     /**
  28.     *   Acquires the lock.
  29.     */
  30.     public void lock()
  31.     {
  32.         lock.lock();
  33.     }

  34.     /**
  35.     *   Releases the lock.
  36.     */
  37.     public void unlock()
  38.     {
  39.         lock.unlock();
  40.     }

  41.     /**
  42.     *   Queries if this lock is held by the current thread.
  43.     *
  44.     *   @return {@code true} if current context holds this lock and {@code
  45.     *   false} otherwise.
  46.     */
  47.     public boolean isHeldByCurrentThread()
  48.     {
  49.         return lock.isHeldByCurrentThread();
  50.     }

  51.     /**
  52.     *   {@return a {@code condition} object for use with this lock}
  53.     */
  54.     public PsyCondition psyCondition()
  55.     {
  56.         return new PsyCondition(lock.newCondition());
  57.     }
  58. }