예제 #1
0
  @Test
  public void testDeleteFile() throws Exception {
    log.debug(" **** testDeleteFile **** ");
    File f = new File(mytempdir + File.separator + "just_deleted");
    long interval = 1000;

    try {
      final Semaphore s = new Semaphore(0);

      fw = new FolderWatcher(new File(mytempdir), interval);
      fw.initialRun();

      fw.addListener(
          new IModificationListener() {

            int state = 0;

            public void fileModified(File f, ModifyActions action) {
              log.debug("testDeleteFile: State: " + state);
              switch (state) {
                case 0:
                  Assert.assertEquals("just_deleted", f.getName());
                  Assert.assertEquals(ModifyActions.CREATED, action);
                  break;
                case 1:
                  Assert.assertEquals("just_deleted", f.getName());
                  Assert.assertEquals(ModifyActions.DELETED, action);
                  break;
                default:
                  Assert.fail("Unknown state");
              }
              state++;
              log.debug("Releasing, we are now in state " + state);
              s.release();
            }
          });
      fw.run();
      f.createNewFile();
      log.debug("We expect CREATED");
      Assert.assertTrue(s.tryAcquire(interval * 3, TimeUnit.MILLISECONDS));
      f.delete();
      System.gc();
      f.delete();
      Assert.assertFalse(f.exists());
      log.debug("We expect DELETED");
      Assert.assertTrue(s.tryAcquire(interval * 3, TimeUnit.MILLISECONDS));

      fw.cancel();
    } catch (Exception e) {
      fw.cancel();
      f.delete();
      throw e;
    }
  }
예제 #2
0
  public void writeConfig() throws ExecutionException, TimeoutException, InterruptedException {
    long startTime = System.currentTimeMillis();

    FutureCallback<None> callback = new FutureCallback<None>();
    _store.start(callback);
    callback.get(_timeout, _timeoutUnit);

    final Semaphore outstandingPutSemaphore = new Semaphore(_maxOutstandingWrites);

    for (final String key : _source.keySet()) {

      Map<String, Object> map = merge(_source.get(key), _defaultMap);

      T properties = _builder.fromMap(map);
      Callback<None> putCallback =
          new Callback<None>() {
            @Override
            public void onSuccess(None none) {
              outstandingPutSemaphore.release();
            }

            @Override
            public void onError(Throwable e) {
              _log.error("Put failed for {}", key, e);
              outstandingPutSemaphore.release();
            }
          };

      if (!outstandingPutSemaphore.tryAcquire(_timeout, _timeoutUnit)) {
        _log.error("Put timed out for {}", key);
        throw new TimeoutException();
      }
      _store.put(key, properties, putCallback);
    }

    // Wait until all puts are finished.
    if (!outstandingPutSemaphore.tryAcquire(_maxOutstandingWrites, _timeout, _timeoutUnit)) {
      _log.error(
          "Put timed out with {} outstanding writes",
          _maxOutstandingWrites - outstandingPutSemaphore.availablePermits());
      throw new TimeoutException();
    }

    FutureCallback<None> shutdownCallback = new FutureCallback<None>();
    _store.shutdown(shutdownCallback);
    shutdownCallback.get(_timeout, _timeoutUnit);

    long elapsedTime = System.currentTimeMillis() - startTime;
    _log.info(
        "A total of {}.{}s elapsed to write configs to store.",
        elapsedTime / 1000,
        elapsedTime % 1000);
  }
  @Test
  public void testCancelled() throws InterruptedException, ExecutionException {
    Task<List<?>> t =
        Tasks.sequential(sayTask("1"), sayTask("2a", Duration.THIRTY_SECONDS, "2b"), sayTask("3"));
    ec.submit(t);
    synchronized (messages) {
      while (messages.size() <= 1) messages.wait();
    }
    Assert.assertEquals(messages, Arrays.asList("1", "2a"));
    Time.sleep(Duration.millis(50));
    t.cancel(true);
    Assert.assertTrue(t.isDone());
    // 2 should get cancelled, and invoke the cancellation semaphore
    // 3 should get cancelled and not run at all
    Assert.assertEquals(messages, Arrays.asList("1", "2a"));

    // Need to ensure that 2 has been started; race where we might cancel it before its run method
    // is even begun. Hence doing "2a; pause; 2b" where nothing is interruptable before pause.
    Assert.assertTrue(cancellations.tryAcquire(10, TimeUnit.SECONDS));

    Iterator<Task<?>> ci = ((HasTaskChildren) t).getChildren().iterator();
    Assert.assertEquals(ci.next().get(), "1");
    Task<?> task2 = ci.next();
    Assert.assertTrue(task2.isBegun());
    Assert.assertTrue(task2.isDone());
    Assert.assertTrue(task2.isCancelled());

    Task<?> task3 = ci.next();
    Assert.assertFalse(task3.isBegun());
    Assert.assertTrue(task2.isDone());
    Assert.assertTrue(task2.isCancelled());

    // but we do _not_ get a mutex from task3 as it does not run (is not interrupted)
    Assert.assertEquals(cancellations.availablePermits(), 0);
  }
 @Override
 @SuppressFBWarnings("DM_EXIT")
 public void onDestroy() {
   Log.i(TAG, "Destroying ChildProcessService pid=%d", Process.myPid());
   super.onDestroy();
   if (mActivitySemaphore.tryAcquire()) {
     // TODO(crbug.com/457406): This is a bit hacky, but there is no known better solution
     // as this service will get reused (at least if not sandboxed).
     // In fact, we might really want to always exit() from onDestroy(), not just from
     // the early return here.
     System.exit(0);
     return;
   }
   synchronized (mMainThread) {
     try {
       while (!mLibraryInitialized) {
         // Avoid a potential race in calling through to native code before the library
         // has loaded.
         mMainThread.wait();
       }
     } catch (InterruptedException e) {
       // Ignore
     }
   }
   // Try to shutdown the MainThread gracefully, but it might not
   // have chance to exit normally.
   nativeShutdownMainThread();
 }
