Search in sources :

Example 16 with Semaphore

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));
    }
}
Also used : Context(android.content.Context) IntentFilter(android.content.IntentFilter) Intent(android.content.Intent) Semaphore(java.util.concurrent.Semaphore) BroadcastReceiver(android.content.BroadcastReceiver)

Example 17 with Semaphore

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);
    }
}
Also used : Random(java.util.Random) Semaphore(java.util.concurrent.Semaphore) Test(org.junit.Test)

Example 18 with Semaphore

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);
    }
}
Also used : Random(java.util.Random) Semaphore(java.util.concurrent.Semaphore)

Example 19 with Semaphore

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);
}
Also used : DRPCRequest(backtype.storm.generated.DRPCRequest) DRPCExecutionException(backtype.storm.generated.DRPCExecutionException) Semaphore(java.util.concurrent.Semaphore)

Example 20 with Semaphore

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();
    }
}
Also used : Semaphore(java.util.concurrent.Semaphore)

Aggregations

Semaphore (java.util.concurrent.Semaphore)511 Test (org.junit.Test)198 IOException (java.io.IOException)55 Context (android.content.Context)39 InvocationOnMock (org.mockito.invocation.InvocationOnMock)38 ArrayList (java.util.ArrayList)37 HashMap (java.util.HashMap)36 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)31 AtomicReference (java.util.concurrent.atomic.AtomicReference)31 ExecutionException (java.util.concurrent.ExecutionException)30 File (java.io.File)29 Intent (android.content.Intent)27 List (java.util.List)27 Map (java.util.Map)26 CountDownLatch (java.util.concurrent.CountDownLatch)25 Handler (android.os.Handler)24 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)24 HazelcastInstance (com.hazelcast.core.HazelcastInstance)21 BroadcastReceiver (android.content.BroadcastReceiver)20 IntentFilter (android.content.IntentFilter)20