Path: blob/master/test/jdk/java/lang/ThreadLocal/TestThreadId.java
41149 views
/*1* Copyright (c) 2007, 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* @bug 643408426* @summary Exercise ThreadLocal javadoc "demo" class ThreadId27* @author Pete Soper28*/2930public final class TestThreadId extends Thread {3132// number of times to create threads and gather their ids33private static final int ITERATIONCOUNT = 50;3435// Threads constructed per iteration. ITERATIONCOUNT=50 and36// THREADCOUNT=50 takes about one second on a sun Blade 1000 (2x750mhz)37private static final int THREADCOUNT = 50;3839// The thread local storage object for holding per-thread ids40private static ThreadId id = new ThreadId();4142// Holds the per-thread so main method thread can collect it. JMM43// guarantees this is valid after this thread joins main method thread.44private int value;4546private synchronized int getIdValue() {47return value;48}4950// Each child thread just publishes its id value for validation51public void run() {52value = id.get();53}5455public static void main(String args[]) throws Throwable {5657// holds true corresponding to a used id value58boolean check[] = new boolean[THREADCOUNT*ITERATIONCOUNT];5960// the test threads61TestThreadId u[] = new TestThreadId[THREADCOUNT];6263for (int i = 0; i < ITERATIONCOUNT; i++) {64// Create and start the threads65for (int t=0;t<THREADCOUNT;t++) {66u[t] = new TestThreadId();67u[t].start();68}69// Join with each thread and get/check its id70for (int t=0;t<THREADCOUNT;t++) {71try {72u[t].join();73} catch (InterruptedException e) {74throw new RuntimeException(75"TestThreadId: Failed with unexpected exception" + e);76}77try {78if (check[u[t].getIdValue()]) {79throw new RuntimeException(80"TestThreadId: Failed with duplicated id: " +81u[t].getIdValue());82} else {83check[u[t].getIdValue()] = true;84}85} catch (Exception e) {86throw new RuntimeException(87"TestThreadId: Failed with unexpected id value" + e);88}89}90}91} // main92} // TestThreadId939495