예제 #5
0
 private int callDocumentHasImagesSync(final AwContents awContents)
     throws Throwable, InterruptedException {
   // Set up a container to hold the result object and a semaphore to
   // make the test wait for the result.
   final AtomicInteger val = new AtomicInteger();
   final Semaphore s = new Semaphore(0);
   final Message msg =
       Message.obtain(
           new Handler(Looper.getMainLooper()) {
             @Override
             public void handleMessage(Message msg) {
               val.set(msg.arg1);
               s.release();
             }
           });
   runTestOnUiThread(
       new Runnable() {
         @Override
         public void run() {
           awContents.documentHasImages(msg);
         }
       });
   assertTrue(s.tryAcquire(WAIT_TIMEOUT_MS, TimeUnit.MILLISECONDS));
   int result = val.get();
   return result;
 }
 private Connection getConnection2(long timeoutMs) throws SQLException {
   // This routine is unsynchronized, because semaphore.tryAcquire() may block.
   synchronized (this) {
     if (isDisposed) {
       throw new IllegalStateException("Connection pool has been disposed.");
     }
   }
   try {
     if (!semaphore.tryAcquire(timeoutMs, TimeUnit.MILLISECONDS)) {
       throw new TimeoutException();
     }
   } catch (InterruptedException e) {
     throw new RuntimeException("Interrupted while waiting for a database connection.", e);
   }
   boolean ok = false;
   try {
     Connection conn = getConnection3();
     ok = true;
     return conn;
   } finally {
     if (!ok) {
       semaphore.release();
     }
   }
 }
  public void close() throws Exception {
    checkOpened();

    writeLock.lock();

    try {

      while (!pendingWrites.await(60000)) {
        HornetQJournalLogger.LOGGER.couldNotGetLock(fileName);
      }

      while (!maxIOSemaphore.tryAcquire(maxIO, 60, TimeUnit.SECONDS)) {
        HornetQJournalLogger.LOGGER.couldNotGetLock(fileName);
      }

      maxIOSemaphore = null;
      if (poller != null) {
        stopPoller();
      }

      if (handler != null) {
        AsynchronousFileImpl.closeInternal(handler);
        AsynchronousFileImpl.addMax(-maxIO);
      }
      opened = false;
      handler = null;
    } finally {
      writeLock.unlock();
    }
  }
 public boolean waitTillNotified(long millisecondsToWait) {
   try {
     return notificationSemaphore.tryAcquire(millisecondsToWait, TimeUnit.MILLISECONDS);
   } catch (InterruptedException e) {
     return false;
   }
 }
 private static String getResultFromQueue(String callId)
     throws JMSException, InterruptedException {
   Destination resultDest = session.createQueue(callId);
   MessageConsumer consumer = session.createConsumer(resultDest);
   final Semaphore messageSem = new Semaphore(0);
   final AtomicReference<String> resultReference = new AtomicReference<String>();
   consumer.setMessageListener(
       new MessageListener() {
         @Override
         public void onMessage(Message message) {
           try {
             String text = ((TextMessage) message).getText();
             resultReference.set(text);
           } catch (JMSException e) {
             throw new RuntimeException(e);
           } finally {
             messageSem.release();
           }
         }
       });
   LOGGER.info("waiting for response");
   if (!messageSem.tryAcquire(10, TimeUnit.SECONDS)) {
     throw new RuntimeException("no response");
   }
   LOGGER.info("response received");
   return resultReference.get();
 }
