1 // Copyright 2017 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.
4 
5 package org.chromium.base;
6 
7 import android.os.Handler;
8 import android.os.Process;
9 
10 import org.chromium.base.annotations.CalledByNative;
11 import org.chromium.base.annotations.CalledByNativeUnchecked;
12 import org.chromium.base.annotations.JNINamespace;
13 
14 import java.util.concurrent.atomic.AtomicBoolean;
15 
16 @JNINamespace("base::android")
17 class JavaHandlerThreadHelpers {
18     private static class TestException extends Exception {}
19 
20     // This is executed as part of base_unittests. This tests that JavaHandlerThread can be used
21     // by itself without attaching to its native peer.
22     @CalledByNative
testAndGetJavaHandlerThread()23     private static JavaHandlerThread testAndGetJavaHandlerThread() {
24         final AtomicBoolean taskExecuted = new AtomicBoolean();
25         final Object lock = new Object();
26         Runnable runnable = new Runnable() {
27             @Override
28             public void run() {
29                 synchronized (lock) {
30                     taskExecuted.set(true);
31                     lock.notifyAll();
32                 }
33             }
34         };
35 
36         JavaHandlerThread thread =
37                 new JavaHandlerThread("base_unittests_java", Process.THREAD_PRIORITY_DEFAULT);
38         thread.maybeStart();
39 
40         Handler handler = new Handler(thread.getLooper());
41         handler.post(runnable);
42         synchronized (lock) {
43             while (!taskExecuted.get()) {
44                 try {
45                     lock.wait();
46                 } catch (InterruptedException e) {
47                     // ignore interrupts
48                 }
49             }
50         }
51 
52         return thread;
53     }
54 
55     @CalledByNativeUnchecked
throwException()56     private static void throwException() throws TestException {
57         throw new TestException();
58     }
59 
60     @CalledByNative
isExceptionTestException(Throwable exception)61     private static boolean isExceptionTestException(Throwable exception) {
62         if (exception == null) return false;
63         return exception instanceof TestException;
64     }
65 }
66