Lock.java revision 3261
0N/A/*
6159N/A * Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
0N/A * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
0N/A *
0N/A * This code is free software; you can redistribute it and/or modify it
0N/A * under the terms of the GNU General Public License version 2 only, as
0N/A * published by the Free Software Foundation.
0N/A *
0N/A * This code is distributed in the hope that it will be useful, but WITHOUT
0N/A * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
0N/A * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
0N/A * version 2 for more details (a copy is included in the LICENSE file that
0N/A * accompanied this code).
0N/A *
0N/A * You should have received a copy of the GNU General Public License version
0N/A * 2 along with this work; if not, write to the Free Software Foundation,
0N/A * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
0N/A *
2362N/A * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
2362N/A * or visit www.oracle.com if you need additional information or have any
2362N/A * questions.
0N/A */
0N/A
0N/A
0N/A/* @test
4571N/A * @bug 4607272 6814948 6842687
0N/A * @summary Unit test for AsynchronousFileChannel#lock method
0N/A */
0N/A
6159N/Aimport java.net.*;
0N/Aimport java.nio.ByteBuffer;
0N/Aimport java.nio.charset.Charset;
0N/Aimport java.nio.file.*;
0N/Aimport static java.nio.file.StandardOpenOption.*;
0N/Aimport java.nio.channels.*;
0N/Aimport java.io.File;
0N/Aimport java.io.IOException;
0N/Aimport java.io.InputStream;
0N/Aimport java.util.Random;
0N/Aimport java.util.concurrent.*;
0N/A
0N/Apublic class Lock {
0N/A
0N/A static final Random rand = new Random();
0N/A
0N/A public static void main(String[] args) throws Exception {
0N/A if (args.length > 0 && args[0].equals("-lockslave")) {
0N/A int port = Integer.parseInt(args[1]);
0N/A runLockSlave(port);
0N/A System.exit(0);
0N/A }
0N/A
0N/A LockSlaveMirror slave = startLockSlave();
0N/A try {
0N/A
0N/A // create temporary file
0N/A File blah = File.createTempFile("blah", null);
0N/A blah.deleteOnExit();
0N/A
0N/A // run tests
0N/A testLockProtocol(blah, slave);
0N/A testAsyncClose(blah, slave);
0N/A
0N/A // eagerly clean-up
0N/A blah.delete();
0N/A
0N/A } finally {
0N/A slave.shutdown();
0N/A }
0N/A }
0N/A
0N/A // test locking protocol
0N/A static void testLockProtocol(File file, LockSlaveMirror slave)
0N/A throws Exception
0N/A {
0N/A FileLock fl;
0N/A
0N/A // slave VM opens file and acquires exclusive lock
0N/A slave.open(file.getPath()).lock();
0N/A
0N/A AsynchronousFileChannel ch = AsynchronousFileChannel
0N/A .open(file.toPath(), READ, WRITE);
0N/A
0N/A // this VM tries to acquire lock
0N/A // (lock should not be acquire until released by slave VM)
0N/A Future<FileLock> result = ch.lock();
0N/A try {
0N/A result.get(2, TimeUnit.SECONDS);
0N/A throw new RuntimeException("Timeout expected");
0N/A } catch (TimeoutException x) {
0N/A }
0N/A
661N/A // slave VM releases lock
0N/A slave.unlock();
0N/A
0N/A // this VM should now acquire lock
0N/A fl = result.get();
0N/A fl.release();
0N/A
0N/A // slave VM acquires lock on range
0N/A slave.lock(0, 10, false);
0N/A
0N/A // this VM acquires lock on non-overlapping range
0N/A fl = ch.lock(10, 10, false).get();
0N/A fl.release();
0N/A
0N/A // done
0N/A ch.close();
0N/A slave.close();
0N/A }
0N/A
0N/A // test close of channel with outstanding lock operation
0N/A static void testAsyncClose(File file, LockSlaveMirror slave) throws Exception {
0N/A // slave VM opens file and acquires exclusive lock
0N/A slave.open(file.getPath()).lock();
0N/A
0N/A for (int i=0; i<100; i++) {
0N/A AsynchronousFileChannel ch = AsynchronousFileChannel
0N/A .open(file.toPath(), READ, WRITE);
0N/A
0N/A // try to lock file (should not complete because file is locked by slave)
0N/A Future<FileLock> result = ch.lock();
0N/A try {
0N/A result.get(rand.nextInt(100), TimeUnit.MILLISECONDS);
0N/A throw new RuntimeException("Timeout expected");
0N/A } catch (TimeoutException x) {
0N/A }
0N/A
2009N/A // close channel with lock operation outstanding
0N/A ch.close();
0N/A
0N/A // operation should complete with AsynchronousCloseException
0N/A try {
0N/A result.get();
0N/A throw new RuntimeException("ExecutionException expected");
2009N/A } catch (ExecutionException x) {
4571N/A if (!(x.getCause() instanceof AsynchronousCloseException)) {
0N/A x.getCause().printStackTrace();
0N/A throw new RuntimeException("AsynchronousCloseException expected");
0N/A }
0N/A }
0N/A }
0N/A
0N/A slave.close();
0N/A }
0N/A
0N/A // starts a "lock slave" in another process, returning a mirror object to
0N/A // control the slave
0N/A static LockSlaveMirror startLockSlave() throws Exception {
0N/A ServerSocketChannel ssc = ServerSocketChannel.open()
0N/A .bind(new InetSocketAddress(0));
0N/A int port = ((InetSocketAddress)(ssc.getLocalAddress())).getPort();
0N/A
0N/A String sep = FileSystems.getDefault().getSeparator();
0N/A
0N/A String command = System.getProperty("java.home") +
0N/A sep + "bin" + sep + "java";
0N/A String testClasses = System.getProperty("test.classes");
0N/A if (testClasses != null)
0N/A command += " -cp " + testClasses;
0N/A command += " Lock -lockslave " + port;
0N/A
0N/A Process p = Runtime.getRuntime().exec(command);
0N/A IOHandler.handle(p.getInputStream());
0N/A IOHandler.handle(p.getErrorStream());
0N/A
0N/A // wait for slave to connect
0N/A SocketChannel sc = ssc.accept();
0N/A return new LockSlaveMirror(sc);
0N/A }
0N/A
0N/A // commands that the slave understands
0N/A static final String OPEN_CMD = "open";
0N/A static final String CLOSE_CMD = "close";
0N/A static final String LOCK_CMD = "lock";
0N/A static final String UNLOCK_CMD = "unlock";
0N/A static final char TERMINATOR = ';';
0N/A
0N/A // provides a proxy to a "lock slave"
0N/A static class LockSlaveMirror {
0N/A private final SocketChannel sc;
0N/A
0N/A LockSlaveMirror(SocketChannel sc) {
0N/A this.sc = sc;
0N/A }
0N/A
0N/A private void sendCommand(String cmd, String... params)
0N/A throws IOException
0N/A {
0N/A for (String s: params) {
0N/A cmd += " " + s;
0N/A }
0N/A cmd += TERMINATOR;
0N/A
0N/A ByteBuffer buf = Charset.defaultCharset().encode(cmd);
0N/A while (buf.hasRemaining()) {
0N/A sc.write(buf);
0N/A }
0N/A
0N/A // wait for ack
0N/A buf = ByteBuffer.allocate(1);
0N/A int n = sc.read(buf);
0N/A if (n != 1)
0N/A throw new RuntimeException("Reply expected");
0N/A if (buf.get(0) != TERMINATOR)
661N/A throw new RuntimeException("Terminated expected");
661N/A }
661N/A
0N/A LockSlaveMirror open(String file) throws IOException {
0N/A sendCommand(OPEN_CMD, file);
0N/A return this;
0N/A }
0N/A
0N/A void close() throws IOException {
0N/A sendCommand(CLOSE_CMD);
0N/A }
0N/A
0N/A LockSlaveMirror lock() throws IOException {
0N/A sendCommand(LOCK_CMD);
0N/A return this;
0N/A }
0N/A
0N/A
0N/A LockSlaveMirror lock(long position, long size, boolean shared)
0N/A throws IOException
0N/A {
0N/A sendCommand(LOCK_CMD, position + "," + size + "," + shared);
0N/A return this;
0N/A }
0N/A
0N/A LockSlaveMirror unlock() throws IOException {
0N/A sendCommand(UNLOCK_CMD);
0N/A return this;
0N/A }
0N/A
0N/A void shutdown() throws IOException {
0N/A sc.close();
0N/A }
0N/A }
0N/A
0N/A // Helper class to direct process output to the parent System.out
0N/A static class IOHandler implements Runnable {
0N/A private final InputStream in;
0N/A
0N/A IOHandler(InputStream in) {
0N/A this.in = in;
0N/A }
0N/A
0N/A static void handle(InputStream in) {
0N/A IOHandler handler = new IOHandler(in);
1515N/A Thread thr = new Thread(handler);
1515N/A thr.setDaemon(true);
1515N/A thr.start();
1515N/A }
1515N/A
1515N/A public void run() {
1515N/A try {
1515N/A byte b[] = new byte[100];
0N/A for (;;) {
0N/A int n = in.read(b);
0N/A if (n < 0) return;
0N/A for (int i=0; i<n; i++) {
0N/A System.out.print((char)b[i]);
0N/A }
0N/A }
0N/A } catch (IOException ioe) { }
0N/A }
0N/A }
0N/A
0N/A // slave process that responds to simple commands a socket connection
0N/A static void runLockSlave(int port) throws Exception {
0N/A
0N/A // establish connection to parent
0N/A SocketChannel sc = SocketChannel.open(new InetSocketAddress(port));
0N/A ByteBuffer buf = ByteBuffer.allocateDirect(1024);
0N/A
0N/A FileChannel fc = null;
0N/A FileLock fl = null;
0N/A try {
0N/A for (;;) {
0N/A
0N/A // read command (ends with ";")
0N/A buf.clear();
0N/A int n, last = 0;
0N/A do {
0N/A n = sc.read(buf);
0N/A if (n < 0)
0N/A return;
0N/A if (n == 0)
0N/A throw new AssertionError();
0N/A last += n;
0N/A } while (buf.get(last-1) != TERMINATOR);
0N/A
0N/A // decode into command and optional parameter
0N/A buf.flip();
0N/A String s = Charset.defaultCharset().decode(buf).toString();
0N/A int sp = s.indexOf(" ");
0N/A String cmd = (sp < 0) ? s.substring(0, s.length()-1) :
0N/A s.substring(0, sp);
0N/A String param = (sp < 0) ? "" : s.substring(sp+1, s.length()-1);
0N/A
0N/A // execute
0N/A if (cmd.equals(OPEN_CMD)) {
0N/A if (fc != null)
0N/A throw new RuntimeException("File already open");
0N/A fc = FileChannel.open(Paths.get(param),READ, WRITE);
0N/A }
0N/A if (cmd.equals(CLOSE_CMD)) {
0N/A if (fc == null)
0N/A throw new RuntimeException("No file open");
0N/A fc.close();
0N/A fc = null;
0N/A fl = null;
0N/A }
0N/A if (cmd.equals(LOCK_CMD)) {
0N/A if (fl != null)
0N/A throw new RuntimeException("Already holding lock");
0N/A
0N/A if (param.length() == 0) {
0N/A fl = fc.lock();
0N/A } else {
0N/A String[] values = param.split(",");
0N/A if (values.length != 3)
0N/A throw new RuntimeException("Lock parameter invalid");
0N/A long position = Long.parseLong(values[0]);
0N/A long size = Long.parseLong(values[1]);
0N/A boolean shared = Boolean.parseBoolean(values[2]);
0N/A fl = fc.lock(position, size, shared);
0N/A }
0N/A }
0N/A
0N/A if (cmd.equals(UNLOCK_CMD)) {
0N/A if (fl == null)
0N/A throw new RuntimeException("Not holding lock");
0N/A fl.release();
0N/A fl = null;
0N/A }
0N/A
0N/A // send reply
0N/A byte[] reply = { TERMINATOR };
0N/A n = sc.write(ByteBuffer.wrap(reply));
0N/A }
0N/A
0N/A } finally {
0N/A sc.close();
0N/A if (fc != null) fc.close();
0N/A }
0N/A }
0N/A}
0N/A