use of java.util.concurrent.Semaphore in project platform_frameworks_base by android.
the class BluetoothTestUtils method enable.
/**
* Enables Bluetooth and checks to make sure that Bluetooth was turned on and that the correct
* actions were broadcast.
*
* @param adapter The BT adapter.
*/
public void enable(BluetoothAdapter adapter) {
writeOutput("Enabling Bluetooth adapter.");
assertFalse(adapter.isEnabled());
int btState = adapter.getState();
final Semaphore completionSemaphore = new Semaphore(0);
final BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (!BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
return;
}
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
if (state == BluetoothAdapter.STATE_ON) {
completionSemaphore.release();
}
}
};
final IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
mContext.registerReceiver(receiver, filter);
assertTrue(adapter.enable());
boolean success = false;
try {
success = completionSemaphore.tryAcquire(ENABLE_DISABLE_TIMEOUT, TimeUnit.MILLISECONDS);
writeOutput(String.format("enable() completed in 0 ms"));
} catch (final InterruptedException e) {
// This should never happen but just in case it does, the test will fail anyway.
}
mContext.unregisterReceiver(receiver);
if (!success) {
fail(String.format("enable() timeout: state=%d (expected %d)", btState, BluetoothAdapter.STATE_ON));
}
}
use of java.util.concurrent.Semaphore in project androidannotations by androidannotations.
the class ThreadActivityTest method parallelBackgroundTasks.
/**
* Verify that non-serialized background tasks <strong>are not</strong>
* serialized (ensure that serial feature does not force all background
* tasks to be serialized).
*
* Start several requests which add an item to a list in background, without
* "@Background" serial attribute enabled.
*
* Once all tasks have completed execution, verify that the items in the
* list are not ordered (with very little false-negative probability).
*/
@Test
public void parallelBackgroundTasks() {
/* number of items to add to the list */
final int NB_ADD = 20;
/* set an executor with 4 threads */
BackgroundExecutor.setExecutor(Executors.newFixedThreadPool(4));
List<Integer> list = Collections.synchronizedList(new ArrayList<Integer>());
/* sem.acquire() will be unlocked exactly after NB_ADD releases */
Semaphore sem = new Semaphore(1 - NB_ADD);
Random random = new Random();
/* execute NB_ADD requests to add an item to the list */
for (int i = 0; i < NB_ADD; i++) {
/*
* wait a random delay (between 0 and 20 milliseconds) to increase
* the probability of wrong order
*/
int delay = random.nextInt(20);
activity.addBackground(list, i, delay, sem);
}
try {
/* wait for all tasks to be completed */
boolean acquired = sem.tryAcquire(MAX_WAITING_TIME, TimeUnit.MILLISECONDS);
Assert.assertTrue("Requested tasks should have completed execution", acquired);
/*
* verify that list items are in the wrong order (the probability it
* is in the right is 1/(NB_ADD!), which is nearly 0)
*/
boolean rightOrder = true;
for (int i = 0; i < NB_ADD && rightOrder; i++) {
rightOrder &= i == list.get(i);
}
Assert.assertFalse("Items should not be in order", rightOrder);
} catch (InterruptedException e) {
Assert.assertFalse("Testing thread should never be interrupted", true);
}
}
use of java.util.concurrent.Semaphore in project androidannotations by androidannotations.
the class ThreadActivityTest method testSerializedBackgroundTasks.
/**
* Verify that serialized background tasks are correctly serialized.
*
* Start several requests which add an item to a list in background, with
* "@Background" serial attribute enabled, so the requests must be executed
* sequentially.
*
* Once all tasks have completed execution, verify that the items in the
* list are ordered.
*/
private void testSerializedBackgroundTasks() {
/* number of items to add to the list */
final int NB_ADD = 10;
/*
* the calls are serialized, but not necessarily on the same thread, so
* we need to synchronize to avoid cache effects
*/
List<Integer> list = Collections.synchronizedList(new ArrayList<Integer>());
/* sem.acquire() will be unlocked exactly after NB_ADD releases */
Semaphore sem = new Semaphore(1 - NB_ADD);
Random random = new Random();
/* execute NB_ADD requests to add an item to the list */
for (int i = 0; i < NB_ADD; i++) {
/*
* wait a random delay (between 0 and 20 milliseconds) to increase
* the probability of wrong order if buggy
*/
int delay = random.nextInt(20);
activity.addSerializedBackground(list, i, delay, sem);
}
try {
/* wait for all tasks to be completed */
boolean acquired = sem.tryAcquire(MAX_WAITING_TIME, TimeUnit.MILLISECONDS);
Assert.assertTrue("Requested tasks should have completed execution", acquired);
for (int i = 0; i < NB_ADD; i++) {
Assert.assertEquals("Items must be in order", i, (int) list.get(i));
}
} catch (InterruptedException e) {
Assert.assertFalse("Testing thread should never be interrupted", true);
}
}
use of java.util.concurrent.Semaphore in project jstorm by alibaba.
the class Drpc method execute.
@Override
public String execute(String function, String args) throws DRPCExecutionException, TException {
LOG.info("Received DRPC request for " + function + " " + args + " at " + (System.currentTimeMillis()));
int idinc = this.ctr.incrementAndGet();
int maxvalue = 1000000000;
int newid = idinc % maxvalue;
if (idinc != newid) {
this.ctr.compareAndSet(idinc, newid);
}
String strid = String.valueOf(newid);
Semaphore sem = new Semaphore(0);
DRPCRequest req = new DRPCRequest(args, strid);
this.idtoStart.put(strid, TimeUtils.current_time_secs());
this.idtoSem.put(strid, sem);
this.idtoFunction.put(strid, function);
this.idtoRequest.put(strid, req);
ConcurrentLinkedQueue<DRPCRequest> queue = acquireQueue(function);
queue.add(req);
LOG.info("Waiting for DRPC request for " + function + " " + args + " at " + (System.currentTimeMillis()));
try {
sem.acquire();
} catch (InterruptedException e) {
LOG.error("acquire fail ", e);
}
LOG.info("Acquired for DRPC request for " + function + " " + args + " at " + (System.currentTimeMillis()));
Object result = this.idtoResult.get(strid);
if (!this.idtoResult.containsKey(strid)) {
// this request is timeout, set exception
result = new DRPCExecutionException("Request timed out");
}
LOG.info("Returning for DRPC request for " + function + " " + args + " at " + (System.currentTimeMillis()));
this.cleanup(strid);
if (result instanceof DRPCExecutionException) {
throw (DRPCExecutionException) result;
}
return String.valueOf(result);
}
use of java.util.concurrent.Semaphore in project jstorm by alibaba.
the class Drpc method result.
@Override
public void result(String id, String result) throws TException {
Semaphore sem = this.idtoSem.get(id);
LOG.info("Received result " + result + " for id " + id + " at " + (System.currentTimeMillis()));
if (sem != null) {
this.idtoResult.put(id, result);
sem.release();
}
}
Aggregations