예제 #10
0
 public void await(Semaphore semaphore) {
   try {
     assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
   } catch (Throwable t) {
     threadUnexpectedException(t);
   }
 }
예제 #11
0
 public boolean putMessage(String message, long timeout) {
   BufferListener listener = listenerRef.get();
   if (listener != null) {
     try {
       if (queue.size() == 0) {
         return listener.onMessage(message);
       } else {
         ArrayList<String> messages = new ArrayList<String>(queue.size() + 1);
         queue.drainTo(messages);
         messages.add(message);
         return listener.onMessages(messages);
       }
     } catch (Throwable t) {
       return false;
     }
   } else {
     try {
       if (!inputSemaphore.tryAcquire(message.length(), timeout, TimeUnit.MILLISECONDS)) {
         return false;
       }
       queue.offer(message);
       return true;
     } catch (InterruptedException e) {
       return false;
     }
   }
 }
예제 #12
0
 private void scheduleReconnect() {
   /*
    * Ensure you are the only one mucking with connections If you find someone
    * else is doing so, then you don't get a turn We trust this other person to
    * do the needful
    */
   if (lock.tryAcquire()) {
     long currentTime = System.currentTimeMillis();
     // Check how long it has been since we reconnected
     try {
       if ((currentTime - connectRequestTime) / 1000 > backoffSeconds) {
         connectRequestTime = currentTime;
         timer.newTimeout(
             new TimerTask() {
               public void run(Timeout timeout) throws Exception {
                 channelSetter.connect();
               }
             },
             backoffSeconds,
             TimeUnit.SECONDS);
       }
     } finally {
       lock.release();
     }
   }
 }
  /**
   * Tries to acquire from the cluster semaphore, and only if that succeeds does it try the pool
   * semaphore.
   *
   * @see java.util.concurrent.Semaphore#tryAcquire(int)
   */
  @Override
  public boolean tryAcquire(int permits) {
    boolean clusterPermitted = clusterSemaphore.tryAcquire(permits);
    boolean poolPermitted = false;

    if (clusterPermitted) {
      poolPermitted = poolSemaphore.tryAcquire(permits);
    }

    if (poolPermitted) {
      return true;
    } else if (clusterPermitted) {
      clusterSemaphore.release(permits);
    }
    return false;
  }
  @Test
  public void testAddListenerCalled() throws Exception {
    final Semaphore flag = new Semaphore(1);

    SimpleTestListener test =
        new SimpleTestListener(
            new Runnable() {
              public void run() {
                flag.release();
              }
            });
    profileCollector.addListener(test, true);

    flag.acquire();
    // Run a task, to be sure our listener gets called at least once
    txnScheduler.runTask(
        new TestAbstractKernelRunnable() {
          // empty task
          public void run() {}
        },
        taskOwner);

    // Calling reports is asynchronous
    flag.tryAcquire(100, TimeUnit.MILLISECONDS);
    assertTrue(test.reportCalls > 0);
  }
