Java Code Examples for java.util.concurrent.Semaphore#acquireUninterruptibly()

The following examples show how to use java.util.concurrent.Semaphore#acquireUninterruptibly() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PCDHIntegrationModuleImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public void convertEncryptedContentToProduct(SingleMessageWrapper wrapper) throws IntegrationModuleException {
   Semaphore availableThread = new Semaphore(this.threadLimit, true);
   EncryptionToken systemETK = this.getSystemETKFromCache();
   List<String> uniqueEncryptionKeys = wrapper.getAllUniqueMedicationHistoryEntriesEncryptionIds();
   LOG.info("uniqueEncryptionKeys.size = " + uniqueEncryptionKeys.size());
   this.loadEncryptionKeysToCache(uniqueEncryptionKeys, systemETK);
   LOG.debug("******************* convertEncryptedContentToProduct ***********************");
   if (uniqueEncryptionKeys.size() > 0) {
      Iterator var6 = wrapper.getAllMedicationHistoryEntries().iterator();

      while(var6.hasNext()) {
         MedicationHistoryType medicationHistoryType = (MedicationHistoryType)var6.next();
         ProductDecryptorThread productDecryptorThread = new ProductDecryptorThread(availableThread, medicationHistoryType, systemETK.getEncoded(), this, this.getKgssCache());
         availableThread.acquireUninterruptibly();
         productDecryptorThread.start();
      }

      try {
         availableThread.acquireUninterruptibly(this.threadLimit);
      } catch (IllegalArgumentException var8) {
         LOG.debug("Incorrect Thread configuration : " + var8);
      }
   }

   LOG.debug("******************* convertEncryptedContentToProduct DONE ***********************");
}
 
Example 2
Source File: GetGraphImage.java    From constellation with Apache License 2.0 6 votes vote down vote up
@Override
public void callService(final PluginParameters parameters, final InputStream in, final OutputStream out) throws IOException {
    final Graph graph = GraphManager.getDefault().getActiveGraph();

    // This is asynchronous, so we need a Semaphore.
    //
    final GraphNode graphNode = GraphNode.getGraphNode(graph);
    final VisualManager visualManager = graphNode.getVisualManager();
    final BufferedImage[] img1 = new BufferedImage[1];

    if (visualManager != null) {
        final Semaphore waiter = new Semaphore(0);
        visualManager.exportToBufferedImage(img1, waiter);
        waiter.acquireUninterruptibly();

        ImageIO.write(img1[0], "png", out);
    } else {
        throw new IOException("Graph image unavailable");
    }
}
 
Example 3
Source File: CheckedLockLoops.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
final int loop(int n) {
    final Semaphore sem = this.sem;
    int sum = 0;
    int x = 0;
    while (n-- > 0) {
        sem.acquireUninterruptibly();
        try {
            x = setValue(LoopHelpers.compute1(getValue()));
        }
        finally {
            sem.release();
        }
        sum += LoopHelpers.compute2(x);
    }
    return sum;
}
 
Example 4
Source File: VideoStream.java    From libstreaming with Apache License 2.0 6 votes vote down vote up
/**
 * Opens the camera in a new Looper thread so that the preview callback is not called from the main thread
 * If an exception is thrown in this Looper thread, we bring it back into the main thread.
 * @throws RuntimeException Might happen if another app is already using the camera.
 */
private void openCamera() throws RuntimeException {
	final Semaphore lock = new Semaphore(0);
	final RuntimeException[] exception = new RuntimeException[1];
	mCameraThread = new Thread(new Runnable() {
		@Override
		public void run() {
			Looper.prepare();
			mCameraLooper = Looper.myLooper();
			try {
				mCamera = Camera.open(mCameraId);
			} catch (RuntimeException e) {
				exception[0] = e;
			} finally {
				lock.release();
				Looper.loop();
			}
		}
	});
	mCameraThread.start();
	lock.acquireUninterruptibly();
	if (exception[0] != null) throw new CameraInUseException(exception[0].getMessage());
}
 
