Path: blob/master/test/jdk/java/nio/channels/FileChannel/Lock.java
41154 views
/*1* Copyright (c) 2001, 2016, 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 4429043 4493595 6332756 6709457 714650625* @summary Test FileChannel file locking26*/2728import java.io.*;29import java.nio.channels.*;30import static java.nio.file.StandardOpenOption.*;3132/**33* Testing FileChannel's lock method.34*/35public class Lock {3637public static void main(String[] args) throws Exception {38if (args.length == 2) {39attemptLock(args[1], args[0].equals("2"));40return;41} else if (args.length != 0) {42throw new RuntimeException("Wrong number of parameters.");43}44File blah = File.createTempFile("blah", null);45blah.deleteOnExit();46RandomAccessFile raf = new RandomAccessFile(blah, "rw");47raf.write(1);48raf.close();49test1(blah, "1");50test1(blah, "2");51test2(blah, true);52test2(blah, false);53test3(blah);54test4(blah);55}5657/**58* Test mutual locking with other process59*/60static void test1(File blah, String str) throws Exception {61try (RandomAccessFile fis = new RandomAccessFile(blah, "rw")) {62FileChannel fc = fis.getChannel();63FileLock lock = null;6465// grab the lock66if (str.equals("1")) {67lock = fc.lock(0, 10, false);68if (lock == null)69throw new RuntimeException("Lock should not return null");70try {71fc.lock(5, 10, false);72throw new RuntimeException("Overlapping locks allowed");73} catch (OverlappingFileLockException e) {} // correct result74}7576// execute the tamperer77String command = System.getProperty("java.home") +78File.separator + "bin" + File.separator + "java";79String testClasses = System.getProperty("test.classes");80if (testClasses != null)81command += " -cp " + testClasses;82command += " Lock " + str + " " + blah;83Process p = Runtime.getRuntime().exec(command);8485// evaluate System.out of child process86String s;87boolean hasOutput = false;88InputStreamReader isr;89isr = new InputStreamReader(p.getInputStream());90BufferedReader br = new BufferedReader(isr);91while ((s = br.readLine()) != null) {92// only throw on Unix as windows over NFS fails...93if ((File.separatorChar == '/') && !s.equals("good")) {94throw new RuntimeException("Failed: " + s);95}96hasOutput = true;97}9899// evaluate System.err in case of System.out of child process100// was empty101if (!hasOutput) {102isr = new InputStreamReader(p.getErrorStream());103br = new BufferedReader(isr);104if ((s = br.readLine()) != null) {105System.err.println("Error output:");106System.err.println(s);107while ((s = br.readLine()) != null) {108System.err.println(s);109}110}111throw new RuntimeException("Failed, no output");112}113114// clean up, check multiple releases115if (lock != null) {116lock.release();117lock.release();118}119}120}121122/**123* Basic test for FileChannel.lock() and FileChannel.tryLock()124*/125static void test2(File blah, boolean b) throws Exception {126try (RandomAccessFile raf = new RandomAccessFile(blah, "rw")) {127FileChannel channel = raf.getChannel();128FileLock lock;129if (b)130lock = channel.lock();131else132lock = channel.tryLock();133lock.release();134}135}136137/**138* Test that overlapping file locking is not possible when using different139* FileChannel objects to the same file path140*/141static void test3(File blah) throws Exception {142try (RandomAccessFile raf1 = new RandomAccessFile(blah, "rw");143RandomAccessFile raf2 = new RandomAccessFile(blah, "rw"))144{145FileChannel fc1 = raf1.getChannel();146FileChannel fc2 = raf2.getChannel();147148// lock via one channel, and then attempt to lock the same file149// using a second channel150FileLock fl1 = fc1.lock();151try {152fc2.tryLock();153throw new RuntimeException("Overlapping locks allowed");154} catch (OverlappingFileLockException x) {}155try {156fc2.lock();157throw new RuntimeException("Overlapping locks allowed");158} catch (OverlappingFileLockException x) {}159160// release lock and the attempt to lock with the second channel161// should succeed.162fl1.release();163fc2.lock();164try {165fc1.lock();166throw new RuntimeException("Overlapping locks allowed");167} catch (OverlappingFileLockException x) {}168}169}170171/**172* Test file locking when file is opened for append173*/174static void test4(File blah) throws Exception {175try (FileOutputStream fos = new FileOutputStream(blah, true)) {176FileChannel fc = fos.getChannel();177fc.tryLock().release();178fc.tryLock(0L, 1L, false).release();179fc.lock().release();180fc.lock(0L, 1L, false).release();181}182try (FileChannel fc = FileChannel.open(blah.toPath(), APPEND)) {183fc.tryLock().release();184fc.tryLock(0L, 1L, false).release();185fc.lock().release();186fc.lock(0L, 1L, false).release();187}188}189190/**191* Utility method to be run in secondary process which tries to acquire a192* lock on a FileChannel193*/194static void attemptLock(String fileName,195boolean expectsLock) throws Exception196{197File f = new File(fileName);198try (RandomAccessFile raf = new RandomAccessFile(f, "rw")) {199FileChannel fc = raf.getChannel();200if (fc.tryLock(10, 10, false) == null) {201System.out.println("bad: Failed to grab adjacent lock");202}203if (fc.tryLock(0, 10, false) == null) {204if (expectsLock)205System.out.println("bad");206else207System.out.println("good");208} else {209if (expectsLock)210System.out.println("good");211else212System.out.println("bad");213}214}215}216}217218219