提交 0de4e06d 编写于 作者: S sherman

Merge

......@@ -92,9 +92,9 @@ ABS_TEMP_DIR = $(ABS_OUTPUTDIR)/tmp
dummy := $(shell $(MKDIR) -p $(TEMP_DIR))
# The language version we want for this jdk build
SOURCE_LANGUAGE_VERSION=5
SOURCE_LANGUAGE_VERSION=7
# The class version we want for this jdk build
TARGET_CLASS_VERSION=5
TARGET_CLASS_VERSION=7
# The MESSAGE, WARNING and ERROR files are used to store sanity check and
# source check messages, warnings and errors.
......
......@@ -122,13 +122,13 @@ ifeq ($(JAVAC_WARNINGS_FATAL), true)
JAVACFLAGS += -Werror
endif
# Add the source level (currently all source is 1.5, should this be 1.6?)
SOURCE_LANGUAGE_VERSION = 5
# Add the source level
SOURCE_LANGUAGE_VERSION = 7
LANGUAGE_VERSION = -source $(SOURCE_LANGUAGE_VERSION)
JAVACFLAGS += $(LANGUAGE_VERSION)
# Add the class version we want (currently this is 5, should it be 6 or even 7?)
TARGET_CLASS_VERSION = 5
# Add the class version we want
TARGET_CLASS_VERSION = 7
CLASS_VERSION = -target $(TARGET_CLASS_VERSION)
JAVACFLAGS += $(CLASS_VERSION)
JAVACFLAGS += -encoding ascii
......
......@@ -33,8 +33,8 @@ AUTO_FILES_JAVA_DIRS = java/dyn sun/dyn
# The sources built here use new language syntax to generate
# method handle calls. Let's be sure we are using that format.
#LANGUAGE_VERSION = -source 7
#CLASS_VERSION = -target 7
LANGUAGE_VERSION = -source 7
CLASS_VERSION = -target 7
# Actually, it will be less disruptive to compile with the same
# -target option as the rest of the system, and just turn on
......
......@@ -93,9 +93,7 @@ final class Filter {
int filtOffset[] = new int[1];
for (filtOffset[0] = filterStart;
filtOffset[0] < filterEnd;
filtOffset[0]++) {
for (filtOffset[0] = filterStart; filtOffset[0] < filterEnd;) {
switch (filter[filtOffset[0]]) {
case '(':
filtOffset[0]++;
......@@ -104,18 +102,21 @@ final class Filter {
case '&':
encodeComplexFilter(ber, filter,
LDAP_FILTER_AND, filtOffset, filterEnd);
// filtOffset[0] has pointed to char after right paren
parens--;
break;
case '|':
encodeComplexFilter(ber, filter,
LDAP_FILTER_OR, filtOffset, filterEnd);
// filtOffset[0] has pointed to char after right paren
parens--;
break;
case '!':
encodeComplexFilter(ber, filter,
LDAP_FILTER_NOT, filtOffset, filterEnd);
// filtOffset[0] has pointed to char after right paren
parens--;
break;
......@@ -143,8 +144,8 @@ final class Filter {
encodeSimpleFilter(ber, filter, filtOffset[0], nextOffset);
// points to right parens; for loop will increment beyond parens
filtOffset[0] = nextOffset;
// points to the char after right paren.
filtOffset[0] = nextOffset + 1;
parens--;
break;
......@@ -170,9 +171,14 @@ final class Filter {
filtOffset[0] = filterEnd; // force break from outer
break;
}
if (parens < 0) {
throw new InvalidSearchFilterException(
"Unbalanced parenthesis");
}
}
if (parens > 0) {
if (parens != 0) {
throw new InvalidSearchFilterException("Unbalanced parenthesis");
}
......
......@@ -2784,8 +2784,13 @@ class Character extends Object implements java.io.Serializable, Comparable<Chara
* @since 1.5
*/
public static int toCodePoint(char high, char low) {
return ((high - MIN_HIGH_SURROGATE) << 10)
+ (low - MIN_LOW_SURROGATE) + MIN_SUPPLEMENTARY_CODE_POINT;
// Optimized form of:
// return ((high - MIN_HIGH_SURROGATE) << 10)
// + (low - MIN_LOW_SURROGATE)
// + MIN_SUPPLEMENTARY_CODE_POINT;
return ((high << 10) + low) + (MIN_SUPPLEMENTARY_CODE_POINT
- (MIN_HIGH_SURROGATE << 10)
- MIN_LOW_SURROGATE);
}
/**
......@@ -3071,9 +3076,10 @@ class Character extends Object implements java.io.Serializable, Comparable<Chara
}
static void toSurrogates(int codePoint, char[] dst, int index) {
int offset = codePoint - MIN_SUPPLEMENTARY_CODE_POINT;
dst[index+1] = (char)((offset & 0x3ff) + MIN_LOW_SURROGATE);
dst[index] = (char)((offset >>> 10) + MIN_HIGH_SURROGATE);
// We write elements "backwards" to guarantee all-or-nothing
dst[index+1] = (char)((codePoint & 0x3ff) + MIN_LOW_SURROGATE);
dst[index] = (char)((codePoint >>> 10)
+ (MIN_HIGH_SURROGATE - (MIN_SUPPLEMENTARY_CODE_POINT >>> 10)));
}
/**
......
......@@ -30,7 +30,6 @@ import java.nio.charset.CoderResult;
import java.nio.charset.MalformedInputException;
import java.nio.charset.UnmappableCharacterException;
/**
* Utility class for dealing with surrogates.
*
......@@ -41,19 +40,15 @@ public class Surrogate {
private Surrogate() { }
// UTF-16 surrogate-character ranges
//
public static final char MIN_HIGH = '\uD800';
public static final char MAX_HIGH = '\uDBFF';
public static final char MIN_LOW = '\uDC00';
public static final char MAX_LOW = '\uDFFF';
public static final char MIN = MIN_HIGH;
public static final char MAX = MAX_LOW;
// Range of UCS-4 values that need surrogates in UTF-16
//
public static final int UCS4_MIN = 0x10000;
public static final int UCS4_MAX = (1 << 20) + UCS4_MIN - 1;
// TODO: Deprecate/remove the following redundant definitions
public static final char MIN_HIGH = Character.MIN_HIGH_SURROGATE;
public static final char MAX_HIGH = Character.MAX_HIGH_SURROGATE;
public static final char MIN_LOW = Character.MIN_LOW_SURROGATE;
public static final char MAX_LOW = Character.MAX_LOW_SURROGATE;
public static final char MIN = Character.MIN_SURROGATE;
public static final char MAX = Character.MAX_SURROGATE;
public static final int UCS4_MIN = Character.MIN_SUPPLEMENTARY_CODE_POINT;
public static final int UCS4_MAX = Character.MAX_CODE_POINT;
/**
* Tells whether or not the given UTF-16 value is a high surrogate.
......@@ -76,36 +71,46 @@ public class Surrogate {
return (MIN <= c) && (c <= MAX);
}
/**
* Tells whether or not the given UCS-4 character is in the Basic
* Multilingual Plane, and can be represented using a single char.
*/
public static boolean isBMP(int uc) {
return (int) (char) uc == uc;
}
/**
* Tells whether or not the given UCS-4 character must be represented as a
* surrogate pair in UTF-16.
*/
public static boolean neededFor(int uc) {
return (uc >= UCS4_MIN) && (uc <= UCS4_MAX);
return Character.isSupplementaryCodePoint(uc);
}
/**
* Returns the high UTF-16 surrogate for the given UCS-4 character.
*/
public static char high(int uc) {
assert neededFor(uc);
return (char)(0xd800 | (((uc - UCS4_MIN) >> 10) & 0x3ff));
assert Character.isSupplementaryCodePoint(uc);
return (char)((uc >> 10)
+ (Character.MIN_HIGH_SURROGATE
- (Character.MIN_SUPPLEMENTARY_CODE_POINT >> 10)));
}
/**
* Returns the low UTF-16 surrogate for the given UCS-4 character.
*/
public static char low(int uc) {
assert neededFor(uc);
return (char)(0xdc00 | ((uc - UCS4_MIN) & 0x3ff));
assert Character.isSupplementaryCodePoint(uc);
return (char)((uc & 0x3ff) + Character.MIN_LOW_SURROGATE);
}
/**
* Converts the given surrogate pair into a 32-bit UCS-4 character.
*/
public static int toUCS4(char c, char d) {
assert isHigh(c) && isLow(d);
return (((c & 0x3ff) << 10) | (d & 0x3ff)) + 0x10000;
assert Character.isHighSurrogate(c) && Character.isLowSurrogate(d);
return Character.toCodePoint(c, d);
}
/**
......@@ -178,14 +183,14 @@ public class Surrogate {
* object
*/
public int parse(char c, CharBuffer in) {
if (Surrogate.isHigh(c)) {
if (Character.isHighSurrogate(c)) {
if (!in.hasRemaining()) {
error = CoderResult.UNDERFLOW;
return -1;
}
char d = in.get();
if (Surrogate.isLow(d)) {
character = toUCS4(c, d);
if (Character.isLowSurrogate(d)) {
character = Character.toCodePoint(c, d);
isPair = true;
error = null;
return character;
......@@ -193,7 +198,7 @@ public class Surrogate {
error = CoderResult.malformedForLength(1);
return -1;
}
if (Surrogate.isLow(c)) {
if (Character.isLowSurrogate(c)) {
error = CoderResult.malformedForLength(1);
return -1;
}
......@@ -220,14 +225,14 @@ public class Surrogate {
*/
public int parse(char c, char[] ia, int ip, int il) {
assert (ia[ip] == c);
if (Surrogate.isHigh(c)) {
if (Character.isHighSurrogate(c)) {
if (il - ip < 2) {
error = CoderResult.UNDERFLOW;
return -1;
}
char d = ia[ip + 1];
if (Surrogate.isLow(d)) {
character = toUCS4(c, d);
if (Character.isLowSurrogate(d)) {
character = Character.toCodePoint(c, d);
isPair = true;
error = null;
return character;
......@@ -235,7 +240,7 @@ public class Surrogate {
error = CoderResult.malformedForLength(1);
return -1;
}
if (Surrogate.isLow(c)) {
if (Character.isLowSurrogate(c)) {
error = CoderResult.malformedForLength(1);
return -1;
}
......@@ -282,7 +287,7 @@ public class Surrogate {
* error() will return a descriptive result object
*/
public int generate(int uc, int len, CharBuffer dst) {
if (uc <= 0xffff) {
if (Surrogate.isBMP(uc)) {
if (Surrogate.is(uc)) {
error = CoderResult.malformedForLength(len);
return -1;
......@@ -294,12 +299,7 @@ public class Surrogate {
dst.put((char)uc);
error = null;
return 1;
}
if (uc < Surrogate.UCS4_MIN) {
error = CoderResult.malformedForLength(len);
return -1;
}
if (uc <= Surrogate.UCS4_MAX) {
} else if (Character.isSupplementaryCodePoint(uc)) {
if (dst.remaining() < 2) {
error = CoderResult.OVERFLOW;
return -1;
......@@ -308,9 +308,10 @@ public class Surrogate {
dst.put(Surrogate.low(uc));
error = null;
return 2;
} else {
error = CoderResult.unmappableForLength(len);
return -1;
}
error = CoderResult.unmappableForLength(len);
return -1;
}
/**
......@@ -330,7 +331,7 @@ public class Surrogate {
* error() will return a descriptive result object
*/
public int generate(int uc, int len, char[] da, int dp, int dl) {
if (uc <= 0xffff) {
if (Surrogate.isBMP(uc)) {
if (Surrogate.is(uc)) {
error = CoderResult.malformedForLength(len);
return -1;
......@@ -342,12 +343,7 @@ public class Surrogate {
da[dp] = (char)uc;
error = null;
return 1;
}
if (uc < Surrogate.UCS4_MIN) {
error = CoderResult.malformedForLength(len);
return -1;
}
if (uc <= Surrogate.UCS4_MAX) {
} else if (Character.isSupplementaryCodePoint(uc)) {
if (dl - dp < 2) {
error = CoderResult.OVERFLOW;
return -1;
......@@ -356,11 +352,11 @@ public class Surrogate {
da[dp + 1] = Surrogate.low(uc);
error = null;
return 2;
} else {
error = CoderResult.unmappableForLength(len);
return -1;
}
error = CoderResult.unmappableForLength(len);
return -1;
}
}
}
......@@ -85,19 +85,21 @@ static jfieldID entry_options;
static jfieldID entry_dev;
/**
* System calls that may not be available at build time.
* System calls that may not be available at run time.
*/
typedef int openat64_func(int, const char *, int, ...);
typedef int fstatat64_func(int, const char *, struct stat64 *, int);
typedef int unlinkat_func(int, const char*, int);
typedef int renameat_func(int, const char*, int, const char*);
typedef int futimesat_func(int, const char *, const struct timeval *);
typedef DIR* fdopendir_func(int);
static openat64_func* my_openat64_func = NULL;
static fstatat64_func* my_fstatat64_func = NULL;
static unlinkat_func* my_unlinkat_func = NULL;
static renameat_func* my_renameat_func = NULL;
static futimesat_func* my_futimesat_func = NULL;
static fdopendir_func* my_fdopendir_func = NULL;
/**
* fstatat missing from glibc on Linux. Temporary workaround
......@@ -183,7 +185,7 @@ Java_sun_nio_fs_UnixNativeDispatcher_init(JNIEnv* env, jclass this)
entry_options = (*env)->GetFieldID(env, clazz, "opts", "[B");
entry_dev = (*env)->GetFieldID(env, clazz, "dev", "J");
/* system calls that might not be available at build time */
/* system calls that might not be available at run time */
#if defined(__solaris__) && defined(_LP64)
/* Solaris 64-bit does not have openat64/fstatat64 */
......@@ -196,6 +198,7 @@ Java_sun_nio_fs_UnixNativeDispatcher_init(JNIEnv* env, jclass this)
my_unlinkat_func = (unlinkat_func*) dlsym(RTLD_DEFAULT, "unlinkat");
my_renameat_func = (renameat_func*) dlsym(RTLD_DEFAULT, "renameat");
my_futimesat_func = (futimesat_func*) dlsym(RTLD_DEFAULT, "futimesat");
my_fdopendir_func = (fdopendir_func*) dlsym(RTLD_DEFAULT, "fdopendir");
#if defined(FSTATAT64_SYSCALL_AVAILABLE)
/* fstatat64 missing from glibc */
......@@ -205,7 +208,7 @@ Java_sun_nio_fs_UnixNativeDispatcher_init(JNIEnv* env, jclass this)
if (my_openat64_func != NULL && my_fstatat64_func != NULL &&
my_unlinkat_func != NULL && my_renameat_func != NULL &&
my_futimesat_func != NULL)
my_futimesat_func != NULL && my_fdopendir_func != NULL)
{
flags |= sun_nio_fs_UnixNativeDispatcher_HAS_AT_SYSCALLS;
}
......@@ -565,8 +568,13 @@ JNIEXPORT jlong JNICALL
Java_sun_nio_fs_UnixNativeDispatcher_fdopendir(JNIEnv* env, jclass this, int dfd) {
DIR* dir;
if (my_fdopendir_func == NULL) {
JNU_ThrowInternalError(env, "should not reach here");
return (jlong)-1;
}
/* EINTR not listed as a possible error */
dir = fdopendir((int)dfd);
dir = (*my_fdopendir_func)((int)dfd);
if (dir == NULL) {
throwUnixException(env, errno);
}
......
......@@ -1177,14 +1177,20 @@ class WindowsPath extends AbstractPath {
/*
* Windows treates symbolic links to directories differently than it
* does to other file types. For that reason we check if the exists and
* is a directory.
* does to other file types. For that reason we need to check if the
* target is a directory (or a directory junction).
*/
WindowsPath resolvedTarget;
if (target.type == WindowsPathType.RELATIVE) {
WindowsPath parent = getParent();
resolvedTarget = (parent == null) ? target : parent.resolve(target);
} else {
resolvedTarget = resolve(target);
}
int flags = 0;
WindowsPath resolvedTarget =
WindowsPath.createFromNormalizedPath(getFileSystem(), resolve(target).path);
try {
if (WindowsFileAttributes.get(resolvedTarget, true).isDirectory())
WindowsFileAttributes wattrs = WindowsFileAttributes.get(resolvedTarget, false);
if (wattrs.isDirectory() || wattrs.isDirectoryLink())
flags |= SYMBOLIC_LINK_FLAG_DIRECTORY;
} catch (WindowsException x) {
// unable to access target so assume target is not a directory
......
/*
* Copyright 2009 Sun Microsystems, Inc. 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/**
* @test
* @bug 6449574
* @summary Invalid ldap filter is accepted and processed
*/
import java.io.*;
import javax.naming.*;
import javax.naming.directory.*;
import java.util.Properties;
import java.util.Hashtable;
import java.net.Socket;
import java.net.ServerSocket;
public class BalancedParentheses {
// Should we run the client or server in a separate thread?
//
// Both sides can throw exceptions, but do you have a preference
// as to which side should be the main thread.
static boolean separateServerThread = true;
// use any free port by default
volatile int serverPort = 0;
// Is the server ready to serve?
volatile static boolean serverReady = false;
// Define the server side of the test.
//
// If the server prematurely exits, serverReady will be set to true
// to avoid infinite hangs.
void doServerSide() throws Exception {
ServerSocket serverSock = new ServerSocket(serverPort);
// signal client, it's ready to accecpt connection
serverPort = serverSock.getLocalPort();
serverReady = true;
// accept a connection
Socket socket = serverSock.accept();
System.out.println("Server: Connection accepted");
InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream();
// read the bindRequest
while (is.read() != -1) {
// ignore
is.skip(is.available());
break;
}
byte[] bindResponse = {0x30, 0x0C, 0x02, 0x01, 0x01, 0x61, 0x07, 0x0A,
0x01, 0x00, 0x04, 0x00, 0x04, 0x00};
// write bindResponse
os.write(bindResponse);
os.flush();
// ignore any more request.
while (is.read() != -1) {
// ignore
is.skip(is.available());
}
is.close();
os.close();
socket.close();
serverSock.close();
}
// Define the client side of the test.
//
// If the server prematurely exits, serverReady will be set to true
// to avoid infinite hangs.
void doClientSide() throws Exception {
// Wait for server to get started.
while (!serverReady) {
Thread.sleep(50);
}
// set up the environment for creating the initial context
Hashtable<Object, Object> env = new Hashtable<Object, Object>();
env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://localhost:" + serverPort);
env.put("com.sun.jndi.ldap.read.timeout", "1000");
// env.put(Context.SECURITY_AUTHENTICATION, "simple");
// env.put(Context.SECURITY_PRINCIPAL,"cn=root");
// env.put(Context.SECURITY_CREDENTIALS,"root");
// create initial context
DirContext context = new InitialDirContext(env);
// searching
SearchControls scs = new SearchControls();
scs.setSearchScope(SearchControls.SUBTREE_SCOPE);
try {
NamingEnumeration answer = context.search(
"o=sun,c=us", "(&(cn=Bob)))", scs);
} catch (InvalidSearchFilterException isfe) {
// ignore, it is the expected filter exception.
System.out.println("Expected exception: " + isfe.getMessage());
} catch (NamingException ne) {
// maybe a read timeout exception, as the server does not response.
throw new Exception("Expect a InvalidSearchFilterException", ne);
}
try {
NamingEnumeration answer = context.search(
"o=sun,c=us", ")(&(cn=Bob)", scs);
} catch (InvalidSearchFilterException isfe) {
// ignore, it is the expected filter exception.
System.out.println("Expected exception: " + isfe.getMessage());
} catch (NamingException ne) {
// maybe a read timeout exception, as the server does not response.
throw new Exception("Expect a InvalidSearchFilterException", ne);
}
try {
NamingEnumeration answer = context.search(
"o=sun,c=us", "(&(cn=Bob))", scs);
} catch (InvalidSearchFilterException isfe) {
// ignore, it is the expected filter exception.
throw new Exception("Unexpected ISFE", isfe);
} catch (NamingException ne) {
// maybe a read timeout exception, as the server does not response.
System.out.println("Expected exception: " + ne.getMessage());
}
context.close();
}
/*
* ============================================================
* The remainder is just support stuff
*/
// client and server thread
Thread clientThread = null;
Thread serverThread = null;
// client and server exceptions
volatile Exception serverException = null;
volatile Exception clientException = null;
void startServer(boolean newThread) throws Exception {
if (newThread) {
serverThread = new Thread() {
public void run() {
try {
doServerSide();
} catch (Exception e) {
/*
* Our server thread just died.
*
* Release the client, if not active already...
*/
System.err.println("Server died...");
System.err.println(e);
serverReady = true;
serverException = e;
}
}
};
serverThread.start();
} else {
doServerSide();
}
}
void startClient(boolean newThread) throws Exception {
if (newThread) {
clientThread = new Thread() {
public void run() {
try {
doClientSide();
} catch (Exception e) {
/*
* Our client thread just died.
*/
System.err.println("Client died...");
clientException = e;
}
}
};
clientThread.start();
} else {
doClientSide();
}
}
// Primary constructor, used to drive remainder of the test.
BalancedParentheses() throws Exception {
if (separateServerThread) {
startServer(true);
startClient(false);
} else {
startClient(true);
startServer(false);
}
/*
* Wait for other side to close down.
*/
if (separateServerThread) {
serverThread.join();
} else {
clientThread.join();
}
/*
* When we get here, the test is pretty much over.
*
* If the main thread excepted, that propagates back
* immediately. If the other thread threw an exception, we
* should report back.
*/
if (serverException != null) {
System.out.print("Server Exception:");
throw serverException;
}
if (clientException != null) {
System.out.print("Client Exception:");
throw clientException;
}
}
public static void main(String[] args) throws Exception {
// start the test
new BalancedParentheses();
}
}
......@@ -44,9 +44,9 @@ public class GroupOfOne {
final AsynchronousServerSocketChannel listener =
AsynchronousServerSocketChannel.open()
.bind(new InetSocketAddress(0));
listener.accept(null, new CompletionHandler<AsynchronousSocketChannel,Void>() {
listener.accept((Void)null, new CompletionHandler<AsynchronousSocketChannel,Void>() {
public void completed(AsynchronousSocketChannel ch, Void att) {
listener.accept(null, this);
listener.accept((Void)null, this);
}
public void failed(Throwable exc, Void att) {
}
......@@ -81,13 +81,13 @@ public class GroupOfOne {
// 2. the close/shutdown completes
final CountDownLatch latch = new CountDownLatch(2);
ch.connect(sa, null, new CompletionHandler<Void,Void>() {
ch.connect(sa, (Void)null, new CompletionHandler<Void,Void>() {
public void completed(Void result, Void att) {
System.out.println("Connected");
// initiate I/O operation that does not complete (successfully)
ByteBuffer buf = ByteBuffer.allocate(100);
ch.read(buf, null, new CompletionHandler<Integer,Void>() {
ch.read(buf, (Void)null, new CompletionHandler<Integer,Void>() {
public void completed(Integer bytesRead, Void att) {
throw new RuntimeException();
}
......
......@@ -78,15 +78,15 @@ public class Identity {
final AsynchronousServerSocketChannel listener =
AsynchronousServerSocketChannel.open()
.bind(new InetSocketAddress(0));
listener.accept(null, new CompletionHandler<AsynchronousSocketChannel,Void>() {
listener.accept((Void)null, new CompletionHandler<AsynchronousSocketChannel,Void>() {
public void completed(final AsynchronousSocketChannel ch, Void att) {
listener.accept(null, this);
listener.accept((Void)null, this);
final ByteBuffer buf = ByteBuffer.allocate(100);
ch.read(buf, null, new CompletionHandler<Integer,Void>() {
ch.read(buf, (Void)null, new CompletionHandler<Integer,Void>() {
public void completed(Integer bytesRead, Void att) {
buf.clear();
ch.read(buf, null, this);
ch.read(buf, (Void)null, this);
}
public void failed(Throwable exc, Void att) {
}
......
......@@ -94,7 +94,7 @@ public class Restart {
for (int i=0; i<count; i++) {
final CountDownLatch latch = new CountDownLatch(1);
listener.accept(null, new CompletionHandler<AsynchronousSocketChannel,Void>() {
listener.accept((Void)null, new CompletionHandler<AsynchronousSocketChannel,Void>() {
public void completed(AsynchronousSocketChannel ch, Void att) {
try {
ch.close();
......
......@@ -45,10 +45,10 @@ public class Unbounded {
final AsynchronousServerSocketChannel listener =
AsynchronousServerSocketChannel.open()
.bind(new InetSocketAddress(0));
listener.accept(null, new CompletionHandler<AsynchronousSocketChannel,Void>() {
listener.accept((Void)null, new CompletionHandler<AsynchronousSocketChannel,Void>() {
public void completed(AsynchronousSocketChannel ch, Void att) {
queue.add(ch);
listener.accept(null, this);
listener.accept((Void)null, this);
}
public void failed(Throwable exc, Void att) {
}
......
......@@ -66,7 +66,7 @@ public class Basic {
// Test: datagram packet not received immediately
dst.clear();
final CountDownLatch latch = new CountDownLatch(1);
ch.receive(dst, null, new CompletionHandler<SocketAddress,Void>() {
ch.receive(dst, (Void)null, new CompletionHandler<SocketAddress,Void>() {
public void completed(SocketAddress source, Void att) {
latch.countDown();
}
......@@ -82,7 +82,7 @@ public class Basic {
// Test: timeout
dst.clear();
final AtomicReference<Throwable> exception = new AtomicReference<Throwable>();
ch.receive(dst, 2, TimeUnit.SECONDS, null, new CompletionHandler<SocketAddress,Void>() {
ch.receive(dst, 2, TimeUnit.SECONDS, (Void)null, new CompletionHandler<SocketAddress,Void>() {
public void completed(SocketAddress source, Void att) {
}
public void failed (Throwable exc, Void att) {
......@@ -101,7 +101,7 @@ public class Basic {
// AsynchronousCloseException
dst = ByteBuffer.allocateDirect(100);
exception.set(null);
ch.receive(dst, null, new CompletionHandler<SocketAddress,Void>() {
ch.receive(dst, (Void)null, new CompletionHandler<SocketAddress,Void>() {
public void completed(SocketAddress source, Void att) {
}
public void failed (Throwable exc, Void att) {
......@@ -156,7 +156,7 @@ public class Basic {
// Test: datagram packet not received immediately
dst.clear();
final CountDownLatch l1 = new CountDownLatch(1);
ch.read(dst, null, new CompletionHandler<Integer,Void>() {
ch.read(dst, (Void)null, new CompletionHandler<Integer,Void>() {
public void completed(Integer bytesRead, Void att) {
l1.countDown();
}
......@@ -172,7 +172,7 @@ public class Basic {
// Test: timeout
dst.clear();
final AtomicReference<Throwable> exception = new AtomicReference<Throwable>();
ch.read(dst, 2, TimeUnit.SECONDS, null, new CompletionHandler<Integer,Void>() {
ch.read(dst, 2, TimeUnit.SECONDS, (Void)null, new CompletionHandler<Integer,Void>() {
public void completed(Integer bytesRead, Void att) {
}
public void failed (Throwable exc, Void att) {
......@@ -191,7 +191,7 @@ public class Basic {
// AsynchronousCloseException
dst.clear();
exception.set(null);
ch.read(dst, null, new CompletionHandler<Integer,Void>() {
ch.read(dst, (Void)null, new CompletionHandler<Integer,Void>() {
public void completed(Integer bytesRead, Void att) {
}
public void failed (Throwable exc, Void att) {
......@@ -238,7 +238,7 @@ public class Basic {
// Test: send datagram packet to reader and check completion handler
// is invoked
final CountDownLatch l2 = new CountDownLatch(1);
ch.send(ByteBuffer.wrap(msg), sa, null, new CompletionHandler<Integer,Void>() {
ch.send(ByteBuffer.wrap(msg), sa, (Void)null, new CompletionHandler<Integer,Void>() {
public void completed(Integer bytesSent, Void att) {
if (bytesSent != msg.length)
throw new RuntimeException("Unexpected number of bytes received");
......@@ -261,7 +261,7 @@ public class Basic {
// Test: check that failed method is invoked
ch.close();
final CountDownLatch l3 = new CountDownLatch(1);
ch.send(ByteBuffer.wrap(msg), sa, null, new CompletionHandler<Integer,Void>() {
ch.send(ByteBuffer.wrap(msg), sa, (Void)null, new CompletionHandler<Integer,Void>() {
public void completed(Integer bytesSent, Void att) {
throw new RuntimeException("completed method invoked");
}
......@@ -315,7 +315,7 @@ public class Basic {
// Test: write datagram and check completion handler is invoked
final CountDownLatch l2 = new CountDownLatch(1);
ch.write(ByteBuffer.wrap(msg), null, new CompletionHandler<Integer,Void>() {
ch.write(ByteBuffer.wrap(msg), (Void)null, new CompletionHandler<Integer,Void>() {
public void completed(Integer bytesSent, Void att) {
if (bytesSent != msg.length)
throw new RuntimeException("Unexpected number of bytes received");
......@@ -372,7 +372,7 @@ public class Basic {
final CountDownLatch latch = new CountDownLatch(1);
long timeout = (i == 0) ? 0L : 60L;
Future<SocketAddress> remote = ch
.receive(ByteBuffer.allocate(100), timeout, TimeUnit.SECONDS, null,
.receive(ByteBuffer.allocate(100), timeout, TimeUnit.SECONDS, (Void)null,
new CompletionHandler<SocketAddress,Void>() {
public void completed(SocketAddress source, Void att) {
}
......@@ -395,7 +395,7 @@ public class Basic {
final CountDownLatch latch = new CountDownLatch(1);
long timeout = (i == 0) ? 0L : 60L;
Future<Integer> result = ch
.read(ByteBuffer.allocate(100), timeout, TimeUnit.SECONDS, null,
.read(ByteBuffer.allocate(100), timeout, TimeUnit.SECONDS, (Void)null,
new CompletionHandler<Integer,Void>() {
public void completed(Integer bytesRead, Void att) {
}
......
......@@ -190,7 +190,7 @@ public class Basic {
if (fl == null)
throw new RuntimeException("Unable to acquire lock");
try {
ch.lock(null, new CompletionHandler<FileLock,Void> () {
ch.lock((Void)null, new CompletionHandler<FileLock,Void> () {
public void completed(FileLock result, Void att) {
}
public void failed(Throwable exc, Void att) {
......@@ -217,7 +217,7 @@ public class Basic {
ByteBuffer buf = ByteBuffer.allocateDirect(100);
final CountDownLatch latch = new CountDownLatch(1);
ch.read(buf, 0L, null, new CompletionHandler<Integer,Void>() {
ch.read(buf, 0L, (Void)null, new CompletionHandler<Integer,Void>() {
public void completed(Integer result, Void att) {
try {
Thread.currentThread().interrupt();
......@@ -311,7 +311,7 @@ public class Basic {
final AtomicReference<Thread> invoker = new AtomicReference<Thread>();
final CountDownLatch latch = new CountDownLatch(1);
ch.write(genBuffer(), 0L, null, new CompletionHandler<Integer,Void>() {
ch.write(genBuffer(), 0L, (Void)null, new CompletionHandler<Integer,Void>() {
public void completed(Integer result, Void att) {
invoker.set(Thread.currentThread());
latch.countDown();
......@@ -410,7 +410,7 @@ public class Basic {
// start write operation
final CountDownLatch latch = new CountDownLatch(1);
Future<Integer> res = ch.write(genBuffer(), 0L, null,
Future<Integer> res = ch.write(genBuffer(), 0L, (Void)null,
new CompletionHandler<Integer,Void>() {
public void completed(Integer result, Void att) {
}
......
......@@ -95,7 +95,7 @@ public class Basic {
final AtomicReference<Throwable> exception = new AtomicReference<Throwable>();
// start accepting
listener.accept(null, new CompletionHandler<AsynchronousSocketChannel,Void>() {
listener.accept((Void)null, new CompletionHandler<AsynchronousSocketChannel,Void>() {
public void completed(AsynchronousSocketChannel ch, Void att) {
try {
ch.close();
......
......@@ -181,7 +181,7 @@ public class Basic {
}
final AtomicReference<Throwable> connectException =
new AtomicReference<Throwable>();
ch.connect(server.address(), null, new CompletionHandler<Void,Void>() {
ch.connect(server.address(), (Void)null, new CompletionHandler<Void,Void>() {
public void completed(Void result, Void att) {
}
public void failed(Throwable exc, Void att) {
......@@ -332,7 +332,7 @@ public class Basic {
// start read operation
final CountDownLatch latch = new CountDownLatch(1);
ByteBuffer buf = ByteBuffer.allocate(1);
Future<Integer> res = ch.read(buf, null,
Future<Integer> res = ch.read(buf, (Void)null,
new CompletionHandler<Integer,Void>() {
public void completed(Integer result, Void att) {
}
......@@ -397,11 +397,11 @@ public class Basic {
// reads should complete immediately
final ByteBuffer dst = ByteBuffer.allocateDirect(src.capacity() + 100);
final CountDownLatch latch = new CountDownLatch(1);
ch.read(dst, null, new CompletionHandler<Integer,Void>() {
ch.read(dst, (Void)null, new CompletionHandler<Integer,Void>() {
public void completed(Integer result, Void att) {
int n = result;
if (n > 0) {
ch.read(dst, null, this);
ch.read(dst, (Void)null, this);
} else {
latch.countDown();
}
......@@ -450,10 +450,10 @@ public class Basic {
// read until the buffer is full
final ByteBuffer dst = ByteBuffer.allocateDirect(src.capacity());
final CountDownLatch latch = new CountDownLatch(1);
ch.read(dst, null, new CompletionHandler<Integer,Void>() {
ch.read(dst, (Void)null, new CompletionHandler<Integer,Void>() {
public void completed(Integer result, Void att) {
if (dst.hasRemaining()) {
ch.read(dst, null, this);
ch.read(dst, (Void)null, this);
} else {
latch.countDown();
}
......@@ -508,7 +508,7 @@ public class Basic {
// scattering read that completes ascynhronously
final CountDownLatch latch = new CountDownLatch(1);
ch.read(dsts, 0, dsts.length, 0L, TimeUnit.SECONDS, null,
ch.read(dsts, 0, dsts.length, 0L, TimeUnit.SECONDS, (Void)null,
new CompletionHandler<Long,Void>() {
public void completed(Long result, Void att) {
long n = result;
......@@ -536,7 +536,7 @@ public class Basic {
dsts[i].rewind();
}
long n = ch
.read(dsts, 0, dsts.length, 0L, TimeUnit.SECONDS, null, null).get();
.read(dsts, 0, dsts.length, 0L, TimeUnit.SECONDS, (Void)null, null).get();
if (n <= 0)
throw new RuntimeException("No bytes read");
......@@ -562,10 +562,10 @@ public class Basic {
// write all bytes and close connection when done
final ByteBuffer src = genBuffer();
ch.write(src, null, new CompletionHandler<Integer,Void>() {
ch.write(src, (Void)null, new CompletionHandler<Integer,Void>() {
public void completed(Integer result, Void att) {
if (src.hasRemaining()) {
ch.write(src, null, this);
ch.write(src, (Void)null, this);
} else {
try {
ch.close();
......@@ -616,7 +616,7 @@ public class Basic {
// write buffers (should complete immediately)
ByteBuffer[] srcs = genBuffers(1);
long n = ch
.write(srcs, 0, srcs.length, 0L, TimeUnit.SECONDS, null, null).get();
.write(srcs, 0, srcs.length, 0L, TimeUnit.SECONDS, (Void)null, null).get();
if (n <= 0)
throw new RuntimeException("No bytes written");
......@@ -629,7 +629,7 @@ public class Basic {
// write until socket buffer is full so as to create the conditions
// for when a write does not complete immediately
srcs = genBuffers(1);
ch.write(srcs, 0, srcs.length, 0L, TimeUnit.SECONDS, null,
ch.write(srcs, 0, srcs.length, 0L, TimeUnit.SECONDS, (Void)null,
new CompletionHandler<Long,Void>() {
public void completed(Long result, Void att) {
long n = result;
......@@ -639,7 +639,7 @@ public class Basic {
if (continueWriting.get()) {
ByteBuffer[] srcs = genBuffers(8);
ch.write(srcs, 0, srcs.length, 0L, TimeUnit.SECONDS,
null, this);
(Void)null, this);
}
}
public void failed(Throwable exc, Void att) {
......@@ -717,7 +717,7 @@ public class Basic {
// this read should timeout
ByteBuffer dst = ByteBuffer.allocate(512);
try {
ch.read(dst, 3, TimeUnit.SECONDS, null, null).get();
ch.read(dst, 3, TimeUnit.SECONDS, (Void)null, null).get();
throw new RuntimeException("Read did not timeout");
} catch (ExecutionException x) {
if (!(x.getCause() instanceof InterruptedByTimeoutException))
......
......@@ -99,7 +99,7 @@ public class StressLoopback {
void start() {
sentBuffer.position(0);
sentBuffer.limit(sentBuffer.capacity());
channel.write(sentBuffer, null, new CompletionHandler<Integer,Void> () {
channel.write(sentBuffer, (Void)null, new CompletionHandler<Integer,Void> () {
public void completed(Integer nwrote, Void att) {
bytesSent += nwrote;
if (finished) {
......@@ -107,7 +107,7 @@ public class StressLoopback {
} else {
sentBuffer.position(0);
sentBuffer.limit(sentBuffer.capacity());
channel.write(sentBuffer, null, this);
channel.write(sentBuffer, (Void)null, this);
}
}
public void failed(Throwable exc, Void att) {
......@@ -142,14 +142,14 @@ public class StressLoopback {
}
void start() {
channel.read(readBuffer, null, new CompletionHandler<Integer,Void> () {
channel.read(readBuffer, (Void)null, new CompletionHandler<Integer,Void> () {
public void completed(Integer nread, Void att) {
if (nread < 0) {
closeUnchecked(channel);
} else {
bytesRead += nread;
readBuffer.clear();
channel.read(readBuffer, null, this);
channel.read(readBuffer, (Void)null, this);
}
}
public void failed(Throwable exc, Void att) {
......
......@@ -22,7 +22,7 @@
*/
/* @test
* @bug 4313887 6838333
* @bug 4313887 6838333 6863864
* @summary Unit test for java.nio.file.Path createSymbolicLink,
* readSymbolicLink, and createLink methods
* @library ..
......@@ -31,7 +31,6 @@
import java.nio.file.*;
import java.nio.file.attribute.*;
import java.io.*;
import java.util.*;
public class Links {
......@@ -47,7 +46,7 @@ public class Links {
* Exercise createSymbolicLink and readLink methods
*/
static void testSymLinks(Path dir) throws IOException {
Path link = dir.resolve("link");
final Path link = dir.resolve("link");
// Check if sym links are supported
try {
......@@ -76,6 +75,63 @@ public class Links {
link.delete();
}
}
// Test links to directory
Path mydir = dir.resolve("mydir");
Path myfile = mydir.resolve("myfile");
try {
mydir.createDirectory();
myfile.createFile();
// link -> "mydir"
link.createSymbolicLink(mydir.getName());
assertTrue(link.readSymbolicLink().equals(mydir.getName()));
// Test access to directory via link
DirectoryStream<Path> stream = link.newDirectoryStream();
try {
boolean found = false;
for (Path entry: stream) {
if (entry.getName().equals(myfile.getName())) {
found = true;
break;
}
}
assertTrue(found);
} finally {
stream.close();
}
// Test link2 -> link -> mydir
final Path link2 = dir.resolve("link2");
Path target2 = link.getName();
link2.createSymbolicLink(target2);
try {
assertTrue(link2.readSymbolicLink().equals(target2));
link2.newDirectoryStream().close();
} finally {
link2.delete();
}
// Remove mydir and re-create link2 before re-creating mydir
// (This is a useful test on Windows to ensure that creating a
// sym link to a directory sym link creates the right type of link).
myfile.delete();
mydir.delete();
link2.createSymbolicLink(target2);
try {
assertTrue(link2.readSymbolicLink().equals(target2));
mydir.createDirectory();
link2.newDirectoryStream().close();
} finally {
link2.delete();
}
} finally {
myfile.deleteIfExists();
mydir.deleteIfExists();
link.deleteIfExists();
}
}
/**
......
......@@ -426,6 +426,36 @@ public class MOAT {
q.poll();
equal(q.size(), 4);
checkFunctionalInvariants(q);
if ((q instanceof LinkedBlockingQueue) ||
(q instanceof LinkedBlockingDeque) ||
(q instanceof ConcurrentLinkedQueue)) {
testQueueIteratorRemove(q);
}
}
private static void testQueueIteratorRemove(Queue<Integer> q) {
System.err.printf("testQueueIteratorRemove %s%n",
q.getClass().getSimpleName());
q.clear();
for (int i = 0; i < 5; i++)
q.add(i);
Iterator<Integer> it = q.iterator();
check(it.hasNext());
for (int i = 3; i >= 0; i--)
q.remove(i);
equal(it.next(), 0);
equal(it.next(), 4);
q.clear();
for (int i = 0; i < 5; i++)
q.add(i);
it = q.iterator();
equal(it.next(), 0);
check(it.hasNext());
for (int i = 1; i < 4; i++)
q.remove(i);
equal(it.next(), 1);
equal(it.next(), 4);
}
private static void testList(final List<Integer> l) {
......@@ -451,6 +481,11 @@ public class MOAT {
}
private static void testCollection(Collection<Integer> c) {
try { testCollection1(c); }
catch (Throwable t) { unexpected(t); }
}
private static void testCollection1(Collection<Integer> c) {
System.out.println("\n==> " + c.getClass().getName());
......
/*
* 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
*/
/*
* @test
* @bug 6805775 6815766
* @summary Test concurrent offer vs. drainTo
*/
import java.util.*;
import java.util.concurrent.*;
@SuppressWarnings({"unchecked", "rawtypes"})
public class OfferDrainToLoops {
void checkNotContainsNull(Iterable it) {
for (Object x : it)
check(x != null);
}
abstract class CheckedThread extends Thread {
abstract protected void realRun();
public void run() {
try { realRun(); } catch (Throwable t) { unexpected(t); }
}
{
setDaemon(true);
start();
}
}
void test(String[] args) throws Throwable {
test(new LinkedBlockingQueue());
test(new LinkedBlockingQueue(2000));
test(new LinkedBlockingDeque());
test(new LinkedBlockingDeque(2000));
test(new ArrayBlockingQueue(2000));
}
void test(final BlockingQueue q) throws Throwable {
System.out.println(q.getClass().getSimpleName());
final long testDurationSeconds = 1L;
final long testDurationMillis = testDurationSeconds * 1000L;
final long quittingTimeNanos
= System.nanoTime() + testDurationSeconds * 1000L * 1000L * 1000L;
Thread offerer = new CheckedThread() {
protected void realRun() {
for (long i = 0; ; i++) {
if ((i % 1024) == 0 &&
System.nanoTime() - quittingTimeNanos > 0)
break;
while (! q.offer(i))
Thread.yield();
}}};
Thread drainer = new CheckedThread() {
protected void realRun() {
for (long i = 0; ; i++) {
if (System.nanoTime() - quittingTimeNanos > 0)
break;
List list = new ArrayList();
int n = q.drainTo(list);
equal(list.size(), n);
for (int j = 0; j < n - 1; j++)
equal((Long) list.get(j) + 1L, list.get(j + 1));
Thread.yield();
}}};
Thread scanner = new CheckedThread() {
protected void realRun() {
for (long i = 0; ; i++) {
if (System.nanoTime() - quittingTimeNanos > 0)
break;
checkNotContainsNull(q);
Thread.yield();
}}};
offerer.join(10 * testDurationMillis);
drainer.join(10 * testDurationMillis);
check(! offerer.isAlive());
check(! drainer.isAlive());
}
//--------------------- Infrastructure ---------------------------
volatile int passed = 0, failed = 0;
void pass() {passed++;}
void fail() {failed++; Thread.dumpStack();}
void fail(String msg) {System.err.println(msg); fail();}
void unexpected(Throwable t) {failed++; t.printStackTrace();}
void check(boolean cond) {if (cond) pass(); else fail();}
void equal(Object x, Object y) {
if (x == null ? y == null : x.equals(y)) pass();
else fail(x + " not equal to " + y);}
public static void main(String[] args) throws Throwable {
new OfferDrainToLoops().instanceMain(args);}
public void instanceMain(String[] args) throws Throwable {
try {test(args);} catch (Throwable t) {unexpected(t);}
System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed);
if (failed > 0) throw new AssertionError("Some tests failed");}
}
......@@ -33,9 +33,8 @@
/*
* @test
* @bug 4486658
* @compile -source 1.5 ConcurrentQueueLoops.java
* @run main/timeout=230 ConcurrentQueueLoops
* @bug 4486658 6785442
* @run main ConcurrentQueueLoops 8 123456
* @summary Checks that a set of threads can repeatedly get and modify items
*/
......@@ -44,34 +43,75 @@ import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
public class ConcurrentQueueLoops {
static final ExecutorService pool = Executors.newCachedThreadPool();
static AtomicInteger totalItems;
static boolean print = false;
ExecutorService pool;
AtomicInteger totalItems;
boolean print;
public static void main(String[] args) throws Exception {
int maxStages = 8;
int items = 100000;
// Suitable for benchmarking. Overriden by args[0] for testing.
int maxStages = 20;
// Suitable for benchmarking. Overriden by args[1] for testing.
int items = 1024 * 1024;
Collection<Queue<Integer>> concurrentQueues() {
List<Queue<Integer>> queues = new ArrayList<Queue<Integer>>();
queues.add(new ConcurrentLinkedQueue<Integer>());
queues.add(new ArrayBlockingQueue<Integer>(items, false));
//queues.add(new ArrayBlockingQueue<Integer>(count, true));
queues.add(new LinkedBlockingQueue<Integer>());
queues.add(new LinkedBlockingDeque<Integer>());
try {
queues.add((Queue<Integer>)
Class.forName("java.util.concurrent.LinkedTransferQueue")
.newInstance());
} catch (IllegalAccessException e) {
} catch (InstantiationException e) {
} catch (ClassNotFoundException e) {
// OK; not yet added to JDK
}
// Following additional implementations are available from:
// http://gee.cs.oswego.edu/dl/concurrency-interest/index.html
// queues.add(new LinkedTransferQueue<Integer>());
// queues.add(new SynchronizedLinkedListQueue<Integer>());
// Avoid "first fast, second slow" benchmark effect.
Collections.shuffle(queues);
return queues;
}
void test(String[] args) throws Throwable {
if (args.length > 0)
maxStages = Integer.parseInt(args[0]);
if (args.length > 1)
items = Integer.parseInt(args[1]);
for (Queue<Integer> queue : concurrentQueues())
test(queue);
}
void test(final Queue<Integer> q) throws Throwable {
System.out.println(q.getClass().getSimpleName());
pool = Executors.newCachedThreadPool();
print = false;
print = false;
System.out.println("Warmup...");
oneRun(1, items);
Thread.sleep(100);
oneRun(1, items);
oneRun(1, items, q);
//Thread.sleep(100);
oneRun(3, items, q);
Thread.sleep(100);
print = true;
for (int i = 1; i <= maxStages; i += (i+1) >>> 1) {
oneRun(i, items);
oneRun(i, items, q);
}
pool.shutdown();
if (! pool.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS))
throw new Error();
check(pool.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS));
}
static class Stage implements Callable<Integer> {
class Stage implements Callable<Integer> {
final Queue<Integer> queue;
final CyclicBarrier barrier;
int items;
......@@ -110,15 +150,11 @@ public class ConcurrentQueueLoops {
}
return new Integer(l);
}
catch (Exception ie) {
ie.printStackTrace();
throw new Error("Call loop failed");
}
catch (Throwable t) { unexpected(t); return null; }
}
}
static void oneRun(int n, int items) throws Exception {
Queue<Integer> q = new ConcurrentLinkedQueue<Integer>();
void oneRun(int n, int items, final Queue<Integer> q) throws Exception {
LoopHelpers.BarrierTimer timer = new LoopHelpers.BarrierTimer();
CyclicBarrier barrier = new CyclicBarrier(n + 1, timer);
totalItems = new AtomicInteger(n * items);
......@@ -141,6 +177,22 @@ public class ConcurrentQueueLoops {
System.out.println(LoopHelpers.rightJustify(time / (items * n)) + " ns per item");
if (total == 0) // avoid overoptimization
System.out.println("useless result: " + total);
}
//--------------------- Infrastructure ---------------------------
volatile int passed = 0, failed = 0;
void pass() {passed++;}
void fail() {failed++; Thread.dumpStack();}
void fail(String msg) {System.err.println(msg); fail();}
void unexpected(Throwable t) {failed++; t.printStackTrace();}
void check(boolean cond) {if (cond) pass(); else fail();}
void equal(Object x, Object y) {
if (x == null ? y == null : x.equals(y)) pass();
else fail(x + " not equal to " + y);}
public static void main(String[] args) throws Throwable {
new ConcurrentQueueLoops().instanceMain(args);}
public void instanceMain(String[] args) throws Throwable {
try {test(args);} catch (Throwable t) {unexpected(t);}
System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed);
if (failed > 0) throw new AssertionError("Some tests failed");}
}
/*
* 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
*/
/*
* @test
* @bug 6785442
* @summary Benchmark that tries to GC-tenure head, followed by
* many add/remove operations.
* @run main GCRetention 12345
*/
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Queue;
import java.util.Map;
public class GCRetention {
// Suitable for benchmarking. Overriden by args[0] for testing.
int count = 1024 * 1024;
final Map<String,String> results = new ConcurrentHashMap<String,String>();
Collection<Queue<Boolean>> queues() {
List<Queue<Boolean>> queues = new ArrayList<Queue<Boolean>>();
queues.add(new ConcurrentLinkedQueue<Boolean>());
queues.add(new ArrayBlockingQueue<Boolean>(count, false));
queues.add(new ArrayBlockingQueue<Boolean>(count, true));
queues.add(new LinkedBlockingQueue<Boolean>());
queues.add(new LinkedBlockingDeque<Boolean>());
queues.add(new PriorityBlockingQueue<Boolean>());
queues.add(new PriorityQueue<Boolean>());
queues.add(new LinkedList<Boolean>());
try {
queues.add((Queue<Boolean>)
Class.forName("java.util.concurrent.LinkedTransferQueue")
.newInstance());
} catch (IllegalAccessException e) {
} catch (InstantiationException e) {
} catch (ClassNotFoundException e) {
// OK; not yet added to JDK
}
// Following additional implementations are available from:
// http://gee.cs.oswego.edu/dl/concurrency-interest/index.html
// queues.add(new LinkedTransferQueue<Boolean>());
// queues.add(new SynchronizedLinkedListQueue<Boolean>());
// Avoid "first fast, second slow" benchmark effect.
Collections.shuffle(queues);
return queues;
}
void prettyPrintResults() {
List<String> classNames = new ArrayList<String>(results.keySet());
Collections.sort(classNames);
int maxClassNameLength = 0;
int maxNanosLength = 0;
for (String name : classNames) {
if (maxClassNameLength < name.length())
maxClassNameLength = name.length();
if (maxNanosLength < results.get(name).length())
maxNanosLength = results.get(name).length();
}
String format = String.format("%%%ds %%%ds nanos/item%%n",
maxClassNameLength, maxNanosLength);
for (String name : classNames)
System.out.printf(format, name, results.get(name));
}
void test(String[] args) {
if (args.length > 0)
count = Integer.valueOf(args[0]);
// Warmup
for (Queue<Boolean> queue : queues())
test(queue);
results.clear();
for (Queue<Boolean> queue : queues())
test(queue);
prettyPrintResults();
}
void test(Queue<Boolean> q) {
long t0 = System.nanoTime();
for (int i = 0; i < count; i++)
check(q.add(Boolean.TRUE));
System.gc();
System.gc();
Boolean x;
while ((x = q.poll()) != null)
equal(x, Boolean.TRUE);
check(q.isEmpty());
for (int i = 0; i < 10 * count; i++) {
for (int k = 0; k < 3; k++)
check(q.add(Boolean.TRUE));
for (int k = 0; k < 3; k++)
if (q.poll() != Boolean.TRUE)
fail();
}
check(q.isEmpty());
String className = q.getClass().getSimpleName();
long elapsed = System.nanoTime() - t0;
int nanos = (int) ((double) elapsed / (10 * 3 * count));
results.put(className, String.valueOf(nanos));
}
//--------------------- Infrastructure ---------------------------
volatile int passed = 0, failed = 0;
void pass() {passed++;}
void fail() {failed++; Thread.dumpStack();}
void fail(String msg) {System.err.println(msg); fail();}
void unexpected(Throwable t) {failed++; t.printStackTrace();}
void check(boolean cond) {if (cond) pass(); else fail();}
void equal(Object x, Object y) {
if (x == null ? y == null : x.equals(y)) pass();
else fail(x + " not equal to " + y);}
public static void main(String[] args) throws Throwable {
new GCRetention().instanceMain(args);}
public void instanceMain(String[] args) throws Throwable {
try {test(args);} catch (Throwable t) {unexpected(t);}
System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed);
if (failed > 0) throw new AssertionError("Some tests failed");}
}
/*
* 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
*/
import java.util.*;
import java.util.concurrent.*;
/*
* @test
* @bug 6805775 6815766
* @summary Check weak consistency of concurrent queue iterators
*/
@SuppressWarnings({"unchecked", "rawtypes"})
public class IteratorWeakConsistency {
void test(String[] args) throws Throwable {
test(new LinkedBlockingQueue());
test(new LinkedBlockingQueue(20));
test(new LinkedBlockingDeque());
test(new LinkedBlockingDeque(20));
test(new ConcurrentLinkedQueue());
// Other concurrent queues (e.g. ArrayBlockingQueue) do not
// currently have weakly consistent iterators.
// test(new ArrayBlockingQueue(20));
}
void test(Queue q) throws Throwable {
// TODO: make this more general
for (int i = 0; i < 10; i++)
q.add(i);
Iterator it = q.iterator();
q.poll();
q.poll();
q.poll();
q.remove(7);
List list = new ArrayList();
while (it.hasNext())
list.add(it.next());
equal(list, Arrays.asList(0, 3, 4, 5, 6, 8, 9));
check(! list.contains(null));
System.out.printf("%s: %s%n",
q.getClass().getSimpleName(),
list);
}
//--------------------- Infrastructure ---------------------------
volatile int passed = 0, failed = 0;
void pass() {passed++;}
void fail() {failed++; Thread.dumpStack();}
void fail(String msg) {System.err.println(msg); fail();}
void unexpected(Throwable t) {failed++; t.printStackTrace();}
void check(boolean cond) {if (cond) pass(); else fail();}
void equal(Object x, Object y) {
if (x == null ? y == null : x.equals(y)) pass();
else fail(x + " not equal to " + y);}
static Class<?> thisClass = new Object(){}.getClass().getEnclosingClass();
public static void main(String[] args) throws Throwable {
new IteratorWeakConsistency().instanceMain(args);}
public void instanceMain(String[] args) throws Throwable {
try {test(args);} catch (Throwable t) {unexpected(t);}
System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed);
if (failed > 0) throw new AssertionError("Some tests failed");}
}
/*
* 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
*/
/*
* @test
* @bug 6785442
* @summary Checks race between poll and remove(Object), while
* occasionally moonlighting as a microbenchmark.
* @run main RemovePollRace 12345
*/
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicLong;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Queue;
import java.util.Map;
public class RemovePollRace {
// Suitable for benchmarking. Overriden by args[0] for testing.
int count = 1024 * 1024;
final Map<String,String> results = new ConcurrentHashMap<String,String>();
Collection<Queue<Boolean>> concurrentQueues() {
List<Queue<Boolean>> queues = new ArrayList<Queue<Boolean>>();
queues.add(new ConcurrentLinkedQueue<Boolean>());
queues.add(new ArrayBlockingQueue<Boolean>(count, false));
queues.add(new ArrayBlockingQueue<Boolean>(count, true));
queues.add(new LinkedBlockingQueue<Boolean>());
queues.add(new LinkedBlockingDeque<Boolean>());
try {
queues.add((Queue<Boolean>)
Class.forName("java.util.concurrent.LinkedTransferQueue")
.newInstance());
} catch (IllegalAccessException e) {
} catch (InstantiationException e) {
} catch (ClassNotFoundException e) {
// OK; not yet added to JDK
}
// Following additional implementations are available from:
// http://gee.cs.oswego.edu/dl/concurrency-interest/index.html
// queues.add(new LinkedTransferQueue<Boolean>());
// queues.add(new SynchronizedLinkedListQueue<Boolean>());
// Avoid "first fast, second slow" benchmark effect.
Collections.shuffle(queues);
return queues;
}
void prettyPrintResults() {
List<String> classNames = new ArrayList<String>(results.keySet());
Collections.sort(classNames);
int maxClassNameLength = 0;
int maxNanosLength = 0;
for (String name : classNames) {
if (maxClassNameLength < name.length())
maxClassNameLength = name.length();
if (maxNanosLength < results.get(name).length())
maxNanosLength = results.get(name).length();
}
String format = String.format("%%%ds %%%ds nanos/item%%n",
maxClassNameLength, maxNanosLength);
for (String name : classNames)
System.out.printf(format, name, results.get(name));
}
void test(String[] args) throws Throwable {
if (args.length > 0)
count = Integer.valueOf(args[0]);
// Warmup
for (Queue<Boolean> queue : concurrentQueues())
test(queue);
results.clear();
for (Queue<Boolean> queue : concurrentQueues())
test(queue);
prettyPrintResults();
}
void await(CountDownLatch latch) {
try { latch.await(); }
catch (InterruptedException e) { unexpected(e); }
}
void test(final Queue<Boolean> q) throws Throwable {
long t0 = System.nanoTime();
final int SPINS = 5;
final AtomicLong removes = new AtomicLong(0);
final AtomicLong polls = new AtomicLong(0);
final int adderCount =
Math.max(1, Runtime.getRuntime().availableProcessors() / 4);
final int removerCount =
Math.max(1, Runtime.getRuntime().availableProcessors() / 4);
final int pollerCount = removerCount;
final int threadCount = adderCount + removerCount + pollerCount;
final CountDownLatch startingGate = new CountDownLatch(1);
final CountDownLatch addersDone = new CountDownLatch(adderCount);
final Runnable remover = new Runnable() {
public void run() {
await(startingGate);
int spins = 0;
for (;;) {
boolean quittingTime = (addersDone.getCount() == 0);
if (q.remove(Boolean.TRUE))
removes.getAndIncrement();
else if (quittingTime)
break;
else if (++spins > SPINS) {
Thread.yield();
spins = 0;
}}}};
final Runnable poller = new Runnable() {
public void run() {
await(startingGate);
int spins = 0;
for (;;) {
boolean quittingTime = (addersDone.getCount() == 0);
if (q.poll() == Boolean.TRUE)
polls.getAndIncrement();
else if (quittingTime)
break;
else if (++spins > SPINS) {
Thread.yield();
spins = 0;
}}}};
final Runnable adder = new Runnable() {
public void run() {
await(startingGate);
for (int i = 0; i < count; i++) {
for (;;) {
try { q.add(Boolean.TRUE); break; }
catch (IllegalStateException e) { Thread.yield(); }
}
}
addersDone.countDown();
}};
final List<Thread> adders = new ArrayList<Thread>();
final List<Thread> removers = new ArrayList<Thread>();
final List<Thread> pollers = new ArrayList<Thread>();
for (int i = 0; i < adderCount; i++)
adders.add(checkedThread(adder));
for (int i = 0; i < removerCount; i++)
removers.add(checkedThread(remover));
for (int i = 0; i < pollerCount; i++)
pollers.add(checkedThread(poller));
final List<Thread> allThreads = new ArrayList<Thread>();
allThreads.addAll(removers);
allThreads.addAll(pollers);
allThreads.addAll(adders);
for (Thread t : allThreads)
t.start();
startingGate.countDown();
for (Thread t : allThreads)
t.join();
String className = q.getClass().getSimpleName();
long elapsed = System.nanoTime() - t0;
int nanos = (int) ((double) elapsed / (adderCount * count));
results.put(className, String.valueOf(nanos));
if (removes.get() + polls.get() != adderCount * count) {
String msg = String.format
("class=%s removes=%s polls=%d count=%d",
className, removes.get(), polls.get(), count);
fail(msg);
}
}
//--------------------- Infrastructure ---------------------------
volatile int passed = 0, failed = 0;
void pass() {passed++;}
void fail() {failed++; Thread.dumpStack();}
void fail(String msg) {System.err.println(msg); fail();}
void unexpected(Throwable t) {failed++; t.printStackTrace();}
void check(boolean cond) {if (cond) pass(); else fail();}
void equal(Object x, Object y) {
if (x == null ? y == null : x.equals(y)) pass();
else fail(x + " not equal to " + y);}
public static void main(String[] args) throws Throwable {
new RemovePollRace().instanceMain(args);}
public void instanceMain(String[] args) throws Throwable {
try {test(args);} catch (Throwable t) {unexpected(t);}
System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed);
if (failed > 0) throw new AssertionError("Some tests failed");}
Thread checkedThread(final Runnable r) {
return new Thread() {public void run() {
try {r.run();} catch (Throwable t) {unexpected(t);}}};}
}
......@@ -28,62 +28,74 @@
* @author Martin Buchholz
*/
import java.util.*;
import java.util.concurrent.*;
public class OfferRemoveLoops {
private static void realMain(String[] args) throws Throwable {
void test(String[] args) throws Throwable {
testQueue(new LinkedBlockingQueue<String>(10));
testQueue(new LinkedBlockingQueue<String>());
testQueue(new LinkedBlockingDeque<String>(10));
testQueue(new LinkedBlockingDeque<String>());
testQueue(new ArrayBlockingQueue<String>(10));
testQueue(new PriorityBlockingQueue<String>(10));
testQueue(new ConcurrentLinkedQueue<String>());
}
private abstract static class ControlledThread extends Thread {
abstract class CheckedThread extends Thread {
abstract protected void realRun();
public void run() {
try { realRun(); } catch (Throwable t) { unexpected(t); }
}
}
private static void testQueue(final BlockingQueue<String> q) throws Throwable {
System.out.println(q.getClass());
final int count = 10000;
final long quittingTime = System.nanoTime() + 1L * 1000L * 1000L * 1000L;
Thread t1 = new ControlledThread() {
protected void realRun() {
for (int i = 0, j = 0; i < count; i++)
while (! q.remove(String.valueOf(i))
&& System.nanoTime() - quittingTime < 0)
Thread.yield();}};
Thread t2 = new ControlledThread() {
protected void realRun() {
for (int i = 0, j = 0; i < count; i++)
while (! q.offer(String.valueOf(i))
&& System.nanoTime() - quittingTime < 0)
Thread.yield();}};
void testQueue(final Queue<String> q) throws Throwable {
System.out.println(q.getClass().getSimpleName());
final int count = 1000 * 1000;
final long testDurationSeconds = 1L;
final long testDurationMillis = testDurationSeconds * 1000L;
final long quittingTimeNanos
= System.nanoTime() + testDurationSeconds * 1000L * 1000L * 1000L;
Thread t1 = new CheckedThread() {
protected void realRun() {
for (int i = 0; i < count; i++) {
if ((i % 1024) == 0 &&
System.nanoTime() - quittingTimeNanos > 0)
return;
while (! q.remove(String.valueOf(i)))
Thread.yield();
}}};
Thread t2 = new CheckedThread() {
protected void realRun() {
for (int i = 0; i < count; i++) {
if ((i % 1024) == 0 &&
System.nanoTime() - quittingTimeNanos > 0)
return;
while (! q.offer(String.valueOf(i)))
Thread.yield();
}}};
t1.setDaemon(true); t2.setDaemon(true);
t1.start(); t2.start();
t1.join(10000); t2.join(10000);
t1.join(10 * testDurationMillis);
t2.join(10 * testDurationMillis);
check(! t1.isAlive());
check(! t2.isAlive());
}
//--------------------- Infrastructure ---------------------------
static volatile int passed = 0, failed = 0;
static void pass() { passed++; }
static void fail() { failed++; Thread.dumpStack(); }
static void unexpected(Throwable t) { failed++; t.printStackTrace(); }
static void check(boolean cond) { if (cond) pass(); else fail(); }
static void equal(Object x, Object y) {
volatile int passed = 0, failed = 0;
void pass() {passed++;}
void fail() {failed++; Thread.dumpStack();}
void fail(String msg) {System.err.println(msg); fail();}
void unexpected(Throwable t) {failed++; t.printStackTrace();}
void check(boolean cond) {if (cond) pass(); else fail();}
void equal(Object x, Object y) {
if (x == null ? y == null : x.equals(y)) pass();
else {System.out.println(x + " not equal to " + y); fail(); }}
else fail(x + " not equal to " + y);}
public static void main(String[] args) throws Throwable {
try { realMain(args); } catch (Throwable t) { unexpected(t); }
new OfferRemoveLoops().instanceMain(args);}
public void instanceMain(String[] args) throws Throwable {
try {test(args);} catch (Throwable t) {unexpected(t);}
System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed);
if (failed > 0) throw new Exception("Some tests failed");
}
if (failed > 0) throw new AssertionError("Some tests failed");}
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册