1/*
2 * Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 */
23
24/*
25 * @test
26 * @bug     4530538
27 * @summary Basic test of ThreadMXBean.getThreadCpuTime and
28 *          getCurrentThreadCpuTime.
29 * @author  Mandy Chung
30 */
31
32import java.lang.management.*;
33
34public class ThreadCpuTime {
35    private static ThreadMXBean mbean = ManagementFactory.getThreadMXBean();
36    private static boolean testFailed = false;
37    private static boolean done = false;
38    private static Object obj = new Object();
39    private static final int NUM_THREADS = 10;
40    private static Thread[] threads = new Thread[NUM_THREADS];
41    private static long[] times = new long[NUM_THREADS];
42
43    // careful about this value
44    private static final int DELTA = 100;
45
46    public static void main(String[] argv)
47        throws Exception {
48        if (!mbean.isCurrentThreadCpuTimeSupported()) {
49            return;
50        }
51
52       // disable CPU time
53        if (mbean.isThreadCpuTimeEnabled()) {
54            mbean.setThreadCpuTimeEnabled(false);
55        }
56
57        Thread curThread = Thread.currentThread();
58        long t = mbean.getCurrentThreadCpuTime();
59        if (t != -1) {
60            throw new RuntimeException("Invalid CurrenThreadCpuTime returned = " +
61                t + " expected = -1");
62        }
63
64        if (mbean.isThreadCpuTimeSupported()) {
65            long t1 = mbean.getThreadCpuTime(curThread.getId());
66            if (t1 != -1) {
67                throw new RuntimeException("Invalid ThreadCpuTime returned = " +
68                    t1 + " expected = -1");
69            }
70        }
71
72        // Enable CPU Time measurement
73        if (!mbean.isThreadCpuTimeEnabled()) {
74            mbean.setThreadCpuTimeEnabled(true);
75        }
76
77        if (!mbean.isThreadCpuTimeEnabled()) {
78            throw new RuntimeException("ThreadCpuTime is expected to be enabled");
79        }
80
81        long time = mbean.getCurrentThreadCpuTime();
82        if (time < 0) {
83            throw new RuntimeException("Invalid CPU time returned = " + time);
84        }
85
86        if (!mbean.isThreadCpuTimeSupported()) {
87            return;
88        }
89
90
91        // Expected to be time1 >= time
92        long time1 = mbean.getThreadCpuTime(curThread.getId());
93        if (time1 < time) {
94            throw new RuntimeException("CPU time " + time1 +
95                " expected >= " + time);
96        }
97        System.out.println(curThread.getName() +
98            " Current Thread Cpu Time = " + time +
99            " CPU time = " + time1);
100
101        for (int i = 0; i < NUM_THREADS; i++) {
102            threads[i] = new MyThread("MyThread-" + i);
103            threads[i].start();
104        }
105
106        waitUntilThreadBlocked();
107
108        for (int i = 0; i < NUM_THREADS; i++) {
109            times[i] = mbean.getThreadCpuTime(threads[i].getId());
110        }
111
112        goSleep(200);
113
114        for (int i = 0; i < NUM_THREADS; i++) {
115            long newTime = mbean.getThreadCpuTime(threads[i].getId());
116            if (times[i] > newTime) {
117                throw new RuntimeException("TEST FAILED: " +
118                    threads[i].getName() +
119                    " previous CPU time = " + times[i] +
120                    " > current CPU time = " + newTime);
121            }
122            if ((times[i] + DELTA) < newTime) {
123                throw new RuntimeException("TEST FAILED: " +
124                    threads[i].getName() +
125                    " CPU time = " + newTime +
126                    " previous CPU time " + times[i] +
127                    " out of expected range");
128            }
129
130            System.out.println(threads[i].getName() +
131                " Previous Cpu Time = " + times[i] +
132                " Current CPU time = " + newTime);
133        }
134
135        synchronized (obj) {
136            done = true;
137            obj.notifyAll();
138        }
139
140        for (int i = 0; i < NUM_THREADS; i++) {
141            try {
142                threads[i].join();
143            } catch (InterruptedException e) {
144                System.out.println("Unexpected exception is thrown.");
145                e.printStackTrace(System.out);
146                testFailed = true;
147                break;
148            }
149        }
150        if (testFailed) {
151            throw new RuntimeException("TEST FAILED");
152        }
153
154        System.out.println("Test passed");
155    }
156
157
158    private static void goSleep(long ms) throws Exception {
159        try {
160            Thread.sleep(ms);
161        } catch (InterruptedException e) {
162            System.out.println("Unexpected exception is thrown.");
163            throw e;
164        }
165    }
166
167    private static void waitUntilThreadBlocked()
168        throws Exception {
169        int count = 0;
170        while (count != NUM_THREADS) {
171            goSleep(100);
172            count = 0;
173            for (int i = 0; i < NUM_THREADS; i++) {
174                ThreadInfo info = mbean.getThreadInfo(threads[i].getId());
175                if (info.getThreadState() == Thread.State.WAITING) {
176                    count++;
177                }
178            }
179        }
180    }
181
182    static class MyThread extends Thread {
183        public MyThread(String name) {
184            super(name);
185        }
186
187        public void run() {
188            double sum = 0;
189            for (int i = 0; i < 5000; i++) {
190               double r = Math.random();
191               double x = Math.pow(3, r);
192               sum += x - r;
193            }
194            synchronized (obj) {
195                while (!done) {
196                    try {
197                        obj.wait();
198                    } catch (InterruptedException e) {
199                        System.out.println("Unexpected exception is thrown.");
200                        e.printStackTrace(System.out);
201                        testFailed = true;
202                        break;
203                    }
204                }
205            }
206
207            sum = 0;
208            for (int i = 0; i < 5000; i++) {
209               double r = Math.random();
210               double x = Math.pow(3, r);
211               sum += x - r;
212            }
213
214            long utime1 = mbean.getCurrentThreadUserTime();
215            long utime2 = mbean.getThreadUserTime(getId());
216            long time1 = mbean.getCurrentThreadCpuTime();
217            long time2 = mbean.getThreadCpuTime(getId());
218
219            System.out.println(getName() + ": " +
220                "CurrentThreadUserTime = " + utime1 +
221                " ThreadUserTime = " + utime2);
222            System.out.println(getName() + ": " +
223                "CurrentThreadCpuTime  = " + time1 +
224                " ThreadCpuTime  = " + time2);
225
226            if (time1 > time2) {
227                throw new RuntimeException("TEST FAILED: " + getName() +
228                    " CurrentThreadCpuTime = " + time1 +
229                    " > ThreadCpuTime = " + time2);
230            }
231/*************
232 * FIXME: Seems that on Solaris-sparc,
233 * It occasionally returns a different current thread user time > thread user time
234            if (utime1 > utime2) {
235                throw new RuntimeException("TEST FAILED: " + getName() +
236                    " CurrentThreadUserTime = " + utime1 +
237                    " > ThreadUserTime = " + utime2);
238            }
239*/
240        }
241    }
242
243}
244