1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 package org.chromium.mojo.bindings;
7 import android.test.suitebuilder.annotation.SmallTest;
9 import org.chromium.mojo.MojoTestCase;
10 import org.chromium.mojo.system.impl.CoreImpl;
12 import java.util.ArrayList;
13 import java.util.List;
14 import java.util.concurrent.BrokenBarrierException;
15 import java.util.concurrent.CyclicBarrier;
16 import java.util.concurrent.Executor;
17 import java.util.concurrent.ExecutorService;
18 import java.util.concurrent.Executors;
21 * Testing the executor factory.
23 public class ExecutorFactoryTest extends MojoTestCase {
25 private static final long RUN_LOOP_TIMEOUT_MS = 50;
26 private static final int CONCURRENCY_LEVEL = 5;
27 private static final ExecutorService WORKERS = Executors.newFixedThreadPool(CONCURRENCY_LEVEL);
29 private Executor mExecutor;
30 private List<Thread> mThreadContainer;
33 * @see MojoTestCase#setUp()
36 protected void setUp() throws Exception {
38 mExecutor = ExecutorFactory.getExecutorForCurrentThread(CoreImpl.getInstance());
39 mThreadContainer = new ArrayList<Thread>();
43 * Testing the {@link Executor} when called from the executor thread.
46 public void testExecutorOnCurrentThread() {
47 Runnable action = new Runnable() {
50 mThreadContainer.add(Thread.currentThread());
53 mExecutor.execute(action);
54 mExecutor.execute(action);
55 assertEquals(0, mThreadContainer.size());
56 runLoop(RUN_LOOP_TIMEOUT_MS);
57 assertEquals(2, mThreadContainer.size());
58 for (Thread thread : mThreadContainer) {
59 assertEquals(Thread.currentThread(), thread);
64 * Testing the {@link Executor} when called from another thread.
67 public void testExecutorOnOtherThread() {
68 final CyclicBarrier barrier = new CyclicBarrier(CONCURRENCY_LEVEL + 1);
69 for (int i = 0; i < CONCURRENCY_LEVEL; ++i) {
70 WORKERS.execute(new Runnable() {
73 mExecutor.execute(new Runnable() {
77 mThreadContainer.add(Thread.currentThread());
82 } catch (InterruptedException e) {
83 fail("Unexpected exception: " + e.getMessage());
84 } catch (BrokenBarrierException e) {
85 fail("Unexpected exception: " + e.getMessage());
92 } catch (InterruptedException e) {
93 fail("Unexpected exception: " + e.getMessage());
94 } catch (BrokenBarrierException e) {
95 fail("Unexpected exception: " + e.getMessage());
97 assertEquals(0, mThreadContainer.size());
98 runLoop(RUN_LOOP_TIMEOUT_MS);
99 assertEquals(CONCURRENCY_LEVEL, mThreadContainer.size());
100 for (Thread thread : mThreadContainer) {
101 assertEquals(Thread.currentThread(), thread);