Path: blob/master/test/jdk/java/lang/InheritableThreadLocal/Basic.java
41149 views
/*1* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223/*24* @test25* @summary Basic functional test of InheritableThreadLocal26* @author Josh Bloch27*/2829public class Basic {30static InheritableThreadLocal n = new InheritableThreadLocal() {31protected Object initialValue() {32return new Integer(0);33}3435protected Object childValue(Object parentValue) {36return new Integer(((Integer)parentValue).intValue() + 1);37}38};3940static int threadCount = 100;41static int x[];4243public static void main(String args[]) throws Exception {44x = new int[threadCount];45Thread progenitor = new MyThread();46progenitor.start();4748// Wait for *all* threads to complete49progenitor.join();5051// Check results52for(int i=0; i<threadCount; i++)53if (x[i] != i)54throw(new Exception("x[" + i + "] =" + x[i]));55}5657private static class MyThread extends Thread {58public void run() {59Thread child = null;60if (((Integer)(n.get())).intValue() < threadCount-1) {61child = new MyThread();62child.start();63}64Thread.currentThread().yield();6566int threadId = ((Integer)(n.get())).intValue();67for (int j=0; j<threadId; j++) {68x[threadId]++;69Thread.currentThread().yield();70}7172// Wait for child (if any)73if (child != null) {74try {75child.join();76} catch(InterruptedException e) {77throw(new RuntimeException("Interrupted"));78}79}80}81}82}838485