Example 5
Source File: BackgroundThreadPosterTest.java    From thread-poster with Apache License 2.0 6 votes vote down vote up
@Test
public void execute_multipleRunnablesIndependent_executionSuccessful() throws Exception {
    // Arrange
    final Semaphore semaphore = new Semaphore(-1);
    Runnable runnable1 = new Runnable() {
        @Override
        public void run() {
            semaphore.release();
        }
    };
    Runnable runnable2 = new Runnable() {
        @Override
        public void run() {
            semaphore.release();
        }
    };
    // Act
    SUT.post(runnable1);
    SUT.post(runnable2);
    // Assert
    semaphore.acquireUninterruptibly();
}
 
Example 6
Source File: BackgroundThreadPosterTestDoubleTest.java    From thread-poster with Apache License 2.0 6 votes vote down vote up
@Test
public void executeThenJoin_multipleRunnablesInterdependent_sideEffectsNotVisibleBeforeJoin() throws Exception {
    // Arrange
    final Counter counter = new Counter();
    final Semaphore semaphore = new Semaphore(0);
    Runnable runnable1 = new Runnable() {
        @Override
        public void run() {
            semaphore.acquireUninterruptibly();
            counter.increment();
        }
    };
    Runnable runnable2 = new Runnable() {
        @Override
        public void run() {
            semaphore.release();
            counter.increment();
        }
    };
    // Act
    SUT.post(runnable1);
    SUT.post(runnable2);
    // Assert
    Thread.sleep(TEST_DELAY_MS);
    assertThat(counter.getCount(), is(0));
}
 
Example 7
Source File: AwexTest.java    From awex with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 5000)
public void shouldBeMarkedAsCancelledInterruptingGracefullyTheTaskOnCancel() {
    setUpAwex();

    final Semaphore workIsRunning = new Semaphore(0);
    mTaskPromise = mAwex.submit(new Task<Integer, Float>() {

        @Override
        protected Integer run() throws InterruptedException {
            workIsRunning.release();
            while(!isCancelled()) {
                mAwex.provideLogger().v("I'm doing something");
            }
            mExecutionFlag = true;
            workIsRunning.release();
            return null;
        }
    });

    workIsRunning.acquireUninterruptibly();
    mTaskPromise.cancelTask(true);

    assertEquals(Promise.STATE_CANCELLED, mTaskPromise.getState());
    workIsRunning.acquireUninterruptibly();
    assertTrue(mExecutionFlag);
}
 
Example 8
Source File: PartitionedScheduledExecutorTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testRunningJobIsInterruptedAfterShutdownNow() throws InterruptedException {
  ExecutorService worker = Executors.newSingleThreadExecutor();
  try {
    PartitionedScheduledExecutor executor = new PartitionedScheduledExecutor(scheduler, worker);

    final Semaphore jobSemaphore = new Semaphore(0);
    final Semaphore testSemaphore = new Semaphore(0);
    final AtomicBoolean interrupted = new AtomicBoolean();

    executor.submit(() -> {
      testSemaphore.release();
      try {
        jobSemaphore.acquire();
      } catch (InterruptedException e) {
        interrupted.set(true);
      }
    });
    testSemaphore.acquireUninterruptibly();
    assertThat(executor.shutdownNow(), empty());
    assertThat(executor.awaitTermination(2, MINUTES), is(true));
    assertThat(executor.isShutdown(), is(true));
    assertThat(executor.isTerminated(), is(true));

    assertThat(jobSemaphore.availablePermits(), is(0));
    assertThat(interrupted.get(), is(true));
  } finally {
    worker.shutdown();
  }
}
 
Example 9
Source File: PartitionedOrderedExecutorTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testQueuedJobRunsAfterShutdown() throws InterruptedException {
  BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>();
  ExecutorService service = Executors.newSingleThreadExecutor();
  try {
    PartitionedOrderedExecutor executor = new PartitionedOrderedExecutor(queue, service);

    final Semaphore jobSemaphore = new Semaphore(0);
    final Semaphore testSemaphore = new Semaphore(0);

    executor.submit(() -> {
      testSemaphore.release();
      jobSemaphore.acquireUninterruptibly();
    });
    executor.submit((Runnable) jobSemaphore::acquireUninterruptibly);
    testSemaphore.acquireUninterruptibly();
    executor.shutdown();
    assertThat(executor.awaitTermination(100, MILLISECONDS), is(false));
    assertThat(executor.isShutdown(), is(true));
    assertThat(executor.isTerminated(), is(false));

    jobSemaphore.release();
    assertThat(executor.awaitTermination(100, MILLISECONDS), is(false));
    assertThat(executor.isShutdown(), is(true));
    assertThat(executor.isTerminated(), is(false));

    jobSemaphore.release();
    assertThat(executor.awaitTermination(2, MINUTES), is(true));
    assertThat(executor.isShutdown(), is(true));
    assertThat(executor.isTerminated(), is(true));

    assertThat(jobSemaphore.availablePermits(), is(0));
  } finally {
    service.shutdown();
  }
}
 
