Path: blob/master/test/jdk/java/nio/channels/FileChannel/ReleaseOnCloseDeadlock.java
41154 views
/*1* Copyright (c) 2009, 2010, 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 6543863 684268725* @summary Try to cause a deadlock between (Asynchronous)FileChannel.close26* and FileLock.release27*/2829import java.io.*;30import java.nio.file.Path;31import static java.nio.file.StandardOpenOption.*;32import java.nio.channels.*;33import java.util.concurrent.*;3435public class ReleaseOnCloseDeadlock {36private static final int LOCK_COUNT = 1024;3738public static void main(String[] args) throws IOException {39File blah = File.createTempFile("blah", null);40blah.deleteOnExit();41try {42for (int i=0; i<100; i++) {43test(blah.toPath());44}45} finally {46blah.delete();47}48}4950static void test(Path file) throws IOException {51FileLock[] locks = new FileLock[LOCK_COUNT];5253FileChannel fc = FileChannel.open(file, READ, WRITE);54for (int i=0; i<LOCK_COUNT; i++) {55locks[i] = fc.lock(i, 1, true);56}57tryToDeadlock(fc, locks);5859AsynchronousFileChannel ch = AsynchronousFileChannel.open(file, READ, WRITE);60for (int i=0; i<LOCK_COUNT; i++) {61try {62locks[i] = ch.lock(i, 1, true).get();63} catch (InterruptedException x) {64throw new RuntimeException(x);65} catch (ExecutionException x) {66throw new RuntimeException(x);67}68}69tryToDeadlock(ch, locks);70}7172static void tryToDeadlock(final Channel channel, FileLock[] locks)73throws IOException74{75// start thread to close the file (and invalidate the locks)76Thread closer = new Thread(77new Runnable() {78public void run() {79try {80channel.close();81} catch (IOException ignore) {82ignore.printStackTrace();83}84}});85closer.start();8687// release the locks explicitly88for (int i=0; i<locks.length; i++) {89try {90locks[i].release();91} catch (ClosedChannelException ignore) { }92}9394// we are done when closer has terminated95while (closer.isAlive()) {96try {97closer.join();98} catch (InterruptedException ignore) { }99}100}101}102103104