예제 #15
0
  @Override
  public void stop() {
    if (bulkRequest.numberOfActions() > 0) {
      executeBulk();
    }
    try {
      if (semaphore.tryAcquire(concurrentRequests, 10, TimeUnit.MINUTES)) {
        semaphore.release(concurrentRequests);
      }
    } catch (InterruptedException e) {
      throw new IllegalStateException(
          "Elasticsearch bulk requests still being executed after 10 minutes", e);
    }
    progress.stop();

    if (!disableRefresh) {
      client.prepareRefresh(indexName).get();
    }
    if (large) {
      // optimize lucene segments and revert index settings
      // Optimization must be done before re-applying replicas:
      // http://www.elasticsearch.org/blog/performance-considerations-elasticsearch-indexing/
      client.prepareForceMerge(indexName).get();

      updateSettings(largeInitialSettings);
    }
    bulkRequest = null;
  }
 public void run() {
   try {
     moved = s.tryAcquire(2, 4, TimeUnit.SECONDS);
   } catch (InterruptedException e) {
     JPADiagramEditorPlugin.logError("Thread interrupted", e); // $NON-NLS-1$		 					
   }
 }
예제 #17
0
 private void waitForOutstandingRequests(
     TimeValue timeOut, Semaphore requestsOutstanding, int maxRequests, String name) {
   long start = System.currentTimeMillis();
   do {
     long msRemaining = timeOut.getMillis() - (System.currentTimeMillis() - start);
     logger.info(
         "[{}] going to try and aquire [{}] in [{}]ms [{}] available to aquire right now",
         name,
         maxRequests,
         msRemaining,
         requestsOutstanding.availablePermits());
     try {
       requestsOutstanding.tryAcquire(maxRequests, msRemaining, TimeUnit.MILLISECONDS);
       return;
     } catch (InterruptedException ie) {
       // Just keep swimming
     }
   } while ((System.currentTimeMillis() - start) < timeOut.getMillis());
   throw new ElasticsearchTimeoutException(
       "Requests were still outstanding after the timeout ["
           + timeOut
           + "] for type ["
           + name
           + "]");
 }
예제 #18
0
 @Override
 protected void setUp() throws Exception {
   super.setUp();
   final Semaphore semaphore = new Semaphore(0);
   ThreadUtils.runOnUiThreadBlocking(
       new Runnable() {
         @Override
         public void run() {
           Profile profile = Profile.getLastUsedProfile();
           mOfflinePageBridge = new OfflinePageBridge(profile);
           if (mOfflinePageBridge.isOfflinePageModelLoaded()) {
             semaphore.release();
           } else {
             mOfflinePageBridge.addObserver(
                 new OfflinePageModelObserver() {
                   @Override
                   public void offlinePageModelLoaded() {
                     semaphore.release();
                     mOfflinePageBridge.removeObserver(this);
                   }
                 });
           }
         }
       });
   assertTrue(semaphore.tryAcquire(TIMEOUT_MS, TimeUnit.MILLISECONDS));
 }
예제 #19
0
  private void savePage(final int expectedResult, final String expectedUrl)
      throws InterruptedException {
    final Semaphore semaphore = new Semaphore(0);
    ThreadUtils.runOnUiThreadBlocking(
        new Runnable() {
          @Override
          public void run() {
            assertNotNull("Tab is null", getActivity().getActivityTab());
            assertEquals(
                "URL does not match requested.",
                TEST_PAGE,
                getActivity().getActivityTab().getUrl());
            assertNotNull("WebContents is null", getActivity().getActivityTab().getWebContents());

            mOfflinePageBridge.savePage(
                getActivity().getActivityTab().getWebContents(),
                BOOKMARK_ID,
                getActivity().getWindowAndroid(),
                new SavePageCallback() {
                  @Override
                  public void onSavePageDone(int savePageResult, String url) {
                    assertEquals("Requested and returned URLs differ.", expectedUrl, url);
                    assertEquals("Save result incorrect.", expectedResult, savePageResult);
                    semaphore.release();
                  }
                });
          }
        });
    assertTrue(semaphore.tryAcquire(TIMEOUT_MS, TimeUnit.MILLISECONDS));
  }