Example 10
Source File: GwtDevTask.java    From putnami-gradle-plugin with GNU Lesser General Public License v3.0 5 votes vote down vote up
private JavaAction execSdm() {
	PutnamiExtension putnami = getProject().getExtensions().getByType(PutnamiExtension.class);
	DevOption devOption = putnami.getDev();
	if (!Strings.isNullOrEmpty(putnami.getSourceLevel()) &&
		Strings.isNullOrEmpty(devOption.getSourceLevel())) {
		devOption.setSourceLevel(putnami.getSourceLevel());
	}

	CodeServerBuilder sdmBuilder = new CodeServerBuilder();
	if (!putnami.getGwtVersion().startsWith("2.6")) {
		sdmBuilder.addArg("-launcherDir", devOption.getWar());
	}
	sdmBuilder.configure(getProject(), putnami.getDev(), getModules());

	final JavaAction sdmAction = sdmBuilder.buildJavaAction();

	final Semaphore lock = new Semaphore(1);

	sdmAction.setInfoLogger(new ProcessLogger() {
		private boolean started = false;

		@Override
		protected void printLine(String line) {
			super.printLine(line);
			if (line.contains("The code server is ready")) {
				this.started = true;
				lock.release();
			}
			if (!started && line.contains("[ERROR]")) {
				sdmAction.kill();
				lock.release();
			}
		}
	});

	lock.acquireUninterruptibly();
	sdmAction.execute(this);
	lock.acquireUninterruptibly();
	return sdmAction;
}
 
Example 11
Source File: KeyLocker.java    From Paper with Apache License 2.0 5 votes vote down vote up
void acquireGlobal() {
    // Set global block
    global.acquireUninterruptibly();
    // And wait for other keys to be released
    for (Semaphore semaphore : semaphoreMap.values()) {
        semaphore.acquireUninterruptibly();
    }
}
 
Example 12
Source File: WalletAPI.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
public static void sendTransactionFromName(final String name, final String key, final String to, final long amount, final long fee, final Callback<Boolean> onComplete) {
    AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
        private DecentWalletManager decent_ = null;
        private Boolean status_ = false;
        @Override
        protected Void doInBackground(Void... voids) {
            Log.d("flint", "createTransactionFromName... to="+to + ", amount="+amount + ", fee="+fee);
            final Semaphore waiter = new Semaphore(1);
            waiter.acquireUninterruptibly();
            decent_ = new DecentWalletManager(CONNECTION_ADDRESS, new DecentAdapter() {
                @Override public void onWalletImported() {decent_.finishRequest();decent_.createTransactionFromName(to, amount, fee);Log.d("flint", "sendTransactionFromName.onWalletImported");}
                @Override public void onTransactionCreated(DecentTransaction transaction) {decent_.finishRequest();decent_.pushTransaction(transaction);Log.d("flint", "sendTransactionFromName.onTransactionCreated");}
                @Override public void onTransactionPushed(DecentTransaction transaction) {status_=true;decent_.finishRequest();waiter.release();Log.d("flint", "sendTransactionFromNamesendTransactionFromName.onTransactionPushed");}
                @Override public void onError(Exception e) {waiter.release();Log.d("flint", "createTransactionFromName.onError: " + e.toString());}
            });
            Log.d("flint", "sendTransactionFromName.importWallet... ");
            decent_.importWallet(name, key);
            try {waiter.tryAcquire(TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);} catch (InterruptedException e) {}
            return null;
        }
        @Override
        protected void onPostExecute(Void result) {
            Log.d("flint", "createTransactionFromName done");
            if (onComplete != null)
                onComplete.onResponse(status_);
        }
    };

    task.execute();
}
 
