Пример #1
0
 public LinkList(E value) {
   this.value = value;
   rest = null;
   lock = new ReentrantLock();
   valueChanged = lock.newCondition();
   linkChanged = lock.newCondition();
 }
Пример #2
0
  public ServerStateContext(
      final ISipManager sipManager,
      final SipUser serverUser,
      final UCESipServerSettings sipSettings) {
    this.sipManager = sipManager;
    this.serverUser = serverUser;
    this.sipSettings = sipSettings;

    this.stateLock = new ReentrantLock();
    this.stateChangeCondition = stateLock.newCondition();

    this.takeCallLock = new ReentrantLock();
    this.takeCallCondition = takeCallLock.newCondition();

    this.serverCallMap = new HashMap<String, UCESipServerCall>();
    this.registerRefreshThread = new RegisterRefreshThread(this.sipManager, this.serverUser);

    this.callMapCleanupTimer = new Timer("Server call map cleanup");
    this.callMapCleanupTask = new CallMapCleanupTask();

    this.callQueue = new ArrayBlockingQueue<>(sipSettings.getCallQueueCapacity());

    this.isTaking = false;
    this.isShutdown = false;
    this.stateTimeoutTimer = new Timer("Sip user agent server state timeout timer");
    this.currentServerState = new InitServerState(this);
  }
Пример #3
0
  public DBWriteManager(
      String path,
      int poolSize,
      DBReadManager readManager,
      boolean useEnvironment,
      boolean useSecondaries) {

    this.useEnvironment = useEnvironment;
    this.useSecondaries = useSecondaries;
    this.path = path;
    this.poolSize = poolSize;
    this.readManager = readManager;

    // default databaseType is queue
    primaryType = DatabaseType.QUEUE;

    // initialize array of DBs
    ready = new LinkedList<TestDatabase>();
    waiting = new LinkedList<TestDatabase>();

    readyLock = new ReentrantLock();
    readyCondition = readyLock.newCondition();
    waitingLock = new ReentrantLock();
    waitingCondition = waitingLock.newCondition();

    runningLock = new ReentrantLock();

    // System.err.println("DBWriteManager initialized. path = " + this.path + " nextIndex = " +
    // nextIndex);
  }
Пример #4
0
class BoundedBuffer {
  final Lock lock = new ReentrantLock();
  final Condition notFull = lock.newCondition();
  final Condition notEmpty = lock.newCondition();

  final Object[] items = new Object[100];
  int putptr, takeptr, count;

  public void put(Object x) throws InterruptedException {
    lock.lock();
    try {
      while (count == items.length) notFull.await();
      items[putptr] = x;
      if (++putptr == items.length) putptr = 0;
      ++count;
      notEmpty.signal();
    } finally {
      lock.unlock();
    }
  }

  public Object take() throws InterruptedException {
    lock.lock();
    try {
      while (count == 0) notEmpty.await();
      Object x = items[takeptr];
      if (++takeptr == items.length) takeptr = 0;
      --count;
      notFull.signal();
      return x;
    } finally {
      lock.unlock();
    }
  }
}
Пример #5
0
  public TestWorker() {
    ping_lock = new ReentrantLock();
    data_lock = new ReentrantLock();
    // clock_lock = new ReentrantLock();
    start_throughput = data_lock.newCondition();
    start_ping = ping_lock.newCondition();
    // start_clock = clock_lock.newCondition();
    start_p = false;
    start_d = false;
    // clock_start = false;

  }
Пример #6
0
public class BlockingQueue<T> {
  private Queue<T> queue;
  private Lock lock = new ReentrantLock(true);
  private Condition notFull = lock.newCondition();
  private Condition notEmpty = lock.newCondition();
  private int maxSize;

  public BlockingQueue(int maxSize) {
    queue = new LinkedList<T>();
    this.maxSize = maxSize;
  }