예제 #20
0
 /**
  * @return if <0, then this pipe should be stopped. If ==0, it should not wait. If >0, if it
  *     should wait
  */
 int execute() {
   if (!lock.tryAcquire()) return 1; // currently being accessed
   Thread myThread = Thread.currentThread();
   int threadIndex = -1;
   for (int i = 0; i < threads.length; i++) {
     if (threads[i] == null) {
       threads[i] = myThread;
       threadIndex = i;
       break;
     }
     if (myThread != threads[i]) continue;
     threadIndex = i;
     break;
   }
   Signal signal;
   if (threadIndex < 0) {
     signal = dummySignal;
   } else {
     SignalImpl s = signals[threadIndex];
     s.threadIndex = threadIndex;
     s.signaled = false;
     signal = s;
   }
   boolean hasData;
   try {
     hasData = poll(signal, null);
   } finally {
     signal.signal();
     if (threadIndex < 0) lock.release();
   }
   return 0;
 }
예제 #21
0
 private FutureChannelCreator acquire(
     final FutureChannelCreator futureChannelCreator, final FutureResponse futureResponse) {
   if (oneConnection.tryAcquire()) {
     futureResponse.addListener(
         new BaseFutureAdapter<FutureResponse>() {
           @Override
           public void operationComplete(FutureResponse future) throws Exception {
             oneConnection.release();
             synchronized (map) {
               Iterator<Map.Entry<FutureChannelCreator, FutureResponse>> iterator =
                   map.entrySet().iterator();
               if (iterator.hasNext()) {
                 Map.Entry<FutureChannelCreator, FutureResponse> entry = iterator.next();
                 iterator.remove();
                 acquire(entry.getKey(), entry.getValue());
               }
             }
           }
         });
     futureChannelCreator.reserved(cc);
     return futureChannelCreator;
   } else {
     synchronized (map) {
       map.put(futureChannelCreator, futureResponse);
     }
   }
   return futureChannelCreator;
 }
예제 #22
0
 @Override
 protected void beforeExecute(Thread t, Runnable r) {
   try {
     semaphore.tryAcquire();
   } finally {
     super.beforeExecute(t, r);
   }
 }
예제 #23
0
 public void acquireRead() {
   assert (!readLocks.contains(Thread.currentThread()));
   if (!lock.tryAcquire()) {
     WorkerThread.beginIO();
     lock.acquireUninterruptibly();
     WorkerThread.endIO();
   }
   readLocks.add(Thread.currentThread());
 }
예제 #24
0
  /** Test of setPeriods method, of class PhoneSignalDetector. */
  @Test
  public void testSetPeriods() throws Exception {
    det.start();
    gen.start();

    semaphore.tryAcquire(10, TimeUnit.SECONDS);

    assertTrue("Event not detected", evtDetected);
  }
예제 #25
0
 /**
  * Wait on the given semaphore
  *
  * @param semaphore the semaphore
  * @param n number of permits to acquire
  * @return result of {@link Semaphore#tryAcquire(int, long, TimeUnit)}
  */
 public boolean acquireSemaphore(Semaphore semaphore, int n) {
   Timing m = forWaiting();
   try {
     return semaphore.tryAcquire(n, m.value, m.unit);
   } catch (InterruptedException e) {
     Thread.currentThread().interrupt();
   }
   return false;
 }
 @Test
 public void testNioSingleUseWithInbound() throws Exception {
   final int port = SocketTestUtils.findAvailableServerSocket();
   final CountDownLatch latch = new CountDownLatch(1);
   final Semaphore semaphore = new Semaphore(0);
   final AtomicBoolean done = new AtomicBoolean();
   Executors.newSingleThreadExecutor()
       .execute(
           new Runnable() {
             public void run() {
               try {
                 ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port);
                 latch.countDown();
                 int i = 0;
                 while (true) {
                   Socket socket = server.accept();
                   semaphore.release();
                   byte[] b = new byte[6];
                   readFully(socket.getInputStream(), b);
                   b = ("Reply" + (++i) + "\r\n").getBytes();
                   socket.getOutputStream().write(b);
                 }
               } catch (Exception e) {
                 if (!done.get()) {
                   e.printStackTrace();
                 }
               }
             }
           });
   AbstractConnectionFactory ccf = new TcpNioClientConnectionFactory("localhost", port);
   ByteArrayCrLfSerializer serializer = new ByteArrayCrLfSerializer();
   ccf.setSerializer(serializer);
   ccf.setDeserializer(serializer);
   ccf.setSoTimeout(10000);
   ccf.start();
   ccf.setSingleUse(true);
   TcpSendingMessageHandler handler = new TcpSendingMessageHandler();
   handler.setConnectionFactory(ccf);
   TcpReceivingChannelAdapter adapter = new TcpReceivingChannelAdapter();
   adapter.setConnectionFactory(ccf);
   QueueChannel channel = new QueueChannel();
   adapter.setOutputChannel(channel);
   assertTrue(latch.await(10, TimeUnit.SECONDS));
   handler.handleMessage(MessageBuilder.withPayload("Test").build());
   handler.handleMessage(MessageBuilder.withPayload("Test").build());
   assertTrue(semaphore.tryAcquire(2, 10000, TimeUnit.MILLISECONDS));
   Set<String> replies = new HashSet<String>();
   for (int i = 0; i < 2; i++) {
     Message<?> mOut = channel.receive(10000);
     assertNotNull(mOut);
     replies.add(new String((byte[]) mOut.getPayload()));
   }
   assertTrue(replies.remove("Reply1"));
   assertTrue(replies.remove("Reply2"));
   done.set(true);
 }