Example 13
Source File: WalletAPI.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
public static void getBalance(final String name, final String key, final Callback<Long> onComplete) {
    AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
        private DecentWalletManager decent_ = null;
        private BigInteger res_ = BigInteger.valueOf(0);
        @Override
        protected Void doInBackground(Void... voids) {
            final Semaphore waiter = new Semaphore(1);
            waiter.acquireUninterruptibly();
            res_ = BigInteger.valueOf(0);
            decent_ = new DecentWalletManager(CONNECTION_ADDRESS, new DecentAdapter() {
                @Override public void onWalletImported() {decent_.finishRequest();decent_.getBalance();Log.d("flint", "getBalance.onWalletImported");}
                @Override public void onBalanceGot(BigInteger balance) {res_ = balance;decent_.finishRequest();waiter.release();Log.d("flint", "getBalance.onBalanceGot " + res_);}
                @Override public void onError(Exception e) {waiter.release();Log.d("flint", "getBalance.onError: " + e.toString());}
            });
            Log.d("flint", "getBalance.importWallet... ");
            decent_.importWallet(name, key);
            try {waiter.tryAcquire(TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);} catch (InterruptedException e) {}
            return null;
        }
        @Override
        protected void onPostExecute(Void result) {
            if (onComplete != null)
                onComplete.onResponse(res_.longValue());
        }
    };

    task.execute();
}
 
Example 14
Source File: DistributedConsensusLoadTest.java    From onos with Apache License 2.0 5 votes vote down vote up
private void startTest() {
    stopped.set(false);
    RateLimiter limiter = RateLimiter.create(rate);
    Semaphore s = new Semaphore(100);
    while (!stopped.get()) {
        limiter.acquire();
        s.acquireUninterruptibly();
        counters.get(RandomUtils.nextInt(TOTAL_COUNTERS)).incrementAndGet().whenComplete((r, e) -> {
            s.release();
            if (e == null) {
                increments.incrementAndGet();
            }
        });
    }
}
 
Example 15
Source File: WalletAPI.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
public static void isWalletExist(final String name, final Callback2<Boolean,Boolean> onComplete) {
    AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
        private DecentWalletManager decent_ = null;
        private Boolean result_ = false;
        private Boolean status_ = false;
        @Override
        protected Void doInBackground(Void... voids) {
            final Semaphore waiter = new Semaphore(1);
            waiter.acquireUninterruptibly();
            decent_ = new DecentWalletManager(CONNECTION_ADDRESS, new DecentAdapter() {
                @Override public void onWalletExistenceChecked(boolean isExist, String name) {result_=isExist;status_=true;decent_.finishRequest();waiter.release();}
                @Override public void onError(Exception e) {waiter.release();Log.d("flint", "createTransactionFromName.onError: " + e.toString());}
            }, WalletWords.getWords(GuardaApp.context_s));
            Log.d("flint", "sendTransactionFromName.importWallet... ");
            decent_.isWalletExist(name);
            try {waiter.tryAcquire(TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);} catch (InterruptedException e) {}
            return null;
        }
        @Override
        protected void onPostExecute(Void result) {
            Log.d("flint", "createTransactionFromName done");
            if (onComplete != null)
                onComplete.onResponse(result_, status_);
        }
    };

    task.execute();
}
 
Example 16
Source File: PartitionedUnorderedExecutorTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testRunningJobsAreInterruptedAfterShutdownNow() throws InterruptedException {
  final int jobCount = 4;

  BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>();
  ExecutorService service = Executors.newCachedThreadPool();
  try {
    PartitionedUnorderedExecutor executor = new PartitionedUnorderedExecutor(queue, service, jobCount);

    final Semaphore jobSemaphore = new Semaphore(0);
    final Semaphore testSemaphore = new Semaphore(0);
    final AtomicInteger interrupted = new AtomicInteger();

    for (int i = 0; i < jobCount; i++) {
      executor.submit(() -> {
        testSemaphore.release();
        try {
          jobSemaphore.acquire();
        } catch (InterruptedException e) {
          interrupted.incrementAndGet();
        }
      });
    }

    testSemaphore.acquireUninterruptibly(jobCount);

    assertThat(executor.shutdownNow(), empty());
    assertThat(executor.awaitTermination(2, MINUTES), is(true));
    assertThat(executor.isShutdown(), is(true));
    assertThat(executor.isTerminated(), is(true));

    assertThat(jobSemaphore.availablePermits(), is(0));
    assertThat(interrupted.get(), is(jobCount));
  } finally {
    service.shutdown();
  }
}
 