  public List<T> take(int n) {
    try {
      lock.lock();
      List<T> answer = new ArrayList<T>();
      for (int i = 0; i < n; ++i) {
        while (queue.size() == 0) {
          try {
            notEmpty.await();
          } catch (InterruptedException e) {
            return null;
          }
        }
        answer.add(queue.poll());
        notFull.signalAll();
      }
      return answer;
    } finally {
      lock.unlock();
    }
  }

  public void offer(List<T> list) {
    try {
      lock.lock();
      for (T element : list) {
        while (queue.size() == maxSize) {
          try {
            notFull.await();
          } catch (InterruptedException e) {
            return;
          }
        }
        queue.add(element);
        notEmpty.signal();
      }
    } finally {
      lock.unlock();
    }
  }
}
public class ConcatThread extends Thread {

  private static String text = ""; // global variable
  private String toe;
  private Lock lock = new ReentrantLock();
  private Condition hasconcat = lock.newCondition();
  private boolean isBusy = false;

  public ConcatThread(String toeArg) {
    this.toe = toeArg;
  }

  public void run() {
    text = text.concat(toe);
  }

  public static void main(String[] args) {
    (new ConcatThread("one;")).start();
    try {
      sleep(100);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    (new ConcatThread("two;")).start();
    try {
      sleep(100);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    System.out.println(text);
  }
}
  public class CalabashHttpServerWaiter implements Runnable {
    private Lock lock = new ReentrantLock();
    private Condition cv = lock.newCondition();

    private boolean isPortBound() {
      Boolean ready = Boolean.parseBoolean(extractStringResponse(execute("/ready", null)));

      if (ready == null || ready == Boolean.FALSE) {
        return Boolean.FALSE;
      } else {
        return Boolean.TRUE;
      }
    }

    @Override
    public void run() {
      lock.lock();
      try {
        while (!isPortBound()) {
          cv.await(2, TimeUnit.SECONDS);
        }
      } catch (InterruptedException e) {
        logger.error("Process to wait for starting the calabash server was interupted.", e);
      } finally {
        lock.unlock();
      }
    }
  }
 /**
  * Instanciates a Departure Terminal Entrance
  *
  * @param totalPassengers The total number of passengers of the current simulation
  * @param numEntities The number of entities that will use the VectorClock at the same time
  */
 public MDepartureTerminalEntrance(int totalPassengers, int numEntities) {
   remainingPassengers = caclNumPassengers(totalPassengers);
   this.totalPassengers = totalPassengers;
   lock = new ReentrantLock();
   cond = lock.newCondition();
   this.vecClock = new VectorClock(numEntities);
 }
Пример #10
0
public class OneMoreSemaphore {

  private Lock lock = new ReentrantLock();
  private Condition queue = lock.newCondition();
  private int permits;
  private int counter = 0;

  OneMoreSemaphore(int p) {
    permits = p;
  }

  public void acquire() throws InterruptedException {
    lock.lock();
    try {
      while (!(counter < permits)) queue.await();
      ++counter;
    } finally {
      lock.unlock();
    }
  }

  public void release() {
    lock.lock();
    try {
      if (counter > 0) --counter;
    } finally {
      lock.unlock();
    }
  }
}
  @SuppressWarnings("all")
  public ZoomPanDrawingView(Context context, AttributeSet attrs) {
    super(context, attrs);
    fHolder = getHolder();
    fHolder.addCallback(this);

    int width = ((Activity) context).getWindowManager().getDefaultDisplay().getWidth();
    int height = ((Activity) context).getWindowManager().getDefaultDisplay().getHeight();
    fCanvasManager = new DrawManager(width, height);

    fDrawListener = new ViewDrawListener();
    fCanvasManager.setDrawListener(fDrawListener);
    fZoomManager = new ZoomPanTouchListener(fCanvasManager);

    fViewMatrix = new Matrix();
    fZoomManager.setViewMatrix(fViewMatrix);

    fInputMatrix = new Matrix();
    fZoomManager.setInputMatrix(fInputMatrix);

    fCanvasManager.setInputMatrix(fInputMatrix);

    fDrawLock = new ReentrantLock();
    fDrawCondition = fDrawLock.newCondition();
    fDrawFlag = true;
    fZoomFlag = false;

    fWidth = fCanvasManager.getWidth();
    fHeight = fCanvasManager.getHeight();

    fCorners = new float[4];
  }
Пример #12
0
 public Ex_4_3_2() {
   for (int i = 0; i < N; ++i) {
     counter[i] = 0;
     process[i] = lock.newCondition();
   }
   counter[0] = M;
 }
  /**
   * Register a service-operation either as secure or unsecure
   *
   * @param serviceOperationEPR EndpointReference for the target service-operation
   * @param isSecure Must be true if the service-operation is secure and false otherwise
   */
  public void setIsInvocationHelperSecure(EndpointReference serviceOperationEPR, boolean isSecure) {

    WorkflowInvocationHelperClient client = null;
    String EPRStr = null;
    try {
      client = new WorkflowInvocationHelperClient(serviceOperationEPR);
      EPRStr = client.getEPRString();

    } catch (MalformedURIException e) {
      e.printStackTrace();
    } catch (RemoteException e) {
      e.printStackTrace();
    }

    if (isSecure) {

      logger.info("Creating locks");

      // Initializes mutual exclusion key that denotes the availability of the delegated credential
      Lock key = new ReentrantLock();
      Condition credentialAvailability = key.newCondition();
      this.serviceConditionVariable.put(EPRStr, credentialAvailability);
      this.servicelLock.put(EPRStr, key);

      this.printCredentials();

    } else {

      logger.info("Adding service to unsecure list");

      this.unsecureInvocations.add(EPRStr);
    }
    logger.info("Done");
  }
Пример #14
0
  @Test(timeout = 1500l)
  public void testConditionWaitsForSignalOtherThread() throws Exception {
    final Lock firstLock = new ReentrantZkLock(baseLockPath, zkSessionManager);
    final Condition firstCondition = firstLock.newCondition();

    firstLock.lock();
    // fire off a thread that will signal the main process thread
    testService.submit(
        new Runnable() {
          @Override
          public void run() {
            firstLock.lock();
            System.out.println("Lock acquired on second thread");
            try {
              firstCondition.signal();
              System.out.println("Lock signalled on second thread");
            } finally {
              System.out.println("Lock released on second thread");
              firstLock.unlock();
            }
          }
        });

    // wait for signal notification
    System.out.println("First thread waiting for notification");
    firstCondition.await();
    System.out.println("First thread has been notified");
  }
  @SuppressWarnings("all")
  public ZoomPanDrawingView(Context context, DrawManager aCanvasManager) {
    super(context);
    fHolder = getHolder();
    fHolder.addCallback(this);
    fCanvasManager = aCanvasManager;
    fDrawListener = new ViewDrawListener();
    fCanvasManager.setDrawListener(fDrawListener);
    fZoomManager = new ZoomPanTouchListener(fCanvasManager);

    fViewMatrix = new Matrix();
    fZoomManager.setViewMatrix(fViewMatrix);

    fInputMatrix = new Matrix();
    fZoomManager.setInputMatrix(fInputMatrix);

    fCanvasManager.setInputMatrix(fInputMatrix);

    fDrawLock = new ReentrantLock();
    fDrawCondition = fDrawLock.newCondition();
    fDrawFlag = true;
    fZoomFlag = false;

    fWidth = fCanvasManager.getWidth();
    fHeight = fCanvasManager.getHeight();

    fCorners = new float[4];
  }
Пример #16
0
  public EventServiceImpl() {
    listenerMap = new TreeMap<>();
    eventQueue = new LinkedList<>();

    eventQueueLock = new ReentrantLock();
    queueNotEmpty = eventQueueLock.newCondition();
  }
Пример #17
0
 public Bank(int n, double initialBalance) {
   acounts = new double[n];
   for (int i = 0; i < acounts.length; i++) {
     acounts[i] = initialBalance;
   }
   bankLock = new ReentrantLock();
   sufficientFunds = bankLock.newCondition();
 }
Пример #18
0
  public Runway() {
    L = new ReentrantLock();
    C = L.newCondition();

    wind_direction = 0;
    runway_number = 0;
    turn = 0;
    runway_direction = "";
  }
  static class RequestTracker<R> {
    final ResultsCallback<R> callback;
    final Map<Address, Set<Integer>> awaitingResponse;
    final Lock completionLock = new ReentrantLock();
    final Condition completionCondition = completionLock.newCondition();
    final Predicate<? super R> earlyTerminatePredicate;

    Set<Integer> missingSegments;

    volatile Throwable throwable;

    RequestTracker(
        ResultsCallback<R> callback,
        Map<Address, Set<Integer>> awaitingResponse,
        Predicate<? super R> earlyTerminatePredicate) {
      this.callback = callback;
      this.awaitingResponse = awaitingResponse;
      this.earlyTerminatePredicate = earlyTerminatePredicate;
    }

    public void intermediateResults(Address origin, R intermediateResult) {
      callback.onIntermediateResult(origin, intermediateResult);
    }

    /**
     * @param origin
     * @param result
     * @return Whether this was the last expected response
     */
    public boolean lastResult(Address origin, R result) {
      Set<Integer> completedSegments = awaitingResponse.get(origin);
      if (missingSegments != null) {
        completedSegments.removeAll(missingSegments);
      }
      callback.onCompletion(origin, completedSegments, result);
      synchronized (this) {
        if (earlyTerminatePredicate != null && earlyTerminatePredicate.test(result)) {
          awaitingResponse.clear();
        } else {
          awaitingResponse.remove(origin);
        }
        return awaitingResponse.isEmpty();
      }
    }

    public void missingSegments(Set<Integer> segments) {
      synchronized (this) {
        if (missingSegments == null) {
          missingSegments = segments;
        } else {
          missingSegments.addAll(segments);
        }
      }
      callback.onSegmentsLost(segments);
    }
  }
Пример #20
0
  @Test(timeout = 1000l)
  public void testConditionTimesOut() throws Exception {
    Lock firstLock = new ReentrantZkLock(baseLockPath, zkSessionManager);
    Condition firstCondition = firstLock.newCondition();

    firstLock.lock();
    boolean timedOut = firstCondition.await(250l, TimeUnit.MILLISECONDS);
    assertTrue("Condition did not time out!", !timedOut);
    firstLock.unlock();
  }
Пример #21
0
 public Pop(UUID uuid, BlockingOnce blocking_once, Notifier<Pop<T>> notifier) {
   this.object = null;
   this.uuid = uuid == null ? UUID.randomUUID() : uuid;
   this.blocking_once = blocking_once;
   this.notifier = notifier;
   this.mutex = new ReentrantLock();
   this.cvar = mutex.newCondition();
   this.received = false;
   this.closed = false;
 }
Пример #22
0
  public PlantAdapterTestbench(ServerActivationThread serverActivator) throws IOException {

    this.serverActivator = serverActivator;
    // usati per sincronizzare il thread che accetta la richiesta  di connessione con quello
    // corrente
    this.lock = new ReentrantLock();
    this.condition = lock.newCondition();
    // sincronizzazione con thread attivazione e lancio
    this.serverActivator.start();
  }
Пример #23
0
  static class Runner {

    private int count = 0;

    private Lock lock = new ReentrantLock();

    private Condition condition = lock.newCondition();

    private void increment() {
      for (int i = 0; i < 10000; i++) {
        count++;
      }
    }

    public void firstThread() throws InterruptedException {
      lock.lock();

      System.out.println("Thread 1 çalışıyor...");

      condition.await();

      System.out.println("Thread 1 devam ediyor...");

      try {
        increment();
      } finally {
        lock.unlock();
      }
    }

    public void secondThread() throws InterruptedException {
      Thread.sleep(2000);

      lock.lock();

      System.out.println("Thread 2 çalışıyor...");
      System.out.print("Devam etmek için 'Enter'a basınız: ");

      new Scanner(System.in).nextLine();

      condition.signal();

      System.out.println("Thread 2 devam ediyor...");

      try {
        increment();
      } finally {
        lock.unlock();
      }
    }

    public void printCount() {
      System.out.println("Sayaç: " + count);
    }
  }
Пример #24
0
public class LockTest {
  static Thread thread1;
  static Thread thread2;
  Lock lock = new ReentrantLock();
  Condition t1Con = lock.newCondition();
  Condition t2Con = lock.newCondition();
  static boolean tag;

  public void methodTest() {
    lock.lock();

    try {
      if (thread2.equals(Thread.currentThread())) {
        t2Con.await();
      }
      Thread.sleep(1000);
      if (thread1.equals(Thread.currentThread())) {
        t2Con.signal();
      }

      System.out.println(Thread.currentThread().getName());
    } catch (InterruptedException e1) {
      e1.printStackTrace();
    } finally {
      lock.unlock();
    }
  }

  public static void main(String[] args) {
    final LockTest lt = new LockTest();
    thread1 =
        new Thread(
            new Runnable() {
              public void run() {
                lt.methodTest();
              }
            });
    thread2 =
        new Thread(
            new Runnable() {
              public void run() {
                lt.methodTest();
              }
            });

    thread2.setName("线程2");
    thread1.setName("线程1");

    thread2.start();
    thread1.start();
  }
}
Пример #25
0
/** Queues messages until a receiver has been connected. This class is thread-safe. */
public class QueuingDispatch<T> implements Dispatch<T>, Stoppable {
  private final Lock lock = new ReentrantLock();
  private final Condition condition = lock.newCondition();
  private List<T> queue = new ArrayList<T>();
  private Dispatch<? super T> dispatch;

  /** Dispatches to the given handler. The handler does not have to be thread-safe. */
  public void dispatchTo(Dispatch<? super T> dispatch) {
    lock.lock();
    try {
      this.dispatch = dispatch;
      for (T message : queue) {
        dispatch.dispatch(message);
      }
      queue = null;
      condition.signalAll();
    } finally {
      lock.unlock();
    }
  }

  public void dispatch(T message) {
    lock.lock();
    try {
      if (dispatch == null) {
        queue.add(message);
      } else {
        dispatch.dispatch(message);
      }
    } finally {
      lock.unlock();
    }
  }

  public void stop() {
    lock.lock();
    try {
      while (queue != null && !queue.isEmpty()) {
        try {
          condition.await();
        } catch (InterruptedException e) {
          throw UncheckedException.asUncheckedException(e);
        }
      }
    } finally {
      lock.unlock();
    }
  }
}
Пример #26
0
 public ProcessingBucket(
     String bucketName,
     AsyncConfig config,
     ToolkitListInternal<E> toolkitList,
     ClusterInfo cluster,
     ItemProcessor<E> processor,
     boolean workingOnDeadBucket) {
   this.bucketName = bucketName;
   this.config = config;
   this.cluster = cluster;
   this.processor = processor;
   this.toolkitList = toolkitList;
   this.baselineTimestampMillis = System.currentTimeMillis();
   ReentrantReadWriteLock bucketLock = new ReentrantReadWriteLock();
   this.bucketReadLock = bucketLock.readLock();
   this.bucketWriteLock = bucketLock.writeLock();
   this.bucketNotEmpty = bucketWriteLock.newCondition();
   this.bucketNotFull = bucketWriteLock.newCondition();
   this.stoppedButBucketNotEmpty = bucketWriteLock.newCondition();
   this.workDelay = new AtomicLong(config.getWorkDelay());
   this.workingOnDeadBucket = workingOnDeadBucket;
   this.processingWorkerRunnable = new ProcessingWorker(threadNamePrefix + bucketName);
   this.destroyAfterStop = true;
 }
  public static void main(String[] args) {
    final Lock lock = new ReentrantLock();
    final Condition condition = lock.newCondition();
    class WaitThread extends Thread {
      String token;

      public WaitThread(String token) {
        super();
        this.token = token;
      }

      @Override
      public void run() {
        try {
          System.out.println("Wait Thread " + token + " was started.");
          lock.lock();
          System.out.println("Wait Thread " + token + " got the lock.");
          System.out.println("Wait Thread " + token + " start to wait.");
          condition.await();
          System.out.println("Wait Thread " + token + " finish waiting.");
          System.out.println("Wait Thread " + token + " was finished.");
        } catch (InterruptedException e) {
          System.out.println("Wait Thread " + token + " was interrupted.");
        }
      }
    }
    final WaitThread waitThread = new WaitThread("one");
    Thread modifyThread =
        new Thread() {
          @Override
          public void run() {
            try {
              System.out.println("Signal Thread was started.");
              TimeUnit.SECONDS.sleep(1L);
              boolean acquire = lock.tryLock();
              System.out.println("Signal Thread got the lock: " + acquire);
              condition.signalAll();
              lock.unlock();
              System.out.println("Signal Thread was finished.");
            } catch (InterruptedException e) {
              e.printStackTrace();
            }
          }
        };
    waitThread.start();
    modifyThread.start();
  }
  private static class Account {

    int balance = 0;

    static Lock lock = new ReentrantLock();

    static Condition newDeposit = lock.newCondition();

    public int getBalance() {
      return this.balance;
    }

    public void deposit(int ammount) {

      lock.lock();
      try {
        this.balance += ammount;
        System.out.println("Deposit " + ammount + " \t\t\t" + getBalance() + "(total balance)");
        newDeposit.signalAll();
      } finally {
        lock.unlock();
      }
    }

    public void withdraw(int amount) {

      lock.lock();
      try {

        while (balance < amount) {
          System.out.println(
              "withdraw amount ("
                  + amount
                  + ") greater than balance("
                  + balance
                  + "). So wait for deposit");
          newDeposit.await();
        }
        balance -= amount;
        System.out.println("Withdraw: " + amount + "\t\t" + balance + "(remaining balance)");

      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
  }
Пример #29
0
/**
 * 一个线程安全的对象包装器。一般在多线程并发操作一个对象时使用。
 *
 * <p>注:BlockingItem使用了可重入锁ReentrantLock来处理资源的并发,默认是非公平的(先take的不一定先拿到)。
 *
 * @author Jun.Deng
 * @param <T> 需要被包装的对象类型
 */
public class BlockingItem<T> {
  final Lock lock = new ReentrantLock();
  final Condition notEmpty = lock.newCondition();

  private volatile T item;

  public void put(T x) {
    lock.lock();
    try {
      item = x;
      if (x != null) notEmpty.signal();
    } finally {
      lock.unlock();
    }
  }

  public T take() throws InterruptedException {
    lock.lock();
    try {
      while (item == null) notEmpty.await();
      T t = item;
      item = null;
      return t;
    } finally {
      lock.unlock();
    }
  }

  public T tryTake(long waitMs) throws InterruptedException {
    lock.lock();
    try {
      while (item == null) if (!notEmpty.await(waitMs, TimeUnit.MILLISECONDS)) return null;
      T t = item;
      item = null;
      return t;
    } finally {
      lock.unlock();
    }
  }

  public T peek() {
    return item;
  }
}
Пример #30
0
  // An inner class for account
  private static class Account {
    private static Lock lock = new ReentrantLock(); // Create a new lock

    // Create a condition
    private static Condition newDeposit = lock.newCondition();

    private int balance = 0;

    public int getBalance() {
      return balance;
    }

    public void withdraw(int amount) {
      lock.lock(); // Acquire the lock
      try {
        while (balance < amount) {
          System.out.println("\t\t\tWait for a deposit");
          newDeposit.await();
        }

        balance -= amount;
        System.out.println("\t\t\tWithdraw " + amount + "\t\t" + getBalance());
      } catch (InterruptedException ex) {
        ex.printStackTrace();
      } finally {
        lock.unlock(); // Release the lock
      }
    }

    public void deposit(int amount) {
      lock.lock(); // Acquire the lock
      try {
        balance += amount;
        System.out.println("Deposit " + amount + "\t\t\t\t\t" + getBalance());

        newDeposit.signalAll();
      } finally {
        lock.unlock(); // Release the lock
      }
    }
  }