예제 #27
0
    void offer(Action action) {
      if (DEBUG) {
        assertOnIcThread();
        Log.d(
            LOGTAG, "offer: Action(" + getConstantName(Action.class, "TYPE_", action.mType) + ")");
      }
      /* Events don't need update because they generate text/selection
      notifications which will do the updating for us */
      if (action.mType != Action.TYPE_EVENT
          && action.mType != Action.TYPE_ACKNOWLEDGE_FOCUS
          && action.mType != Action.TYPE_SET_HANDLER) {
        action.mShouldUpdate = mUpdateGecko;
      }
      if (mActions.isEmpty()) {
        mActionsActive.acquireUninterruptibly();
        mActions.offer(action);
      } else
        synchronized (this) {
          // tryAcquire here in case Gecko thread has just released it
          mActionsActive.tryAcquire();
          mActions.offer(action);
        }

      switch (action.mType) {
        case Action.TYPE_EVENT:
        case Action.TYPE_SET_SELECTION:
        case Action.TYPE_SET_SPAN:
        case Action.TYPE_REMOVE_SPAN:
        case Action.TYPE_SET_HANDLER:
          onImeSynchronize();
          break;

        case Action.TYPE_REPLACE_TEXT:
          // try key events first
          sendCharKeyEvents(action);

          // fall-through

        case Action.TYPE_COMPOSE_TEXT:
          onImeReplaceText(
              action.mStart,
              action.mEnd,
              action.mSequence.toString(),
              action.mType == Action.TYPE_COMPOSE_TEXT);
          break;

        case Action.TYPE_ACKNOWLEDGE_FOCUS:
          onImeAcknowledgeFocus();
          break;

        default:
          throw new IllegalStateException("Action not processed");
      }

      ++mIcUpdateSeqno;
    }
예제 #28
0
 private void process(ByteBuffer buffer, int len) {
   if (len > 0) {
     byte[] b = new byte[len];
     System.arraycopy(buffer.array(), 0, b, 0, len);
     reads.add(b);
     if (notListened.tryAcquire()) {
       listen();
     }
   }
 }
예제 #29
0
 private void waitForRemoteColor(String msgName, Thread t) throws InterruptedException {
   if (!remoteEventLatch.tryAcquire(timeout, timeoutTimeUnit)) {
     t.interrupt();
     throw new RuntimeException(
         msgName
             + "Change color not detected in REMOTE steam after "
             + timeout
             + " "
             + timeoutTimeUnit);
   }
 }
예제 #30
0
 public void waitForEvents(Integer releaseId, Integer sprintId, Integer teamId)
     throws InterruptedException {
   Assert.assertTrue(semaphore.tryAcquire(3, 2000000, TimeUnit.MILLISECONDS));
   sprintService.removeListener(this);
   if (fail.length() > 0) {
     Assert.fail(fail.toString());
   }
   compare(release, releaseId);
   compare(sprint, sprintId);
   compare(team, teamId);
 }