Path: blob/master/test/jdk/java/io/PrintWriter/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 PrintWriter.println(Object) oversynchronized, can deadlock26*/2728import java.io.PrintWriter;2930public class OversynchronizedTest extends Thread {31private static PrintWriter writer = new PrintWriter(System.out);32private static TestObj testObj = new TestObj("This is a test.", writer);33private static int loopNum = 100;3435public void run() {36for(int i=0; i<loopNum; i++) {37testObj.test();3839//passing an object to PrintWriter.println might cause deadlock40//if the object has a synchronized toString() method.41//using PrintWriter.println(testObj.toString()) won't have a problem42writer.println(testObj);43}44}4546public static void main(String args[]) throws Exception {47// should no NullPointerException48writer.println((Object)null);4950int num = 5;5152OversynchronizedTest[] t = new OversynchronizedTest[num];53for(int i=0; i<num; i++) {54t[i] = new OversynchronizedTest();55t[i].start();56}5758for(int i=0; i <num; i++) {59t[i].join();60}6162System.out.println("Test completed");63}64}6566class TestObj {67String mStr;6869TestObj(String str, PrintWriter writer) {70mStr = str;71this.writer = writer;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 PrintWriter.println(testObj)85//called by other threads.86writer.println("In test().");87}8889public synchronized String toString() {90writer.println("Calling toString\n");91return mStr;92}9394private PrintWriter writer;95}969798