Example 17
Source File: PartitionedUnorderedExecutorTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testRunningJobIsInterruptedAfterShutdownNow() throws InterruptedException {
  BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>();
  ExecutorService service = Executors.newSingleThreadExecutor();
  try {
    PartitionedUnorderedExecutor executor = new PartitionedUnorderedExecutor(queue, service, 1);

    final Semaphore jobSemaphore = new Semaphore(0);
    final Semaphore testSemaphore = new Semaphore(0);
    final AtomicBoolean interrupted = new AtomicBoolean();

    executor.submit(() -> {
      testSemaphore.release();
      try {
        jobSemaphore.acquire();
      } catch (InterruptedException e) {
        interrupted.set(true);
      }
    });
    testSemaphore.acquireUninterruptibly();
    assertThat(executor.shutdownNow(), empty());
    assertThat(executor.awaitTermination(2, MINUTES), is(true));
    assertThat(executor.isShutdown(), is(true));
    assertThat(executor.isTerminated(), is(true));

    assertThat(jobSemaphore.availablePermits(), is(0));
    assertThat(interrupted.get(), is(true));
  } finally {
    service.shutdown();
  }
}
 
Example 18
Source File: MySemaphore.java    From ThreadProject with MIT License 5 votes vote down vote up
public static void main(String args[]){
    ExecutorService list=Executors.newCachedThreadPool();
    Semaphore position=new Semaphore(2);
    for(int i=0;i<10;i++){
     list.submit(new MySemaphore(i+1,position));
    }
    list.shutdown();
    position.acquireUninterruptibly(2);
    System.out.println("使用完毕,需要清扫了");
    position.release(2);
}
 
Example 19
Source File: Shell.java    From berkeleyparser with GNU General Public License v2.0 5 votes vote down vote up
StreamGobbler(InputStream is, String prefix, boolean echo) {
	this.is = is;
	semaphore = new Semaphore(1);
	semaphore.acquireUninterruptibly();
	this.echo = echo;
	this.prefix = prefix;
}
 
Example 20
Source File: WalletAPI.java    From guarda-android-wallets with GNU General Public License v3.0 4 votes vote down vote up
public static void getTransactionList(final String name, final String key, final Callback<Vector<DecentTransaction>> onComplete) {
    AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
        private DecentWalletManager decent_ = null;
        private Vector<DecentTransaction> transactionsRes_ = null;
        @Override
        protected Void doInBackground(Void... voids) {
            final Semaphore waiter = new Semaphore(1);
            waiter.acquireUninterruptibly();
            transactionsRes_ = new Vector<>();
            decent_ = new DecentWalletManager(CONNECTION_ADDRESS, new DecentAdapter() {
                @Override
                public void onWalletImported() {
                    decent_.finishRequest();
                    decent_.getTransactions(200);
                    Log.d("flint", "getTransactionList.onWalletImported");
                }

                @Override
                public void onTransactionsGot(Vector<DecentTransaction> transactions) {
                    transactionsRes_ = transactions;
                    decent_.finishRequest();
                    waiter.release();
                    Log.d("flint", "getTransactionList.onTransactionsGot");
                }

                @Override
                public void onError(Exception e) {
                    waiter.release();
                    Log.d("flint", "getTransactionList.onError: " + e.toString());
                }
            }, WalletWords.getWords(GuardaApp.context_s));

            Log.d("flint", "getTransactionList.importWallet... ");
            decent_.importWallet(name, key);
            try {
                waiter.tryAcquire(TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
            } catch (InterruptedException e) {}
            return null;
        }
        @Override
        protected void onPostExecute(Void result) {
            Log.d("flint", "getTransactionList done, transactions count: " + transactionsRes_.size());
            if (onComplete != null)
                onComplete.onResponse(transactionsRes_);
        }
    };

    task.execute();
}