Path: blob/master/test/jdk/java/io/PrintStream/OversynchronizedTest.java
41149 views
/*1* Copyright (c) 2005, 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/* @test24@bug 490577725@summary PrintStream.println(Object) oversynchronized, can deadlock26@key randomness27*/2829import java.io.PrintStream;3031public class OversynchronizedTest extends Thread {32private static TestObj testObj = new TestObj("This is a test.");33private static int loopNum = 100;3435public void run() {36for(int i=0; i<loopNum; i++) {37testObj.test();3839//passing an object to System.out.println might cause deadlock40//if the object has a synchronized toString() method.41//using System.out.println(testObj.toString()) won't have a problem42System.out.println(testObj);43}44}4546public static void main(String args[]) throws Exception {47// should no NullPointerException48System.out.println((Object)null);4950// over synch test51int num = 5;5253OversynchronizedTest[] t = new OversynchronizedTest[num];54for(int i=0; i<num; i++) {55t[i] = new OversynchronizedTest();56t[i].start();57}5859for(int i=0; i <num; i++) {60t[i].join();61}6263System.out.println("Test completed.");64}65}6667class TestObj {68String mStr;6970TestObj(String str) {71mStr = str;72}7374synchronized void test() {75try {76long t = Math.round(Math.random()*10);77Thread.currentThread().sleep(t);78} catch (InterruptedException e) {79// jtreg timeout?80// Only jtreg will interrupt this thread so it knows what to do:81e.printStackTrace();82}8384//the following line might cause hang if there is System.out.println(testObj)85//called by other threads.86System.out.println("In test().");87}8889public synchronized String toString() {90System.out.println("Calling toString\n");91return mStr;92}93}949596