提交 9b0f3ac7 编写于 作者: A alanb

6963027: TEST_BUG: channels and buffer tests need to run in samevm mode

Reviewed-by: ohair, sherman, chegar
上级 ae7f1139
......@@ -495,19 +495,17 @@ JDK_ALL_TARGETS += jdk_nio1
jdk_nio1: java/nio/file
$(call RunSamevmBatch)
# Stable othervm testruns (minus items from PROBLEM_LIST)
# Using samevm has serious problems with these tests
# Stable samevm testruns (minus items from PROBLEM_LIST)
JDK_ALL_TARGETS += jdk_nio2
jdk_nio2: java/nio/Buffer java/nio/ByteOrder \
java/nio/channels java/nio/BufferPoolMXBean java/nio/MappedByteBuffer
$(call SharedLibraryPermissions,java/nio/channels)
$(call RunOthervmBatch)
$(call RunSamevmBatch)
# Stable othervm testruns (minus items from PROBLEM_LIST)
# Using samevm has serious problems with these tests
# Stable samevm testruns (minus items from PROBLEM_LIST)
JDK_ALL_TARGETS += jdk_nio3
jdk_nio3: com/sun/nio sun/nio
$(call RunOthervmBatch)
$(call RunSamevmBatch)
# All nio tests
jdk_nio: jdk_nio1 jdk_nio2 jdk_nio3
......
......@@ -507,25 +507,46 @@ sun/net/www/protocol/http/DigestTest.java generic-all
############################################################################
# jdk_nio
# jdk_io
# Suspect many of these tests auffer from using fixed ports, no concrete
# evidence.
# 6962637
java/io/File/MaxPathLength.java windows-all
# Occasionally Failing with java.lang.AssertionError on Windows X64
# at sun.nio.ch.PendingIoCache.clearPendingIoMap(PendingIoCache.java:144)
#java/nio/channels/FileChannel/ReleaseOnCloseDeadlock.java windows-all
############################################################################
# Some kind of sleep/wake problem on Windows X64
java/nio/channels/Selector/Wakeup.java windows-all
# jdk_nio
# 6944810
java/nio/channels/FileChannel/ReleaseOnCloseDeadlock.java windows-all
# 6963118
java/nio/channels/Selector/Wakeup.java windows-all
# The asynchronous I/O implementation on Windows requires Windows XP or newer.
# We can remove the following once all Windows 2000 machines have been
# decommissioned.
java/nio/channels/AsynchronousChannelGroup/Basic.java windows-5.0
java/nio/channels/AsynchronousChannelGroup/GroupOfOne.java windows-5.0
java/nio/channels/AsynchronousChannelGroup/Identity.java windows-5.0
java/nio/channels/AsynchronousChannelGroup/Restart.java windows-5.0
java/nio/channels/AsynchronousChannelGroup/Unbounded.java windows-5.0
java/nio/channels/AsynchronousDatagramChannel/Basic.java windows-5.0
java/nio/channels/AsynchronousFileChannel/Lock.java windows-5.0
java/nio/channels/AsynchronousServerSocketChannel/Basic.java windows-5.0
java/nio/channels/AsynchronousServerSocketChannel/WithSecurityManager.java windows-5.0
java/nio/channels/AsynchronousSocketChannel/Basic.java windows-5.0
java/nio/channels/AsynchronousSocketChannel/DieBeforeComplete.java windows-5.0
java/nio/channels/AsynchronousSocketChannel/Leaky.java windows-5.0
java/nio/channels/AsynchronousSocketChannel/StressLoopback.java windows-5.0
java/nio/channels/Channels/Basic2.java windows-5.0
# 6959891
com/sun/nio/sctp/SctpChannel/SocketOptionTests.java
# Fails with -ea -esa, Assertion error, but only on Solaris 10 machines?
com/sun/nio/sctp/SctpChannel/Send.java generic-all
com/sun/nio/sctp/SctpChannel/Shutdown.java generic-all
# Fails on Windows 2000, times out
java/nio/channels/FileChannel/Transfer.java generic-all
# Fails on OpenSolaris, IllegalStateException: Cannot add or remove addresses
# from a channel that is bound to the wildcard address
com/sun/nio/sctp/SctpChannel/Bind.java generic-all
......@@ -533,12 +554,6 @@ com/sun/nio/sctp/SctpChannel/Bind.java generic-all
# Failed on OpenSolaris, java.lang.AssertionError: Unknown event type
com/sun/nio/sctp/SctpChannel/Receive.java generic-all
# Runtime exception on windows X64, samevm mode
java/nio/channels/Selector/WakeupNow.java generic-all
# Occasional errors, solarix x86, address already in use, othervm mode
java/nio/channels/Selector/SelectorTest.java generic-all
# Solaris 11 gave assert error and "connection refused", samevm issues?
com/sun/nio/sctp/SctpServerChannel/NonBlockingAccept.java generic-all
......@@ -549,43 +564,6 @@ com/sun/nio/sctp/SctpMultiChannel/Branch.java generic-all
com/sun/nio/sctp/SctpMultiChannel/Send.java generic-all
com/sun/nio/sctp/SctpMultiChannel/SocketOptionTests.java generic-all
# Linux 64bit failures. too many files open
java/nio/channels/Selector/HelperSlowToDie.java generic-all
# Gets java.lang.ExceptionInInitializerError on Windows 2000 (need XP or newer)
java/nio/channels/AsynchronousChannelGroup/Basic.java windows-5.0
java/nio/channels/AsynchronousChannelGroup/GroupOfOne.java windows-5.0
java/nio/channels/AsynchronousChannelGroup/Identity.java windows-5.0
java/nio/channels/AsynchronousChannelGroup/Restart.java windows-5.0
java/nio/channels/AsynchronousChannelGroup/Unbounded.java windows-5.0
java/nio/channels/AsynchronousDatagramChannel/Basic.java windows-5.0
java/nio/channels/AsynchronousFileChannel/Lock.java windows-5.0
java/nio/channels/AsynchronousServerSocketChannel/Basic.java windows-5.0
java/nio/channels/AsynchronousServerSocketChannel/WithSecurityManager.java windows-5.0
java/nio/channels/AsynchronousSocketChannel/Basic.java windows-5.0
java/nio/channels/AsynchronousSocketChannel/DieBeforeComplete.java windows-5.0
java/nio/channels/AsynchronousSocketChannel/Leaky.java windows-5.0
java/nio/channels/AsynchronousSocketChannel/StressLoopback.java windows-5.0
java/nio/channels/Channels/Basic2.java windows-5.0
# Failed loopback connection? On windows 32bit?
# Considered a stress test, can consume all resources.
java/nio/channels/Selector/LotsOfChannels.java generic-all
# Windows i586 client, crashed hotspot? Unpredictable
# Considered a stress test, can consume all resources.
java/nio/channels/Selector/RegAfterPreClose.java generic-all
# Solaris i586, cannot assign address, samevm issues
java/nio/channels/Selector/SelectorLimit.java generic-all
# Socket timeout windows X64
java/nio/channels/ServerSocketChannel/AdaptServerSocket.java windows-all
# Timeouts etc. on Window
java/nio/channels/SocketChannel/ConnectState.java windows-all
java/nio/channels/SocketChannel/FinishConnect.java windows-all
############################################################################
# jdk_rmi
......
......@@ -24,6 +24,7 @@
/* @test
* @bug 6606598
* @summary Unit test for java.nio.BufferPoolMXBean
* @run main/othervm Basic
*/
import java.nio.ByteBuffer;
......
......@@ -24,6 +24,7 @@
/* @test
* @bug 4462336
* @summary Simple MappedByteBuffer tests
* @run main/othervm Basic
*/
import java.io.*;
......
......@@ -24,6 +24,7 @@
/* @test
* @bug 4625907
* @summary Testing force()
* @run main/othervm Force
*/
import java.io.*;
......
......@@ -24,6 +24,7 @@
/* @test
* @bug 4802340
* @summary Testing force(), load() isLoaded() of zero len MBB
* @run main/othervm ZeroMap
*/
import java.io.*;
......
......@@ -29,6 +29,7 @@
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.net.*;
import java.util.*;
import java.util.concurrent.*;
import java.io.IOException;
......@@ -44,8 +45,12 @@ public class GroupOfOne {
final AsynchronousServerSocketChannel listener =
AsynchronousServerSocketChannel.open()
.bind(new InetSocketAddress(0));
final List<AsynchronousSocketChannel> accepted = new ArrayList<AsynchronousSocketChannel>();
listener.accept((Void)null, new CompletionHandler<AsynchronousSocketChannel,Void>() {
public void completed(AsynchronousSocketChannel ch, Void att) {
synchronized (accepted) {
accepted.add(ch);
}
listener.accept((Void)null, this);
}
public void failed(Throwable exc, Void att) {
......@@ -58,6 +63,14 @@ public class GroupOfOne {
test(sa, true, false);
test(sa, false, true);
test(sa, true, true);
// clean-up
listener.close();
synchronized (accepted) {
for (AsynchronousSocketChannel ch: accepted) {
ch.close();
}
}
}
static void test(SocketAddress sa,
......
......@@ -32,6 +32,7 @@ import java.net.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.io.IOException;
/**
* Tests that the completion handler is invoked by a thread with
......@@ -81,14 +82,18 @@ public class Identity {
listener.accept((Void)null, new CompletionHandler<AsynchronousSocketChannel,Void>() {
public void completed(final AsynchronousSocketChannel ch, Void att) {
listener.accept((Void)null, this);
final ByteBuffer buf = ByteBuffer.allocate(100);
ch.read(buf, (Void)null, new CompletionHandler<Integer,Void>() {
public void completed(Integer bytesRead, Void att) {
buf.clear();
ch.read(buf, (Void)null, this);
ch.read(buf, ch, new CompletionHandler<Integer,AsynchronousSocketChannel>() {
public void completed(Integer bytesRead, AsynchronousSocketChannel ch) {
if (bytesRead < 0) {
try { ch.close(); } catch (IOException ignore) { }
} else {
buf.clear();
ch.read(buf, ch, this);
}
}
public void failed(Throwable exc, Void att) {
public void failed(Throwable exc, AsynchronousSocketChannel ch) {
try { ch.close(); } catch (IOException ignore) { }
}
});
}
......@@ -100,7 +105,8 @@ public class Identity {
// create 3-10 channels, each in its own group
final int groupCount = 3 + rand.nextInt(8);
final AsynchronousSocketChannel[] channel = new AsynchronousSocketChannel[groupCount];
AsynchronousChannelGroup[] groups = new AsynchronousChannelGroup[groupCount];
final AsynchronousSocketChannel[] channels = new AsynchronousSocketChannel[groupCount];
for (int i=0; i<groupCount; i++) {
ThreadFactory factory = createThreadFactory(i);
AsynchronousChannelGroup group;
......@@ -111,17 +117,18 @@ public class Identity {
ExecutorService pool = Executors.newCachedThreadPool(factory);
group = AsynchronousChannelGroup.withCachedThreadPool(pool, rand.nextInt(5));
}
groups[i] = group;
// create channel in group and connect it to the server
AsynchronousSocketChannel ch = AsynchronousSocketChannel.open(group);
ch.connect(sa).get();
channel[i] = ch;
channels[i] = ch;
}
// randomly write to each channel, ensuring that the completion handler
// is always invoked by a thread with the right identity.
final AtomicInteger writeCount = new AtomicInteger(100);
channel[0].write(getBuffer(), 0, new CompletionHandler<Integer,Integer>() {
channels[0].write(getBuffer(), 0, new CompletionHandler<Integer,Integer>() {
public void completed(Integer bytesWritten, Integer groupId) {
if (bytesWritten != 1)
fail("Expected 1 byte to be written");
......@@ -129,7 +136,7 @@ public class Identity {
fail("Handler invoked by thread with the wrong identity");
if (writeCount.decrementAndGet() > 0) {
int id = rand.nextInt(groupCount);
channel[id].write(getBuffer(), id, this);
channels[id].write(getBuffer(), id, this);
} else {
done.countDown();
}
......@@ -139,8 +146,16 @@ public class Identity {
}
});
// wait until
// wait until done
done.await();
// clean-up
for (AsynchronousSocketChannel ch: channels)
ch.close();
for (AsynchronousChannelGroup group: groups)
group.shutdownNow();
listener.close();
if (failed.get())
throw new RuntimeException("Test failed - see log for details");
}
......
......@@ -371,17 +371,22 @@ public class Basic {
static void doMulticastTests() throws Exception {
final byte[] msg = "hello".getBytes();
InetAddress lh = InetAddress.getLocalHost();
NetworkInterface interf = NetworkInterface.getByInetAddress(lh);
if (interf.isLoopback() || !interf.supportsMulticast()) {
System.out.println("Multicasting not tested");
return;
}
AsynchronousDatagramChannel ch = AsynchronousDatagramChannel
.open(StandardProtocolFamily.INET, null)
.setOption(StandardSocketOption.SO_REUSEADDR, true)
.bind(new InetSocketAddress(0));
InetAddress lh = InetAddress.getLocalHost();
int port = ((InetSocketAddress)(ch.getLocalAddress())).getPort();
// join group
InetAddress group = InetAddress.getByName("225.4.5.6");
NetworkInterface interf = NetworkInterface.getByInetAddress(lh);
MembershipKey key = ch.join(group, interf);
// check key
......
......@@ -45,16 +45,18 @@ public class Basic {
File blah = File.createTempFile("blah", null);
blah.deleteOnExit();
final AsynchronousFileChannel ch = AsynchronousFileChannel
AsynchronousFileChannel ch = AsynchronousFileChannel
.open(blah.toPath(), READ, WRITE);
try {
// run tests
testUsingCompletionHandlers(ch);
testUsingWaitOnResult(ch);
testInterruptHandlerThread(ch);
} finally {
ch.close();
}
// run tests
testUsingCompletionHandlers(ch);
testUsingWaitOnResult(ch);
testInterruptHandlerThread(ch);
// close channel and invoke test that expects channel to be closed
ch.close();
// run test that expects channel to be closed
testClosedChannel(ch);
// these tests open the file themselves
......@@ -63,6 +65,9 @@ public class Basic {
testAsynchronousClose(blah.toPath());
testCancel(blah.toPath());
testTruncate(blah.toPath());
// eagerly clean-up
blah.delete();
}
/*
......
......@@ -53,13 +53,17 @@ public class Lock {
LockSlaveMirror slave = startLockSlave();
try {
// create temporary file
// create temporary file
File blah = File.createTempFile("blah", null);
blah.deleteOnExit();
// run tests
testLockProtocol(blah, slave);
testAsyncClose(blah, slave);
// eagerly clean-up
blah.delete();
} finally {
slave.shutdown();
}
......@@ -150,7 +154,12 @@ public class Lock {
String sep = FileSystems.getDefault().getSeparator();
String command = System.getProperty("java.home") +
sep + "bin" + sep + "java Lock -lockslave " + port;
sep + "bin" + sep + "java";
String testClasses = System.getProperty("test.classes");
if (testClasses != null)
command += " -cp " + testClasses;
command += " Lock -lockslave " + port;
Process p = Runtime.getRuntime().exec(command);
IOHandler.handle(p.getInputStream());
IOHandler.handle(p.getErrorStream());
......
......@@ -135,6 +135,7 @@ public class LotsOfWrites {
latch.await();
// verify content of each file
boolean failed = false;
byte[] buf = new byte[8192];
for (int i=0; i<count ;i++) {
Writer writer = writers[i];
......@@ -145,18 +146,35 @@ public class LotsOfWrites {
int nread = in.read(buf);
while (nread > 0) {
for (int j=0; j<nread; j++) {
if (buf[j] != expected)
throw new RuntimeException("Unexpected byte");
if (buf[j] != expected) {
System.err.println("Unexpected contents");
failed = true;
break;
}
expected++;
}
if (failed)
break;
size += nread;
nread = in.read(buf);
}
if (size != writer.size())
throw new RuntimeException("Unexpected size");
if (!failed && size != writer.size()) {
System.err.println("Unexpected size");
failed = true;
}
if (failed)
break;
} finally {
in.close();
}
}
// clean-up
for (int i=0; i<count; i++) {
writers[i].file().delete();
}
if (failed)
throw new RuntimeException("Test failed");
}
}
......@@ -776,6 +776,7 @@ public class Basic {
throw new RuntimeException("RuntimeException expected after timeout.");
ch.close();
server.close();
}
// returns ByteBuffer with random bytes
......
......@@ -61,6 +61,9 @@ public class Basic2 {
writerThread.join();
readerThread.join();
// shutdown listener
listener.close();
// check that reader received what we expected
if (reader.total() != writer.total())
throw new RuntimeException("Unexpected number of bytes read");
......
......@@ -47,5 +47,6 @@ public class Write {
out.close();
fc.close();
fos.close();
testFile.delete();
}
}
......@@ -82,8 +82,6 @@ public class AdaptDatagramSocket {
}
throw x;
}
if (shouldTimeout)
throw new Exception("Receive did not time out");
break;
}
......
......@@ -46,21 +46,25 @@ public class EmptyBuffer {
Thread serverThread = new Thread(server);
serverThread.start();
DatagramChannel dc = DatagramChannel.open();
ByteBuffer bb = ByteBuffer.allocateDirect(12);
bb.order(ByteOrder.BIG_ENDIAN);
bb.putInt(1).putLong(1);
bb.flip();
InetAddress address = InetAddress.getLocalHost();
InetSocketAddress isa = new InetSocketAddress(address, server.port());
dc.connect(isa);
dc.write(bb);
bb.rewind();
dc.write(bb);
bb.rewind();
dc.write(bb);
Thread.sleep(2000);
serverThread.interrupt();
server.throwException();
try {
ByteBuffer bb = ByteBuffer.allocateDirect(12);
bb.order(ByteOrder.BIG_ENDIAN);
bb.putInt(1).putLong(1);
bb.flip();
InetAddress address = InetAddress.getLocalHost();
InetSocketAddress isa = new InetSocketAddress(address, server.port());
dc.connect(isa);
dc.write(bb);
bb.rewind();
dc.write(bb);
bb.rewind();
dc.write(bb);
Thread.sleep(2000);
serverThread.interrupt();
server.throwException();
} finally {
dc.close();
}
}
public static class Server implements Runnable {
......@@ -118,6 +122,8 @@ public class EmptyBuffer {
}
} catch (Exception ex) {
e = ex;
} finally {
try { dc.close(); } catch (IOException ignore) { }
}
}
}
......
......@@ -66,6 +66,10 @@ public class ReceiveISA {
rb.clear();
}
dc1.close();
dc2.close();
dc3.close();
/*
* Check that sa[0] equals sa[1] (both from dc1)
* Check that sa[1] not equal to sa[2] (one from dc1, one from dc2)
......
......@@ -43,9 +43,9 @@ public class SelectWhenRefused {
SocketAddress refuser = new InetSocketAddress(InetAddress.getLocalHost(), port);
dc = DatagramChannel.open().bind(new InetSocketAddress(0));
Selector sel = Selector.open();
try {
dc.configureBlocking(false);
Selector sel = Selector.open();
dc.register(sel, SelectionKey.OP_READ);
/* Test 1: not connected so ICMP port unreachable should not be received */
......@@ -81,6 +81,7 @@ public class SelectWhenRefused {
}
} finally {
sel.close();
dc.close();
}
}
......
......@@ -97,6 +97,8 @@ public class Args {
(long)Integer.MAX_VALUE << 3);
}});
fc.close();
f.delete();
}
}
......@@ -38,6 +38,7 @@ public class ClosedChannelTransfer {
test1(channel);
test2(channel);
channel.close();
file.delete();
}
static void test1(FileChannel channel) throws Exception {
......
......@@ -25,6 +25,7 @@
* @bug 4938372 6541641
* @summary Flushing dirty pages prior to unmap can cause Cleaner thread to
* abort VM if memory system has pages locked
* @run main/othervm ExpandingMap
*/
import java.io.File;
import java.io.RandomAccessFile;
......
......@@ -55,6 +55,7 @@ public class Lock {
test2(blah, true);
test2(blah, false);
test3(blah);
blah.delete();
}
private static void test2(File blah, boolean b) throws Exception {
......@@ -90,7 +91,11 @@ public class Lock {
// Exec the tamperer
String command = System.getProperty("java.home") +
File.separator + "bin" + File.separator + "java Lock " + str + " " + blah;
File.separator + "bin" + File.separator + "java";
String testClasses = System.getProperty("test.classes");
if (testClasses != null)
command += " -cp " + testClasses;
command += " Lock " + str + " " + blah;
Process p = Runtime.getRuntime().exec(command);
BufferedReader in = new BufferedReader
......
......@@ -24,6 +24,7 @@
/* @test
* @bug 4463036
* @summary Check if file mapping extends beyond end of file
* @run main/othervm MapOverEnd
*/
import java.nio.*;
......
......@@ -24,6 +24,7 @@
/* @test
* @bug 4510489
* @summary Verify IOUtil.java reads to buffer limits
* @run main/othervm MapReadOnly
*/
import java.io.*;
import java.nio.*;
......
......@@ -23,6 +23,7 @@
/* @test
* @summary Test file mapping with FileChannel
* @run main/othervm MapTest
*/
import java.io.*;
......
......@@ -24,6 +24,7 @@
/* @test
@bug 4462298
* @summary Test FileChannel maps with different accesses
* @run main/othervm Mode
*/
import java.nio.channels.*;
......
......@@ -63,6 +63,7 @@ public class Position {
c.close();
fis.close();
blah.delete();
}
/**
......
......@@ -65,6 +65,9 @@ public class Pread {
throw new RuntimeException("Expected exception not thrown");
} catch(IllegalArgumentException e) {
// Correct result
} finally {
fc.close();
blah.delete();
}
}
......@@ -73,13 +76,18 @@ public class Pread {
File blah = File.createTempFile("blah2", null);
blah.deleteOnExit();
FileOutputStream fos = new FileOutputStream(blah);
fos.write(new byte[128]);
FileChannel fc = fos.getChannel();
try {
fc.read(ByteBuffer.allocate(256),1);
throw new RuntimeException("Expected exception not thrown");
} catch(NonReadableChannelException e) {
// Correct result
fos.write(new byte[128]);
FileChannel fc = fos.getChannel();
try {
fc.read(ByteBuffer.allocate(256),1);
throw new RuntimeException("Expected exception not thrown");
} catch(NonReadableChannelException e) {
// Correct result
}
} finally {
fos.close();
blah.delete();
}
}
......@@ -130,6 +138,7 @@ public class Pread {
c.close();
fis.close();
blah.delete();
}
/**
......
......@@ -62,6 +62,9 @@ public class Pwrite {
throw new RuntimeException("Expected exception not thrown");
} catch(NonWritableChannelException e) {
// Correct result
} finally {
fc.close();
blah.delete();
}
}
......@@ -123,6 +126,7 @@ public class Pwrite {
}
c.close();
raf.close();
blah.delete();
}
/**
......
......@@ -80,6 +80,7 @@ public class Read {
c.close();
fis.close();
blah.delete();
}
/**
......
......@@ -54,5 +54,6 @@ public class ReadFull {
fc.close();
fis.close();
blah.delete();
}
}
......@@ -48,6 +48,7 @@ public class ReadToLimit {
throw new Exception("Test failed");
fc.close();
fis.close();
blah.delete();
}
/**
......
......@@ -39,8 +39,12 @@ public class ReleaseOnCloseDeadlock {
public static void main(String[] args) throws IOException {
File blah = File.createTempFile("blah", null);
blah.deleteOnExit();
for (int i=0; i<100; i++) {
test(blah.toPath());
try {
for (int i=0; i<100; i++) {
test(blah.toPath());
}
} finally {
blah.delete();
}
}
......
......@@ -24,6 +24,7 @@
/* @test
@bug 4452020 4629048 4638365 4869859
* @summary Test FileChannel scattering reads
* @run main/othervm ScatteringRead
*/
import java.nio.channels.*;
......
......@@ -24,6 +24,7 @@
/* @test
* @bug 4563125
* @summary Test size method of FileChannel
* @run main/othervm Size
*/
import java.io.*;
......
......@@ -25,7 +25,7 @@
* @bug 4434723 4482726 4559072 4638365 4795550 5081340 5103988 6253145
* @summary Test FileChannel.transferFrom and transferTo
* @library ..
* @run main/timeout=180 Transfer
* @run main/timeout=240 Transfer
*/
import java.io.*;
......@@ -96,6 +96,9 @@ public class Transfer {
sourceChannel.close();
sinkChannel.close();
source.delete();
sink.delete();
}
private static void testReadableByteChannel(int size) throws Exception {
......@@ -139,6 +142,8 @@ public class Transfer {
fc.close();
sink.close();
source.close();
f.delete();
}
public static void xferTest02() throws Exception {
......@@ -173,6 +178,9 @@ public class Transfer {
fc2.close();
raf1.close();
raf2.close();
source.delete();
dest.delete();
}
public static void xferTest03() throws Exception {
......@@ -207,6 +215,9 @@ public class Transfer {
fc2.close();
raf1.close();
raf2.close();
source.delete();
dest.delete();
}
// Test transferTo with large file
......@@ -245,6 +256,8 @@ public class Transfer {
sourceChannel.close();
sinkChannel.close();
source.delete();
sink.delete();
}
// Test transferFrom with large file
......@@ -293,6 +306,8 @@ public class Transfer {
}
sourceChannel.close();
sinkChannel.close();
source.delete();
sink.delete();
}
static void checkFileData(File file, String expected) throws Exception {
......@@ -338,6 +353,8 @@ public class Transfer {
checkFileData(source, data);
checkFileData(sink, data.substring(7,data.length()));
source.delete();
}
// Test transferTo to non-blocking socket channel
......@@ -371,6 +388,7 @@ public class Transfer {
sink.close();
other.close();
ssc.close();
source.delete();
}
......@@ -473,6 +491,7 @@ public class Transfer {
source.close();
ssc.close();
fc.close();
file.delete();
}
}
......
......@@ -51,6 +51,8 @@ public class TransferToChannel {
test1();
test2();
in.close();
file.delete();
outFile.delete();
}
static void test1() throws Exception {
......
......@@ -43,6 +43,9 @@ public class TransferToNonWritable {
throw new RuntimeException("Test failed");
} catch (NonWritableChannelException nwce) {
// Correct result
} finally {
channel.close();
blah.delete();
}
}
}
......@@ -554,6 +554,10 @@ public class Transfers {
break;
}
sourceFile.delete();
targetFile.delete();
fn.delete();
if (failures > 0) {
out.println();
throw new RuntimeException("Some tests failed");
......
......@@ -56,7 +56,6 @@ public class TryLock {
public static void test1(boolean shared, boolean trylock) throws Exception {
File testFile = File.createTempFile("test1", null);
testFile.deleteOnExit();
FileInputStream fis = new FileInputStream(testFile);
FileChannel fc = fis.getChannel();
FileLock fl = null;
......@@ -73,12 +72,13 @@ public class TryLock {
} finally {
if (fl != null)
fl.release();
fc.close();
testFile.delete();
}
}
public static void test2(boolean shared, boolean trylock) throws Exception {
File testFile = File.createTempFile("test2", null);
testFile.deleteOnExit();
FileOutputStream fis = new FileOutputStream(testFile);
FileChannel fc = fis.getChannel();
FileLock fl = null;
......@@ -95,19 +95,25 @@ public class TryLock {
} finally {
if (fl != null)
fl.release();
fc.close();
testFile.delete();
}
}
public static void test3(boolean shared, boolean trylock) throws Exception {
File testFile = File.createTempFile("test3", null);
testFile.deleteOnExit();
RandomAccessFile fis = new RandomAccessFile(testFile, "rw");
FileChannel fc = fis.getChannel();
FileLock fl = null;
if (trylock)
fl = fc.tryLock(0, fc.size(), shared);
else
fl = fc.lock(0, fc.size(), shared);
fl.release();
try {
FileLock fl = null;
if (trylock)
fl = fc.tryLock(0, fc.size(), shared);
else
fl = fc.lock(0, fc.size(), shared);
fl.release();
} finally {
fc.close();
testFile.delete();
}
}
}
......@@ -25,6 +25,7 @@
* @test
* @bug 4475533 4698138 4638365 4796221
* @summary Test FileChannel write
* @run main/othervm Write
*/
import java.nio.channels.*;
......@@ -46,23 +47,25 @@ public class Write {
// Test to see that offset > length does not throw exception
static void test1() throws Exception {
File testFile = File.createTempFile("test1", null);
testFile.deleteOnExit();
ByteBuffer[] dsts = new ByteBuffer[4];
for (int i=0; i<4; i++)
dsts[i] = ByteBuffer.allocateDirect(10);
FileOutputStream fos = new FileOutputStream(testFile);
FileChannel fc = fos.getChannel();
fc.write(dsts, 2, 1);
fos.close();
File testFile = File.createTempFile("test1", null);
try {
FileOutputStream fos = new FileOutputStream(testFile);
FileChannel fc = fos.getChannel();
fc.write(dsts, 2, 1);
fos.close();
} finally {
testFile.delete();
}
}
// Test to see that the appropriate buffers are updated
static void test2() throws Exception {
File testFile = File.createTempFile("test2", null);
testFile.deleteOnExit();
testFile.delete();
ByteBuffer[] srcs = new ByteBuffer[4];
for (int i=0; i<4; i++)
srcs[i] = ByteBuffer.allocateDirect(10);
......@@ -74,25 +77,34 @@ public class Write {
FileOutputStream fos = new FileOutputStream(testFile);
FileChannel fc = fos.getChannel();
fc.write(srcs, 1, 2);
fos.close();
try {
fc.write(srcs, 1, 2);
} finally {
fc.close();
}
FileInputStream fis = new FileInputStream(testFile);
fc = fis.getChannel();
ByteBuffer bb = ByteBuffer.allocateDirect(10);
fc.read(bb);
bb.flip();
if (bb.get() != 2)
throw new RuntimeException("Write failure");
if (bb.get() != 3)
throw new RuntimeException("Write failure");
try {
bb.get();
throw new RuntimeException("Write failure");
} catch (BufferUnderflowException bufe) {
// correct result
ByteBuffer bb = ByteBuffer.allocateDirect(10);
fc.read(bb);
bb.flip();
if (bb.get() != 2)
throw new RuntimeException("Write failure");
if (bb.get() != 3)
throw new RuntimeException("Write failure");
try {
bb.get();
throw new RuntimeException("Write failure");
} catch (BufferUnderflowException bufe) {
// correct result
}
} finally {
fc.close();
}
fis.close();
// eagerly clean-up
testFile.delete();
}
// Test write to a negative position (bug 4698138).
......
......@@ -41,12 +41,17 @@ public class NonBlocking {
static void test1() throws Exception {
Pipe p = Pipe.open();
p.sink().configureBlocking(false);
if (p.sink().isBlocking())
throw new Exception("Sink still blocking");
p.source().configureBlocking(false);
if (p.source().isBlocking())
throw new Exception("Source still blocking");
try {
p.sink().configureBlocking(false);
if (p.sink().isBlocking())
throw new Exception("Sink still blocking");
p.source().configureBlocking(false);
if (p.source().isBlocking())
throw new Exception("Source still blocking");
} finally {
p.sink().close();
p.source().close();
}
}
}
......@@ -78,10 +78,12 @@ public class SelectPipe {
totalRead += bytesRead;
} while(totalRead < 10);
sink.close();
source.close();
selector.close();
for(int i=0; i<10; i++)
if (outgoingdata.get(i) != incomingdata.get(i))
throw new Exception("Pipe failed");
sink.close();
source.close();
}
}
......@@ -58,6 +58,11 @@ public class AtomicAttachTest {
};
t.join();
pipe.sink().close();
pipe.source().close();
selector.close();
int count = errorCount.get();
if (count > 0) {
throw new RuntimeException("Error count:" + count);
......
......@@ -36,49 +36,60 @@ import java.util.*;
public class BasicAccept {
public static int TEST_PORT = 40170;
static void server() throws Exception {
static void server(ServerSocketChannel ssc) throws Exception {
Selector acceptSelector = Selector.open();
ServerSocketChannel ssc = ServerSocketChannel.open();
ssc.configureBlocking(false);
InetAddress lh = InetAddress.getLocalHost();
InetSocketAddress isa
= new InetSocketAddress(lh, SelectorTest.TEST_PORT);
ssc.socket().bind(isa);
SelectionKey acceptKey
= ssc.register(acceptSelector, SelectionKey.OP_ACCEPT);
for (;;) {
if (acceptSelector.select() == 0)
continue;
Set readyKeys = acceptSelector.selectedKeys();
Iterator i = readyKeys.iterator();
while (i.hasNext()) {
SelectionKey sk = (SelectionKey)i.next();
i.remove();
ServerSocketChannel nextReady
= (ServerSocketChannel)sk.channel();
SocketChannel sc = nextReady.accept();
ByteBuffer bb = ByteBuffer.wrap(new byte[] { 42 });
sc.write(bb);
try {
ssc.configureBlocking(false);
SelectionKey acceptKey
= ssc.register(acceptSelector, SelectionKey.OP_ACCEPT);
for (;;) {
int n = acceptSelector.select();
if (Thread.interrupted())
break;
if (n == 0)
continue;
Set<SelectionKey> readyKeys = acceptSelector.selectedKeys();
Iterator<SelectionKey> i = readyKeys.iterator();
while (i.hasNext()) {
SelectionKey sk = i.next();
i.remove();
ServerSocketChannel nextReady
= (ServerSocketChannel)sk.channel();
SocketChannel sc = nextReady.accept();
ByteBuffer bb = ByteBuffer.wrap(new byte[] { 42 });
sc.write(bb);
sc.close();
}
}
} finally {
acceptSelector.close();
}
}
private static class Server extends TestThread {
Server() {
final ServerSocketChannel ssc;
Server() throws IOException {
super("Server", System.err);
this.ssc = ServerSocketChannel.open()
.bind(new InetSocketAddress(0));
}
int port() {
return ssc.socket().getLocalPort();
}
void go() throws Exception {
server();
try {
server(ssc);
} finally {
ssc.close();
}
}
}
static void client() throws Exception {
static void client(int port) throws Exception {
// Get a connection from the server
InetAddress lh = InetAddress.getLocalHost();
InetSocketAddress isa
= new InetSocketAddress(lh, SelectorTest.TEST_PORT);
= new InetSocketAddress(lh, port);
int connectFailures = 0;
boolean result = false;
SocketChannel sc = SocketChannel.open();
......@@ -122,17 +133,17 @@ public class BasicAccept {
if (bb.get(0) != 42)
throw new RuntimeException("Read wrong byte from server");
System.err.println("Read from server");
sc.close();
}
public static void main(String[] args) throws Exception {
if (args.length == 0) {
Server server = new Server();
server.start();
client();
} else if (args[0].equals("client")) {
client();
} else if (args[0].equals("server")) {
server();
Server server = new Server();
server.start();
try {
client(server.port());
} finally {
server.interrupt();
server.finish(2000);
}
}
......
......@@ -83,10 +83,13 @@ public class BasicConnect {
ByteBuffer bb2 = ByteBuffer.allocateDirect(100);
int n = sc.read(bb2);
bb2.flip();
sc.close();
connectSelector.close();
if (!bb.equals(bb2))
throw new Exception("Echoed bytes incorrect: Sent "
+ bb + ", got " + bb2);
sc.close();
}
}
......@@ -61,5 +61,7 @@ public class CheckLocking implements Runnable {
doSelect();
sk.interestOps(SelectionKey.OP_READ);
selector.wakeup();
sc.close();
selector.close();
}
}
......@@ -33,12 +33,16 @@ public class CloseInvalidatesKeys {
public static void main (String [] args) throws Exception {
DatagramChannel ch = DatagramChannel.open();
ch.configureBlocking(false);
Selector sel = Selector.open();
SelectionKey key = ch.register(sel, SelectionKey.OP_WRITE);
sel.close();
if (key.isValid())
throw new Exception("Key valid after selector closed");
try {
ch.configureBlocking(false);
Selector sel = Selector.open();
SelectionKey key = ch.register(sel, SelectionKey.OP_WRITE);
sel.close();
if (key.isValid())
throw new Exception("Key valid after selector closed");
} finally {
ch.close();
}
}
}
......@@ -111,10 +111,14 @@ public class CloseWhenKeyIdle {
// select should block
int spinCount = 0;
boolean failed = false;
for (;;) {
int n = sel.select();
if (n > 0)
throw new RuntimeException("channel should not be selected");
if (n > 0) {
System.err.println("Channel should not be selected!!!");
failed = true;
break;
}
// wakeup
if (wakeupDone)
......@@ -123,10 +127,19 @@ public class CloseWhenKeyIdle {
// wakeup for no reason - if it happens a few times then we have a
// problem
spinCount++;
if (spinCount >= 3)
throw new RuntimeException("Selector appears to be spinning");
if (spinCount >= 3) {
System.err.println("Selector appears to be spinning");
failed = true;
break;
}
}
sc1.close();
sel.close();
if (failed)
throw new RuntimeException("Test failed");
System.out.println("PASS");
}
......
......@@ -25,7 +25,6 @@
* @bug 4511624
* @summary Test Making lots of Selectors
* @library ..
* @run main/timeout=240 Connect
*/
import java.io.*;
......@@ -38,7 +37,7 @@ import java.nio.channels.spi.SelectorProvider;
public class Connect {
static int success = 0;
static int LIMIT = 500;
static int LIMIT = 100;
public static void main(String[] args) throws Exception {
scaleTest();
......@@ -51,29 +50,30 @@ public class Connect {
for (int j=0; j<LIMIT; j++) {
SocketChannel sc = SocketChannel.open();
sc.configureBlocking(false);
boolean result = sc.connect(isa);
if (!result) {
boolean connected = sc.connect(isa);
if (!connected) {
Selector RSelector = SelectorProvider.provider().openSelector();
SelectionKey RKey = sc.register (RSelector, SelectionKey.OP_CONNECT);
while (!result) {
while (!connected) {
int keysAdded = RSelector.select(100);
if (keysAdded > 0) {
Set readyKeys = RSelector.selectedKeys();
Iterator i = readyKeys.iterator();
Set<SelectionKey> readyKeys = RSelector.selectedKeys();
Iterator<SelectionKey> i = readyKeys.iterator();
while (i.hasNext()) {
SelectionKey sk = (SelectionKey)i.next();
SelectionKey sk = i.next();
SocketChannel nextReady = (SocketChannel)sk.channel();
result = nextReady.finishConnect();
connected = nextReady.finishConnect();
}
readyKeys.clear();
}
}
RSelector.close();
}
read(sc);
readAndClose(sc);
}
}
static void read(SocketChannel sc) throws Exception {
static void readAndClose(SocketChannel sc) throws Exception {
ByteBuffer bb = ByteBuffer.allocateDirect(100);
int n = 0;
while (n == 0) // Note this is not a rigorous check for done reading
......
......@@ -45,8 +45,8 @@ public class ConnectWrite {
Selector selector = SelectorProvider.provider().openSelector();
InetAddress myAddress=InetAddress.getByName(TestUtil.HOST);
InetSocketAddress isa = new InetSocketAddress(myAddress, port);
SocketChannel sc = SocketChannel.open();
try {
SocketChannel sc = SocketChannel.open();
sc.configureBlocking(false);
SelectionKey key = sc.register(selector, SelectionKey.OP_CONNECT);
boolean result = sc.connect(isa);
......@@ -80,6 +80,7 @@ public class ConnectWrite {
}
}
} finally {
sc.close();
selector.close();
}
}
......
......@@ -33,9 +33,15 @@ import java.io.IOException;
public class HelperSlowToDie {
private static final int CHANNELS_PER_THREAD = 1023;
private static final int TEST_ITERATIONS = 200;
private static volatile boolean done;
public static void main(String[] args) throws IOException {
if (!System.getProperty("os.name").startsWith("Windows")) {
System.out.println("Test skipped as it verifies a Windows specific bug");
return;
}
Selector sel = Selector.open();
// register channels
......@@ -60,7 +66,7 @@ public class HelperSlowToDie {
new Thread(busy).start();
// Loop changing the number of channels from 1023 to 1024 and back.
for (int i=0; i<1000; i++) {
for (int i=0; i<TEST_ITERATIONS; i++) {
SocketChannel sc = SocketChannel.open();
sc.configureBlocking(false);
sc.register(sel, SelectionKey.OP_CONNECT);
......@@ -71,5 +77,11 @@ public class HelperSlowToDie {
// terminate busy threads
done = true;
// clean-up
for (int i=0; i<CHANNELS_PER_THREAD; i++) {
channels[i].close();
}
sel.close();
}
}
......@@ -49,14 +49,18 @@ public class KeysReady {
// Prepare a selector
Selector selector = SelectorProvider.provider().openSelector();
SelectionKey key = sc.register(selector, SelectionKey.OP_CONNECT);
int keysAdded = selector.select();
if (keysAdded > 0) {
keysAdded = selector.select(1000);
if (keysAdded > 0)
throw new Exception("Same key reported added twice");
try {
SelectionKey key = sc.register(selector, SelectionKey.OP_CONNECT);
int keysAdded = selector.select();
if (keysAdded > 0) {
keysAdded = selector.select(1000);
if (keysAdded > 0)
throw new Exception("Same key reported added twice");
}
} finally {
selector.close();
sc.close();
}
sc.close();
}
public static void main(String[] args) throws Exception {
......
......@@ -35,19 +35,11 @@ import java.nio.channels.*;
public class LotsOfChannels {
private final static int PIPES_COUNT = 1900;
private final static int PIPES_COUNT = 256;
private final static int BUF_SIZE = 8192;
private final static int LOOPS = 10;
public static void main(String[] argv) throws Exception {
String os = System.getProperty("os.name");
if (!(os.equals("Windows NT")
|| os.equals("Windows 2000")
|| os.equals("Windows XP")))
return;
Pipe[] pipes = new Pipe[PIPES_COUNT];
Pipe pipe = Pipe.open();
Pipe.SinkChannel sink = pipe.sink();
......@@ -72,6 +64,13 @@ public class LotsOfChannels {
sel.selectedKeys().clear();
source.read(ByteBuffer.allocate(BUF_SIZE));
}
for (int i = 0; i < PIPES_COUNT; i++ ) {
pipes[i].sink().close();
pipes[i].source().close();
}
pipe.sink().close();
pipe.source().close();
sel.close();
}
}
......@@ -35,6 +35,7 @@ import java.io.IOException;
public class RegAfterPreClose {
static final int TEST_ITERATIONS = 300;
static volatile boolean done;
/**
......@@ -96,26 +97,21 @@ public class RegAfterPreClose {
}
};
// schedule test to run for 1 minute
Executors.newScheduledThreadPool(1, factory).schedule(new Runnable() {
public void run() {
done = true;
sel.wakeup();
}}, 1, TimeUnit.MINUTES);
// create Executor that handles tasks that closes channels
// "asynchronously" - this creates the conditions to provoke the bug.
Executor executor = Executors.newFixedThreadPool(2, factory);
ExecutorService executor = Executors.newFixedThreadPool(2, factory);
// submit task that connects to listener
executor.execute(new Connector(ssc.socket().getLocalPort()));
// loop accepting connections until done (or an IOException is thrown)
while (!done) {
int remaining = TEST_ITERATIONS;
while (remaining > 0) {
sel.select();
if (key.isAcceptable()) {
SocketChannel sc = ssc.accept();
if (sc != null) {
remaining--;
sc.configureBlocking(false);
sc.register(sel, SelectionKey.OP_READ);
executor.execute(new Closer(sc));
......@@ -123,5 +119,8 @@ public class RegAfterPreClose {
}
sel.selectedKeys().clear();
}
done = true;
sel.close();
executor.shutdown();
}
}
......@@ -31,11 +31,7 @@ import java.io.IOException;
import java.net.*;
public class SelectAndCancel {
static ServerSocketChannel ssc;
static Selector selector;
static SelectionKey sk;
static InetSocketAddress isa;
public static int TEST_PORT = 40170;
/*
* CancelledKeyException is the failure symptom of 4729342
......@@ -43,17 +39,17 @@ public class SelectAndCancel {
* seen immediately when the bug is present.
*/
public static void main(String[] args) throws Exception {
InetAddress lh = InetAddress.getLocalHost();
isa = new InetSocketAddress(lh, TEST_PORT);
selector = Selector.open();
ssc = ServerSocketChannel.open();
final Selector selector = Selector.open();
final ServerSocketChannel ssc =
ServerSocketChannel.open().bind(new InetSocketAddress(0));
final InetSocketAddress isa =
new InetSocketAddress(InetAddress.getLocalHost(), ssc.socket().getLocalPort());
// Create and start a selector in a separate thread.
new Thread(new Runnable() {
public void run() {
try {
ssc.configureBlocking(false);
ssc.socket().bind(isa);
sk = ssc.register(selector, SelectionKey.OP_ACCEPT);
selector.select();
} catch (IOException e) {
......
......@@ -26,6 +26,8 @@
* @summary Ensure that a Selector can return at least 100 selected keys
* @author Mark Reinhold
* @library ..
* @build SelectorLimit
* @run main/othervm SelectorLimit
*/
import java.io.*;
......
......@@ -57,13 +57,13 @@ public class SelectorTest {
*/
public static void main(String[] args) throws Exception {
if (args.length == 0) {
InetSocketAddress isa
= new InetSocketAddress(InetAddress.getLocalHost(), TEST_PORT);
Server server = new Server(isa);
Server server = new Server(0);
server.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) { }
InetSocketAddress isa
= new InetSocketAddress(InetAddress.getLocalHost(), server.port());
Client client = new Client(isa);
client.start();
if ((server.finish(FINISH_TIME) & client.finish(FINISH_TIME)) == 0)
......@@ -74,9 +74,7 @@ public class SelectorTest {
if (args.length > 1)
TEST_PORT = Integer.parseInt(args[1]);
InetSocketAddress isa
= new InetSocketAddress(InetAddress.getLocalHost(), TEST_PORT);
Server server = new Server(isa);
Server server = new Server(TEST_PORT);
server.start();
if (server.finish(FINISH_TIME) == 0)
throw new Exception("Failure");
......@@ -136,18 +134,22 @@ public class SelectorTest {
}
static class Server extends TestThread {
private final ServerSocketChannel ssc;
private List socketList = new ArrayList();
private ServerSocket ss;
private int connectionsAccepted = 0;
private Selector pollSelector;
private Selector acceptSelector;
private InetSocketAddress isa;
private Set pkeys;
private Set pskeys;
Server(InetSocketAddress isa) {
Server(int port) throws IOException {
super("Server", SelectorTest.log);
this.isa = isa;
this.ssc = ServerSocketChannel.open().bind(new InetSocketAddress(port));
}
int port() {
return ssc.socket().getLocalPort();
}
public void go() throws Exception {
......@@ -162,11 +164,7 @@ public class SelectorTest {
requestThread.start();
ServerSocketChannel ssc = ServerSocketChannel.open();
ssc.configureBlocking(false);
ssc.socket().setReuseAddress(true);
ssc.socket().bind(isa);
SelectionKey acceptKey = ssc.register(acceptSelector,
SelectionKey.OP_ACCEPT);
while(connectionsAccepted < SelectorTest.NUM_CLIENTS) {
......
......@@ -44,10 +44,15 @@ public class WakeupNow {
p.source().configureBlocking(false);
p.source().register(sel, SelectionKey.OP_READ);
sel.wakeup();
// ensure wakeup is consumed by selectNow
Thread.sleep(2000);
sel.selectNow();
long startTime = System.currentTimeMillis();
int n = sel.select(2000);
long endTime = System.currentTimeMillis();
p.source().close();
p.sink().close();
sel.close();
if (endTime - startTime < 1000)
throw new RuntimeException("test failed");
}
......@@ -60,10 +65,13 @@ public class WakeupNow {
Pipe p = Pipe.open();
p.source().configureBlocking(false);
sel.wakeup();
// ensure wakeup is consumed by selectNow
Thread.sleep(2000);
sel.selectNow();
long startTime = System.currentTimeMillis();
int n = sel.select(2000);
long endTime = System.currentTimeMillis();
sel.close();
if (endTime - startTime < 1000)
throw new RuntimeException("test failed");
}
......
......@@ -31,8 +31,12 @@ import java.nio.channels.*;
public class WakeupOverflow {
public static void main( String[] args ) throws Exception {
Selector selector = Selector.open();
for(int i=0; i<10000; i++) {
selector.wakeup();
try {
for(int i=0; i<10000; i++) {
selector.wakeup();
}
} finally {
selector.close();
}
}
}
......@@ -35,16 +35,19 @@ public class WakeupSpeed {
public static void main(String argv[]) throws Exception {
int waitTime = 4000;
Selector selector = Selector.open();
selector.wakeup();
long t1 = System.currentTimeMillis();
selector.select(waitTime);
long t2 = System.currentTimeMillis();
long totalTime = t2 - t1;
if (totalTime > waitTime)
throw new RuntimeException("Test failed");
try {
selector.wakeup();
long t1 = System.currentTimeMillis();
selector.select(waitTime);
long t2 = System.currentTimeMillis();
long totalTime = t2 - t1;
if (totalTime > waitTime)
throw new RuntimeException("Test failed");
} finally {
selector.close();
}
}
}
/*
* Copyright (c) 2001, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @summary test the address returned in socket from accept
*/
import java.io.*;
import java.net.*;
import java.nio.*;
import java.nio.channels.*;
public class AcceptAddress {
public static void main(String[] args) throws Exception {
InetAddress local = InetAddress.getLocalHost();
InetSocketAddress isa = new InetSocketAddress(local, 5555);
ServerSocketChannel ssc;
ssc = ServerSocketChannel.open();
ssc.socket().bind(isa);
SocketChannel sc;
sc = SocketChannel.open();
sc.connect(isa);
SocketChannel sc2 = ssc.accept();
System.err.println("Socket connected to " + sc2);
}
}
......@@ -78,8 +78,6 @@ public class AdaptSocket {
throw x;
}
}
if (shouldTimeout)
throw new Exception("Connection did not time out");
}
out.println("connected: " + so);
out.println(" " + sc);
......@@ -118,8 +116,6 @@ public class AdaptSocket {
}
throw x;
}
if (shouldTimeout)
throw new Exception("Read did not time out");
}
static void testRead(String hn, int timeout, boolean shouldTimeout)
......
......@@ -31,13 +31,20 @@ import java.nio.channels.*;
public class Bind {
public static void main(String[] args) throws Exception {
SocketChannel sc1 = SocketChannel.open();
try {
SocketChannel channel1 = SocketChannel.open();
channel1.socket().bind(new InetSocketAddress(5555));
SocketChannel channel2 = SocketChannel.open();
channel2.socket().bind(new InetSocketAddress(5555));
sc1.bind(new InetSocketAddress(0));
int port = sc1.socket().getLocalPort();
SocketChannel sc2 = SocketChannel.open();
try {
sc2.bind(new InetSocketAddress(port));
} finally {
sc2.close();
}
} catch (BindException be) {
// Correct result
} finally {
sc1.close();
}
}
}
......@@ -56,8 +56,12 @@ public class Close {
static void testChannelClose() throws IOException {
SelectionKey sk = open();
sk.channel().close();
check(sk);
try {
sk.channel().close();
check(sk);
} finally {
sk.selector().close();
}
}
public static void main(String[] args) throws Exception {
......
......@@ -55,5 +55,8 @@ public class CloseRegisteredChannel {
System.out.println ("Will hang here...");
int nb = slave.read (ByteBuffer.allocate (1024));
//System.out.println("read nb=" + nb);
selector.close();
server.close();
}
}
......@@ -33,11 +33,12 @@ import java.nio.channels.*;
import java.net.*;
public class CloseTimeoutChannel {
final static int PORT=6347;
public static void main(String args[]) throws Exception {
int port = -1;
try {
ServerSocketChannel listener=ServerSocketChannel.open();
listener.socket().bind(new InetSocketAddress(PORT));
listener.socket().bind(new InetSocketAddress(0));
port = listener.socket().getLocalPort();
AcceptorThread thread=new AcceptorThread(listener);
thread.start();
} catch (IOException e) {
......@@ -50,7 +51,7 @@ public class CloseTimeoutChannel {
try {
System.out.println("Establishing connection");
Socket socket=SocketChannel.open(
new InetSocketAddress("127.0.0.1", PORT)).socket();
new InetSocketAddress("127.0.0.1", port)).socket();
OutputStream out=socket.getOutputStream();
InputStream in=socket.getInputStream();
......@@ -98,7 +99,8 @@ public class CloseTimeoutChannel {
Thread.sleep(100);
} catch (InterruptedException e) { }
System.out.println(INDENT+"Listening on port "+ PORT);
System.out.println(INDENT+"Listening on port "+
_listener.socket().getLocalPort());
ByteBuffer buf=ByteBuffer.allocate(5);
Socket client=_listener.accept().socket();;
System.out.println(INDENT+"Accepted client");
......@@ -123,6 +125,8 @@ public class CloseTimeoutChannel {
client.close();
} catch (IOException e) {
System.out.println(INDENT+"Error accepting!");
} finally {
try { _listener.close(); } catch (IOException ignore) { }
}
}
}
......
......@@ -48,27 +48,31 @@ public class IsConnectable {
sc.connect(isa);
Selector selector = SelectorProvider.provider().openSelector();
SelectionKey key = sc.register(selector, SelectionKey.OP_CONNECT);
int keysAdded = selector.select();
if (keysAdded > 0) {
boolean result = sc.finishConnect();
if (result) {
keysAdded = selector.select(5000);
// 4750573: keysAdded should not be incremented when op is dropped
// from a key already in the selected key set
if (keysAdded > 0)
throw new Exception("Test failed: 4750573 detected");
Set sel = selector.selectedKeys();
Iterator i = sel.iterator();
SelectionKey sk = (SelectionKey)i.next();
// 4737146: isConnectable should be false while connected
if (sk.isConnectable())
throw new Exception("Test failed: 4737146 detected");
try {
SelectionKey key = sc.register(selector, SelectionKey.OP_CONNECT);
int keysAdded = selector.select();
if (keysAdded > 0) {
boolean result = sc.finishConnect();
if (result) {
keysAdded = selector.select(5000);
// 4750573: keysAdded should not be incremented when op is dropped
// from a key already in the selected key set
if (keysAdded > 0)
throw new Exception("Test failed: 4750573 detected");
Set<SelectionKey> sel = selector.selectedKeys();
Iterator<SelectionKey> i = sel.iterator();
SelectionKey sk = i.next();
// 4737146: isConnectable should be false while connected
if (sk.isConnectable())
throw new Exception("Test failed: 4737146 detected");
}
} else {
throw new Exception("Select failed");
}
} else {
throw new Exception("Select failed");
} finally {
sc.close();
selector.close();
}
sc.close();
}
public static void main(String[] args) throws Exception {
......
......@@ -38,25 +38,33 @@ public class LocalAddress {
static void test1() throws Exception {
InetAddress bogus = InetAddress.getByName("0.0.0.0");
SocketChannel sc = SocketChannel.open();
InetSocketAddress saddr = new InetSocketAddress(
InetAddress.getByName(TestUtil.HOST), 23);
//Test1: connect only
sc.connect(saddr);
InetAddress isa = sc.socket().getLocalAddress();
if (isa == null || isa.equals(bogus))
throw new RuntimeException("test failed");
SocketChannel sc = SocketChannel.open();
try {
sc.connect(saddr);
InetAddress ia = sc.socket().getLocalAddress();
if (ia == null || ia.equals(bogus))
throw new RuntimeException("test failed");
} finally {
sc.close();
}
//Test2: bind and connect
sc = SocketChannel.open();
sc.socket().bind(new InetSocketAddress(0));
if (sc.socket().getLocalPort() == 0)
throw new RuntimeException("test failed");
sc.socket().connect(saddr);
isa = sc.socket().getLocalAddress();
if (isa == null || isa.isAnyLocalAddress())
throw new RuntimeException("test failed");
try {
sc.socket().bind(new InetSocketAddress(0));
if (sc.socket().getLocalPort() == 0)
throw new RuntimeException("test failed");
sc.socket().connect(saddr);
InetAddress ia = sc.socket().getLocalAddress();
if (ia == null || ia.isAnyLocalAddress())
throw new RuntimeException("test failed");
} finally {
sc.close();
}
}
}
......@@ -105,7 +105,11 @@ public class SocketInheritance {
// launch the child
String cmd = System.getProperty("java.home") + File.separator + "bin" +
File.separator + "java SocketInheritance -child " + port;
File.separator + "java";
String testClasses = System.getProperty("test.classes");
if (testClasses != null)
cmd += " -cp " + testClasses;
cmd += " SocketInheritance -child " + port;
Process p = Runtime.getRuntime().exec(cmd);
......
......@@ -33,22 +33,27 @@ public class Trivial {
public static void main(String[] args) throws Exception {
SocketChannel sc = SocketChannel.open();
Selector sel = Selector.open();
if (sc.keyFor(sel) != null)
throw new Exception("keyFor != null");
sc.configureBlocking(false);
SelectionKey sk = sc.register(sel, SelectionKey.OP_READ, args);
if (sc.keyFor(sel) != sk)
throw new Exception("keyFor returned " + sc.keyFor(sel));
if (sk.attachment() != args)
throw new Exception("attachment() returned " + sk.attachment());
Trivial t = new Trivial();
sk.attach(t);
if (sk.attachment() != t)
throw new Exception("Wrong attachment");
sk.isReadable();
sk.isWritable();
sk.isConnectable();
sk.isAcceptable();
try {
if (sc.keyFor(sel) != null)
throw new Exception("keyFor != null");
sc.configureBlocking(false);
SelectionKey sk = sc.register(sel, SelectionKey.OP_READ, args);
if (sc.keyFor(sel) != sk)
throw new Exception("keyFor returned " + sc.keyFor(sel));
if (sk.attachment() != args)
throw new Exception("attachment() returned " + sk.attachment());
Trivial t = new Trivial();
sk.attach(t);
if (sk.attachment() != t)
throw new Exception("Wrong attachment");
sk.isReadable();
sk.isWritable();
sk.isConnectable();
sk.isAcceptable();
} finally {
sel.close();
sc.close();
}
}
}
......@@ -57,39 +57,47 @@ public class UnboundSocketTests {
System.out.println("\n-- SocketChannel --");
SocketChannel sc = SocketChannel.open();
check("getLocalPort()", sc.socket().getLocalPort(), -1);
checkIsAnyLocalAddress("getLocalAddress()",
sc.socket().getLocalAddress());
check("getLocalSocketAddress()", sc.socket().getLocalSocketAddress(), null);
check("getPort()", sc.socket().getPort(), 0);
check("getInetAddress()", sc.socket().getInetAddress(), null);
check("getRemoteSocketAddress()", sc.socket().getRemoteSocketAddress(), null);
try {
check("getLocalPort()", sc.socket().getLocalPort(), -1);
checkIsAnyLocalAddress("getLocalAddress()",
sc.socket().getLocalAddress());
check("getLocalSocketAddress()", sc.socket().getLocalSocketAddress(), null);
check("getPort()", sc.socket().getPort(), 0);
check("getInetAddress()", sc.socket().getInetAddress(), null);
check("getRemoteSocketAddress()", sc.socket().getRemoteSocketAddress(), null);
} finally {
sc.close();
}
System.out.println("\n-- ServerSocketChannel --");
ServerSocketChannel ssc = ServerSocketChannel.open();
check("getLocalPort()", ssc.socket().getLocalPort(), -1);
check("getInetAddress()", ssc.socket().getInetAddress(), null);
check("getLocalSocketAddress()", ssc.socket().getLocalSocketAddress(), null);
try {
check("getLocalPort()", ssc.socket().getLocalPort(), -1);
check("getInetAddress()", ssc.socket().getInetAddress(), null);
check("getLocalSocketAddress()", ssc.socket().getLocalSocketAddress(), null);
} finally {
ssc.close();
}
System.out.println("\n-- DatagramChannel --");
DatagramChannel dc = DatagramChannel.open();
// not specified
check("getLocalPort()", dc.socket().getLocalPort(), 0);
checkIsAnyLocalAddress("getLocalAddress()",
dc.socket().getLocalAddress());
check("getLocalSocketAddress()", dc.socket().getLocalSocketAddress(), null);
check("getPort()", dc.socket().getPort(), -1);
check("getInetAddress()", dc.socket().getInetAddress(), null);
check("getRemoteSocketAddress()", dc.socket().getRemoteSocketAddress(), null);
try {
// not specified
check("getLocalPort()", dc.socket().getLocalPort(), 0);
checkIsAnyLocalAddress("getLocalAddress()",
dc.socket().getLocalAddress());
check("getLocalSocketAddress()", dc.socket().getLocalSocketAddress(), null);
check("getPort()", dc.socket().getPort(), -1);
check("getInetAddress()", dc.socket().getInetAddress(), null);
check("getRemoteSocketAddress()", dc.socket().getRemoteSocketAddress(), null);
} finally {
dc.close();
}
if (failures > 0) {
throw new RuntimeException(failures + " sub-tests(s) failed.");
......
......@@ -35,7 +35,6 @@ import java.nio.channels.*;
public class Shadow {
private static final int PORT = 2019;
static PrintStream log = System.err;
private static void dump(ServerSocket s) {
......@@ -69,7 +68,7 @@ public class Shadow {
public static void main(String[] args) throws Exception {
boolean useChannels
= ((args.length == 0) || Boolean.valueOf(args[0]).booleanValue());
int port = (args.length > 1 ? Integer.parseInt(args[1]) : PORT);
int port = (args.length > 1 ? Integer.parseInt(args[1]) : -1);
// open server socket
ServerSocket serverSocket;
......@@ -86,7 +85,8 @@ public class Shadow {
}
// bind server socket to port
SocketAddress bindAddr = new InetSocketAddress(port);
SocketAddress bindAddr =
new InetSocketAddress((port == -1) ? 0 : port);
serverSocket.bind(bindAddr);
log.println("bound ServerSocket: " + serverSocket);
......
......@@ -26,6 +26,8 @@
* @bug 4997227
* @summary Calling inheritedChannel() after FileDescriptor.in was closed
* caused an InternalError to be thrown.
* @build ClosedStreams
* @run main/othervm ClosedStreams
*/
import java.io.FileDescriptor;
......
......@@ -32,5 +32,7 @@ import java.nio.channels.Pipe;
public class Basic {
public static void main(String[] args) throws Exception {
Pipe p = Pipe.open();
p.source().close();
p.sink().close();
}
}
......@@ -54,8 +54,12 @@ public class TempBuffer {
blah.deleteOnExit();
TempBuffer.initTestFile(blah);
RandomAccessFile raf = new RandomAccessFile(blah, "rw");
FileChannel fs = raf.getChannel();
fs.transferTo(0, SIZE, Channels.newChannel(out));
FileChannel fc = raf.getChannel();
try {
fc.transferTo(0, SIZE, Channels.newChannel(out));
} finally {
fc.close();
}
out.flush();
} catch (IOException ioe) {
throw new RuntimeException(ioe);
......@@ -69,10 +73,17 @@ public class TempBuffer {
File blah = File.createTempFile("blah2", null);
blah.deleteOnExit();
RandomAccessFile raf = new RandomAccessFile(blah, "rw");
FileChannel fs = raf.getChannel();
raf.setLength(SIZE);
fs.transferFrom(Channels.newChannel(in), 0, SIZE);
fs.close();
FileChannel fc = raf.getChannel();
try {
raf.setLength(SIZE);
fc.transferFrom(Channels.newChannel(in), 0, SIZE);
} finally {
fc.close();
}
sourceChannel.close();
sinkChannel.close();
blah.delete();
}
private static void initTestFile(File blah) throws IOException {
......
......@@ -43,15 +43,18 @@ public class ReadZero {
return 0;
}
};
is.read(new byte[1], 0, 1); // ok
InputStreamReader isr = new InputStreamReader(is);
try {
int res = isr.read(new char[1], 0, 1);
} catch (IOException x) {
System.out.println("IOException caught");
return;
is.read(new byte[1], 0, 1); // ok
InputStreamReader isr = new InputStreamReader(is);
try {
int res = isr.read(new char[1], 0, 1);
} catch (IOException x) {
System.out.println("IOException caught");
return;
}
} finally {
is.close();
}
throw new RuntimeException("IOException not thrown");
}
......
......@@ -32,7 +32,12 @@ import java.io.UnsupportedEncodingException;
public class Test4206507 {
public static void main(String[] args) throws UnsupportedEncodingException {
Locale.setDefault(new Locale("tr", "TR"));
byte[] b = "".getBytes("ISO8859-9");
Locale l = Locale.getDefault();
try {
Locale.setDefault(new Locale("tr", "TR"));
byte[] b = "".getBytes("ISO8859-9");
} finally {
Locale.setDefault(l);
}
}
}
......@@ -26,7 +26,7 @@
/* @test
@bug 6636323 6636319
@summary Test if StringCoding and NIO result have the same de/encoding result
* @run main/timeout=2000 TestStringCoding
* @run main/othervm/timeout=2000 TestStringCoding
*/
import java.util.*;
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册