1 /*
2  * Copyright (C) 2017 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package art;
18 
19 import java.util.Arrays;
20 
21 public class Test1907 {
22   public static final Object lock = new Object();
23 
waitFor(long millis)24   public static void waitFor(long millis) {
25     try {
26       lock.wait(millis);
27     } catch (Exception e) {
28       System.out.println("Unexpected error: " + e);
29       e.printStackTrace();
30     }
31   }
32 
waitForSuspension(Thread target)33   public static void waitForSuspension(Thread target) {
34     while (!Suspension.isSuspended(target)) {
35       waitFor(100);
36     }
37   }
38 
run()39   public static void run() {
40     synchronized (lock) {
41       Thread thrd = new Thread(
42           () -> {
43             try {
44               // Put self twice in the suspend list
45               System.out.println("Suspend self twice returned: " +
46                   Arrays.toString(
47                       Suspension.suspendList(Thread.currentThread(), Thread.currentThread())));
48             } catch (Throwable t) {
49               System.out.println("Unexpected error occurred " + t);
50               t.printStackTrace();
51               Runtime.getRuntime().halt(2);
52             }
53           },
54           "TARGET THREAD");
55       try {
56         thrd.start();
57 
58         // Wait for at least one suspend to happen.
59         waitForSuspension(thrd);
60 
61         // Wake it up.
62         Suspension.resume(thrd);
63         waitFor(1000);
64 
65         // Is it suspended.
66         if (Suspension.isSuspended(thrd)) {
67           Suspension.resume(thrd);
68           thrd.join();
69           System.out.println("Thread was still suspended after one resume.");
70         } else {
71           thrd.join();
72           System.out.println("Thread was no longer suspended after one resume.");
73         }
74 
75       } catch (Throwable t) {
76         System.out.println("something was thrown. Runtime might be in unrecoverable state: " + t);
77         t.printStackTrace();
78         Runtime.getRuntime().halt(2);
79       }
80     }
81   }
82 }
83