提交 fc0ce92d 编写于 作者: R redestad

8145680: Remove unnecessary explicit initialization of volatile variables in java.base

Reviewed-by: alanb, chegar, jfranck, shade
上级 4cf275a1
......@@ -29,7 +29,6 @@ import java.io.IOException;
import java.nio.channels.*;
import java.nio.channels.spi.*;
import java.util.*;
import sun.misc.*;
/**
* An implementation of Selector for Linux 2.6+ kernels that uses
......@@ -50,7 +49,7 @@ class EPollSelectorImpl
private Map<Integer,SelectionKeyImpl> fdToKey;
// True if this Selector has been closed
private volatile boolean closed = false;
private volatile boolean closed;
// Lock for interrupt triggering and clearing
private final Object interruptLock = new Object();
......
......@@ -93,7 +93,7 @@ public final class SunJCE extends Provider {
// Instance of this provider, so we don't have to call the provider list
// to find ourselves or run the risk of not being in the list.
private static volatile SunJCE instance = null;
private static volatile SunJCE instance;
// lazy initialize SecureRandom to avoid potential recursion if Sun
// provider has not been installed yet
......
......@@ -48,9 +48,9 @@ package java.io;
* @since 1.0
*/
public class PipedInputStream extends InputStream {
boolean closedByWriter = false;
volatile boolean closedByReader = false;
boolean connected = false;
boolean closedByWriter;
volatile boolean closedByReader;
boolean connected;
/* REMIND: identification of the read and write sides needs to be
more sophisticated. Either using thread groups (but what about
......
......@@ -2518,7 +2518,7 @@ public final class Class<T> implements java.io.Serializable,
// Incremented by the VM on each call to JVM TI RedefineClasses()
// that redefines this class or a superclass.
private transient volatile int classRedefinedCount = 0;
private transient volatile int classRedefinedCount;
// Lazily create and cache ReflectionData
private ReflectionData<T> reflectionData() {
......@@ -3331,7 +3331,8 @@ public final class Class<T> implements java.io.Serializable,
* uncloned, cached, and shared by all callers.
*/
T[] getEnumConstantsShared() {
if (enumConstants == null) {
T[] constants = enumConstants;
if (constants == null) {
if (!isEnum()) return null;
try {
final Method values = getMethod("values");
......@@ -3344,16 +3345,16 @@ public final class Class<T> implements java.io.Serializable,
});
@SuppressWarnings("unchecked")
T[] temporaryConstants = (T[])values.invoke(null);
enumConstants = temporaryConstants;
enumConstants = constants = temporaryConstants;
}
// These can happen when users concoct enum-like classes
// that don't comply with the enum spec.
catch (InvocationTargetException | NoSuchMethodException |
IllegalAccessException ex) { return null; }
}
return enumConstants;
return constants;
}
private transient volatile T[] enumConstants = null;
private transient volatile T[] enumConstants;
/**
* Returns a map from simple name to enum constant. This package-private
......@@ -3363,19 +3364,21 @@ public final class Class<T> implements java.io.Serializable,
* created lazily on first use. Typically it won't ever get created.
*/
Map<String, T> enumConstantDirectory() {
if (enumConstantDirectory == null) {
Map<String, T> directory = enumConstantDirectory;
if (directory == null) {
T[] universe = getEnumConstantsShared();
if (universe == null)
throw new IllegalArgumentException(
getName() + " is not an enum type");
Map<String, T> m = new HashMap<>(2 * universe.length);
for (T constant : universe)
m.put(((Enum<?>)constant).name(), constant);
enumConstantDirectory = m;
directory = new HashMap<>(2 * universe.length);
for (T constant : universe) {
directory.put(((Enum<?>)constant).name(), constant);
}
enumConstantDirectory = directory;
}
return enumConstantDirectory;
return directory;
}
private transient volatile Map<String, T> enumConstantDirectory = null;
private transient volatile Map<String, T> enumConstantDirectory;
/**
* Casts an object to the class or interface represented
......
......@@ -132,7 +132,7 @@ public final class System {
/* The security manager for the system.
*/
private static volatile SecurityManager security = null;
private static volatile SecurityManager security;
/**
* Reassigns the "standard" input stream.
......@@ -206,7 +206,7 @@ public final class System {
setErr0(err);
}
private static volatile Console cons = null;
private static volatile Console cons;
/**
* Returns the unique {@link java.io.Console Console} object associated
* with the current Java virtual machine, if any.
......@@ -216,12 +216,13 @@ public final class System {
* @since 1.6
*/
public static Console console() {
if (cons == null) {
Console c = cons;
if (c == null) {
synchronized (System.class) {
cons = SharedSecrets.getJavaIOAccess().console();
cons = c = SharedSecrets.getJavaIOAccess().console();
}
}
return cons;
return c;
}
/**
......
......@@ -207,12 +207,10 @@ class Thread implements Runnable {
/* For generating thread ID */
private static long threadSeqNumber;
/* Java thread status for tools,
* initialized to indicate thread 'not yet started'
/*
* Java thread status for tools, default indicates thread 'not yet started'
*/
private volatile int threadStatus = 0;
private volatile int threadStatus;
private static synchronized long nextThreadID() {
return ++threadSeqNumber;
......
......@@ -53,7 +53,7 @@ public class ReferenceQueue<T> {
private static class Lock { };
private Lock lock = new Lock();
private volatile Reference<? extends T> head = null;
private volatile Reference<? extends T> head;
private long queueLength = 0;
boolean enqueue(Reference<? extends T> r) { /* Called only by Reference class */
......
......@@ -205,7 +205,7 @@ public final class Parameter implements AnnotatedElement {
return tmp;
}
private transient volatile Type parameterTypeCache = null;
private transient volatile Type parameterTypeCache;
/**
* Returns a {@code Class} object that identifies the
......@@ -237,7 +237,7 @@ public final class Parameter implements AnnotatedElement {
return executable.getAnnotatedParameterTypes()[index];
}
private transient volatile Class<?> parameterClassCache = null;
private transient volatile Class<?> parameterClassCache;
/**
* Returns {@code true} if this parameter is implicitly declared
......
......@@ -33,7 +33,6 @@ import java.io.Serializable;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CoderResult;
import java.nio.charset.CodingErrorAction;
import java.nio.charset.CharacterCodingException;
......@@ -495,12 +494,12 @@ public final class URI
private transient volatile String schemeSpecificPart;
private transient volatile int hash; // Zero ==> undefined
private transient volatile String decodedUserInfo = null;
private transient volatile String decodedAuthority = null;
private transient volatile String decodedPath = null;
private transient volatile String decodedQuery = null;
private transient volatile String decodedFragment = null;
private transient volatile String decodedSchemeSpecificPart = null;
private transient volatile String decodedUserInfo;
private transient volatile String decodedAuthority;
private transient volatile String decodedPath;
private transient volatile String decodedQuery;
private transient volatile String decodedFragment;
private transient volatile String decodedSchemeSpecificPart;
/**
* The string form of this URI.
......
......@@ -25,9 +25,7 @@
package java.nio;
import java.security.AccessController;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.LongAdder;
import jdk.internal.misc.JavaNioAccess;
import jdk.internal.misc.JavaLangRefAccess;
......@@ -603,7 +601,8 @@ class Bits { // package-private
private static final AtomicLong reservedMemory = new AtomicLong();
private static final AtomicLong totalCapacity = new AtomicLong();
private static final AtomicLong count = new AtomicLong();
private static volatile boolean memoryLimitSet = false;
private static volatile boolean memoryLimitSet;
// max. number of sleeps during try-reserving with exponentially
// increasing delay before throwing OutOfMemoryError:
// 1, 2, 4, 8, 16, 32, 64, 128, 256 (total 511 ms ~ 0.5 s)
......
......@@ -26,8 +26,6 @@
package java.nio.channels;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import java.io.IOException;
/**
* A token representing the registration of a {@link SelectableChannel} with a
......@@ -363,7 +361,7 @@ public abstract class SelectionKey {
// -- Attachments --
private volatile Object attachment = null;
private volatile Object attachment;
private static final AtomicReferenceFieldUpdater<SelectionKey,Object>
attachmentUpdater = AtomicReferenceFieldUpdater.newUpdater(
......
......@@ -29,11 +29,7 @@
package java.nio.channels.spi;
import java.io.IOException;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
import java.nio.channels.*;
import java.security.AccessController;
import java.security.PrivilegedAction;
import jdk.internal.misc.SharedSecrets;
import sun.nio.ch.Interruptible;
......@@ -90,7 +86,7 @@ public abstract class AbstractInterruptibleChannel
{
private final Object closeLock = new Object();
private volatile boolean open = true;
private volatile boolean closed;
/**
* Initializes a new instance of this class.
......@@ -110,9 +106,9 @@ public abstract class AbstractInterruptibleChannel
*/
public final void close() throws IOException {
synchronized (closeLock) {
if (!open)
if (closed)
return;
open = false;
closed = true;
implCloseChannel();
}
}
......@@ -136,7 +132,7 @@ public abstract class AbstractInterruptibleChannel
protected abstract void implCloseChannel() throws IOException;
public final boolean isOpen() {
return open;
return !closed;
}
......@@ -158,9 +154,9 @@ public abstract class AbstractInterruptibleChannel
interruptor = new Interruptible() {
public void interrupt(Thread target) {
synchronized (closeLock) {
if (!open)
if (closed)
return;
open = false;
closed = true;
interrupted = target;
try {
AbstractInterruptibleChannel.this.implCloseChannel();
......@@ -202,7 +198,7 @@ public abstract class AbstractInterruptibleChannel
this.interrupted = null;
throw new ClosedByInterruptException();
}
if (!completed && !open)
if (!completed && closed)
throw new AsynchronousCloseException();
}
......
......@@ -276,7 +276,7 @@ public abstract class Charset
/* -- Static methods -- */
private static volatile String bugLevel = null;
private static volatile String bugLevel;
static boolean atBugLevel(String bl) { // package-private
String level = bugLevel;
......@@ -324,8 +324,8 @@ public abstract class Charset
// Cache of the most-recently-returned charsets,
// along with the names that were used to find them
//
private static volatile Object[] cache1 = null; // "Level 1" cache
private static volatile Object[] cache2 = null; // "Level 2" cache
private static volatile Object[] cache1; // "Level 1" cache
private static volatile Object[] cache2; // "Level 2" cache
private static void cache(String charsetName, Charset cs) {
cache2 = cache1;
......
......@@ -124,7 +124,7 @@ public class SecureRandom extends java.util.Random {
private String algorithm;
// Seed Generator
private static volatile SecureRandom seedGenerator = null;
private static volatile SecureRandom seedGenerator;
/**
* Constructs a secure random number generator (RNG) implementing the
......@@ -522,10 +522,12 @@ public class SecureRandom extends java.util.Random {
* @see #setSeed
*/
public static byte[] getSeed(int numBytes) {
if (seedGenerator == null) {
seedGenerator = new SecureRandom();
SecureRandom seedGen = seedGenerator;
if (seedGen == null) {
seedGen = new SecureRandom();
seedGenerator = seedGen;
}
return seedGenerator.generateSeed(numBytes);
return seedGen.generateSeed(numBytes);
}
/**
......
......@@ -630,7 +630,9 @@ public class DateFormatSymbols implements Serializable, Cloneable {
hashCode = 11 * hashCode + Arrays.hashCode(ampms);
hashCode = 11 * hashCode + Arrays.deepHashCode(getZoneStringsWrapper());
hashCode = 11 * hashCode + Objects.hashCode(localPatternChars);
cachedHashCode = hashCode;
if (hashCode != 0) {
cachedHashCode = hashCode;
}
}
return hashCode;
......@@ -670,12 +672,12 @@ public class DateFormatSymbols implements Serializable, Cloneable {
private static final ConcurrentMap<Locale, SoftReference<DateFormatSymbols>> cachedInstances
= new ConcurrentHashMap<>(3);
private transient int lastZoneIndex = 0;
private transient int lastZoneIndex;
/**
* Cached hash code
*/
transient volatile int cachedHashCode = 0;
transient volatile int cachedHashCode;
private void initializeData(Locale desiredLocale) {
locale = desiredLocale;
......
......@@ -42,14 +42,8 @@ import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.text.spi.DecimalFormatSymbolsProvider;
import java.util.ArrayList;
import java.util.Currency;
import java.util.List;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import sun.util.locale.provider.LocaleProviderAdapter;
import sun.util.locale.provider.LocaleServiceProviderPool;
import sun.util.locale.provider.ResourceBundleBasedAdapter;
......@@ -875,7 +869,7 @@ public class DecimalFormatSymbols implements Cloneable, Serializable {
// currency; only the ISO code is serialized.
private transient Currency currency;
private transient volatile boolean currencyInitialized = false;
private transient volatile boolean currencyInitialized;
// Proclaim JDK 1.1 FCS compatibility
static final long serialVersionUID = 5772796243397350300L;
......
......@@ -62,7 +62,6 @@ import sun.util.locale.ParseStatus;
import sun.util.locale.provider.LocaleProviderAdapter;
import sun.util.locale.provider.LocaleResources;
import sun.util.locale.provider.LocaleServiceProviderPool;
import sun.util.locale.provider.ResourceBundleBasedAdapter;
/**
* A <code>Locale</code> object represents a specific geographical, political,
......@@ -2016,11 +2015,11 @@ public final class Locale implements Cloneable, Serializable {
/**
* Calculated hashcode
*/
private transient volatile int hashCodeValue = 0;
private transient volatile int hashCodeValue;
private static volatile Locale defaultLocale = initDefault();
private static volatile Locale defaultDisplayLocale = null;
private static volatile Locale defaultFormatLocale = null;
private static volatile Locale defaultDisplayLocale;
private static volatile Locale defaultFormatLocale;
private transient volatile String languageTag;
......@@ -2207,9 +2206,9 @@ public final class Locale implements Cloneable, Serializable {
baseLocale.getRegion(), baseLocale.getVariant(), localeExtensions);
}
private static volatile String[] isoLanguages = null;
private static volatile String[] isoLanguages;
private static volatile String[] isoCountries = null;
private static volatile String[] isoCountries;
private static String convertOldISOCodes(String language) {
// we accept both the old and the new ISO codes for the languages whose ISO
......@@ -2851,7 +2850,7 @@ public final class Locale implements Cloneable, Serializable {
private final String range;
private final double weight;
private volatile int hash = 0;
private volatile int hash;
/**
* Constructs a {@code LanguageRange} using the given {@code range}.
......@@ -3108,14 +3107,17 @@ public final class Locale implements Cloneable, Serializable {
*/
@Override
public int hashCode() {
if (hash == 0) {
int result = 17;
result = 37*result + range.hashCode();
int h = hash;
if (h == 0) {
h = 17;
h = 37*h + range.hashCode();
long bitsWeight = Double.doubleToLongBits(weight);
result = 37*result + (int)(bitsWeight ^ (bitsWeight >>> 32));
hash = result;
h = 37*h + (int)(bitsWeight ^ (bitsWeight >>> 32));
if (h != 0) {
hash = h;
}
}
return hash;
return h;
}
/**
......
......@@ -950,7 +950,7 @@ public final class Pattern
* Boolean indicating this Pattern is compiled; this is necessary in order
* to lazily compile deserialized Patterns.
*/
private transient volatile boolean compiled = false;
private transient volatile boolean compiled;
/**
* The normalized pattern string.
......@@ -1332,7 +1332,6 @@ public final class Pattern
localCount = 0;
// if length > 0, the Pattern is lazily compiled
compiled = false;
if (pattern.length() == 0) {
root = new Start(lastAccept);
matchRoot = lastAccept;
......@@ -1377,7 +1376,6 @@ public final class Pattern
* equivalences of the characters.
*/
private void normalize() {
boolean inCharClass = false;
int lastCodePoint = -1;
// Convert pattern into normalized form
......@@ -1551,7 +1549,6 @@ public final class Pattern
// offset maintains the index in code units.
loop: for(int x=0, offset=0; x<nCodePoints; x++, offset+=len) {
len = countChars(input, offset, 1);
boolean skip = false;
for(int y=x-1; y>=0; y--) {
if (combClass[y] == combClass[x]) {
continue loop;
......@@ -1566,8 +1563,7 @@ loop: for(int x=0, offset=0; x<nCodePoints; x++, offset+=len) {
temp[index++] = prefix + sre;
}
String[] result = new String[index];
for (int x=0; x<index; x++)
result[x] = temp[x];
System.arraycopy(temp, 0, result, 0, index);
return result;
}
......@@ -1742,9 +1738,11 @@ loop: for(int x=0, offset=0; x<nCodePoints; x++, offset+=len) {
}
Map<String, Integer> namedGroups() {
if (namedGroups == null)
namedGroups = new HashMap<>(2);
return namedGroups;
Map<String, Integer> groups = namedGroups;
if (groups == null) {
namedGroups = groups = new HashMap<>(2);
}
return groups;
}
/**
......
......@@ -72,7 +72,7 @@ public
class ZipFile implements ZipConstants, Closeable {
private final String name; // zip file name
private volatile boolean closeRequested = false;
private volatile boolean closeRequested;
private Source zsrc;
private ZipCoder zc;
......@@ -366,7 +366,7 @@ class ZipFile implements ZipConstants, Closeable {
}
private class ZipFileInflaterInputStream extends InflaterInputStream {
private volatile boolean closeRequested = false;
private volatile boolean closeRequested;
private boolean eof = false;
private final ZipFileInputStream zfin;
......@@ -653,7 +653,7 @@ class ZipFile implements ZipConstants, Closeable {
* (possibly compressed) zip file entry.
*/
private class ZipFileInputStream extends InputStream {
private volatile boolean closeRequested = false;
private volatile boolean closeRequested;
private long pos; // current position within entry data
protected long rem; // number of remaining bytes within entry
protected long size; // uncompressed size of this entry
......
......@@ -326,20 +326,22 @@ public final class LazyLoggers {
}
// Do not expose this outside of this package.
private static volatile LoggerFinder provider = null;
private static volatile LoggerFinder provider;
private static LoggerFinder accessLoggerFinder() {
if (provider == null) {
LoggerFinder prov = provider;
if (prov == null) {
// no need to lock: it doesn't matter if we call
// getLoggerFinder() twice - since LoggerFinder already caches
// the result.
// This is just an optimization to avoid the cost of calling
// doPrivileged every time.
final SecurityManager sm = System.getSecurityManager();
provider = sm == null ? LoggerFinder.getLoggerFinder() :
prov = sm == null ? LoggerFinder.getLoggerFinder() :
AccessController.doPrivileged(
(PrivilegedAction<LoggerFinder>)LoggerFinder::getLoggerFinder);
provider = prov;
}
return provider;
return prov;
}
// Avoid using lambda here as lazy loggers could be created early
......
......@@ -27,9 +27,6 @@ package sun.misc;
import static java.lang.Thread.State.*;
import java.util.Properties;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class VM {
......@@ -288,10 +285,10 @@ public class VM {
}
/* Current count of objects pending for finalization */
private static volatile int finalRefCount = 0;
private static volatile int finalRefCount;
/* Peak count of objects pending for finalization */
private static volatile int peakFinalRefCount = 0;
private static volatile int peakFinalRefCount;
/*
* Gets the number of objects pending for finalization.
......
......@@ -54,12 +54,12 @@ import sun.util.logging.PlatformLogger;
* @author jccollet
*/
public class HttpCapture {
private File file = null;
private File file;
private boolean incoming = true;
private BufferedWriter out = null;
private static boolean initialized = false;
private static volatile ArrayList<Pattern> patterns = null;
private static volatile ArrayList<String> capFiles = null;
private BufferedWriter out;
private static boolean initialized;
private static volatile ArrayList<Pattern> patterns;
private static volatile ArrayList<String> capFiles;
private static synchronized void init() {
initialized = true;
......
......@@ -98,7 +98,7 @@ public class HttpClient extends NetworkClient {
// from previous releases.
private static boolean retryPostProp = true;
volatile boolean keepingAlive = false; /* this is a keep-alive connection */
volatile boolean keepingAlive; /* this is a keep-alive connection */
int keepAliveConnections = -1; /* number of keep-alives left */
/**Idle timeout value, in milliseconds. Zero means infinity,
......
......@@ -51,14 +51,14 @@ abstract class AsynchronousServerSocketChannelImpl
protected final FileDescriptor fd;
// the local address to which the channel's socket is bound
protected volatile InetSocketAddress localAddress = null;
protected volatile InetSocketAddress localAddress;
// need this lock to set local address
private final Object stateLock = new Object();
// close support
private ReadWriteLock closeLock = new ReentrantReadWriteLock();
private volatile boolean open = true;
private volatile boolean closed;
// set true when accept operation is cancelled
private volatile boolean acceptKilled;
......@@ -73,7 +73,7 @@ abstract class AsynchronousServerSocketChannelImpl
@Override
public final boolean isOpen() {
return open;
return !closed;
}
/**
......@@ -102,9 +102,9 @@ abstract class AsynchronousServerSocketChannelImpl
// synchronize with any threads using file descriptor/handle
closeLock.writeLock().lock();
try {
if (!open)
if (closed)
return; // already closed
open = false;
closed = true;
} finally {
closeLock.writeLock().unlock();
}
......
......@@ -54,8 +54,8 @@ abstract class AsynchronousSocketChannelImpl
// protects state, localAddress, and remoteAddress
protected final Object stateLock = new Object();
protected volatile InetSocketAddress localAddress = null;
protected volatile InetSocketAddress remoteAddress = null;
protected volatile InetSocketAddress localAddress;
protected volatile InetSocketAddress remoteAddress;
// State, increases monotonically
static final int ST_UNINITIALIZED = -1;
......@@ -78,7 +78,7 @@ abstract class AsynchronousSocketChannelImpl
// close support
private final ReadWriteLock closeLock = new ReentrantReadWriteLock();
private volatile boolean open = true;
private volatile boolean closed;
// set true when exclusive binding is on and SO_REUSEADDR is emulated
private boolean isReuseAddress;
......@@ -106,7 +106,7 @@ abstract class AsynchronousSocketChannelImpl
@Override
public final boolean isOpen() {
return open;
return !closed;
}
/**
......@@ -135,9 +135,9 @@ abstract class AsynchronousSocketChannelImpl
// synchronize with any threads initiating asynchronous operations
closeLock.writeLock().lock();
try {
if (!open)
if (closed)
return; // already closed
open = false;
closed = true;
} finally {
closeLock.writeLock().unlock();
}
......
......@@ -58,8 +58,8 @@ class DatagramChannelImpl
private final ProtocolFamily family;
// IDs of native threads doing reads and writes, for signalling
private volatile long readerThread = 0;
private volatile long writerThread = 0;
private volatile long readerThread;
private volatile long writerThread;
// Cached InetAddress and port for unconnected DatagramChannels
// used by receive0
......
......@@ -46,7 +46,7 @@ public class DatagramSocketAdaptor
private final DatagramChannelImpl dc;
// Timeout "option" value for receives
private volatile int timeout = 0;
private volatile int timeout;
// ## super will create a useless impl
private DatagramSocketAdaptor(DatagramChannelImpl dc) throws IOException {
......
......@@ -31,7 +31,7 @@ import java.nio.channels.*;
public class FileLockImpl
extends FileLock
{
private volatile boolean valid = true;
private volatile boolean invalid;
FileLockImpl(FileChannel channel, long position, long size, boolean shared)
{
......@@ -44,25 +44,25 @@ public class FileLockImpl
}
public boolean isValid() {
return valid;
return !invalid;
}
void invalidate() {
assert Thread.holdsLock(this);
valid = false;
invalid = true;
}
public synchronized void release() throws IOException {
Channel ch = acquiredBy();
if (!ch.isOpen())
throw new ClosedChannelException();
if (valid) {
if (isValid()) {
if (ch instanceof FileChannelImpl)
((FileChannelImpl)ch).release(this);
else if (ch instanceof AsynchronousFileChannelImpl)
((AsynchronousFileChannelImpl)ch).release(this);
else throw new AssertionError();
valid = false;
invalidate();
}
}
}
......@@ -43,8 +43,7 @@ class MembershipKeyImpl
private final NetworkInterface interf;
private final InetAddress source;
// true when key is valid
private volatile boolean valid = true;
private volatile boolean invalid;
// lock used when creating or accessing blockedSet
private Object stateLock = new Object();
......@@ -134,12 +133,12 @@ class MembershipKeyImpl
}
public boolean isValid() {
return valid;
return !invalid;
}
// package-private
void invalidate() {
valid = false;
invalid = true;
}
public void drop() {
......
......@@ -32,7 +32,6 @@ import java.nio.channels.*;
import java.util.*;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.PrivilegedExceptionAction;
import sun.net.ExtendedOptionsImpl;
......@@ -55,7 +54,7 @@ public class Net {
// -- Miscellaneous utilities --
private static volatile boolean checkedIPv6 = false;
private static volatile boolean checkedIPv6;
private static volatile boolean isIPv6Available;
/**
......
......@@ -45,7 +45,7 @@ public class ServerSocketAdaptor // package-private
private final ServerSocketChannelImpl ssc;
// Timeout "option" value for accepts
private volatile int timeout = 0;
private volatile int timeout;
public static ServerSocket create(ServerSocketChannelImpl ssc) {
try {
......
......@@ -54,7 +54,7 @@ class ServerSocketChannelImpl
private int fdVal;
// ID of native thread currently blocked in this channel, for signalling
private volatile long thread = 0;
private volatile long thread;
// Lock held by thread currently blocked in this channel
private final Object lock = new Object();
......
......@@ -26,13 +26,11 @@
package sun.nio.ch;
import java.io.*;
import java.lang.ref.*;
import java.net.*;
import java.nio.*;
import java.nio.channels.*;
import java.security.AccessController;
import java.security.PrivilegedExceptionAction;
import java.util.*;
// Make a socket channel look like a socket.
......@@ -55,7 +53,7 @@ public class SocketAdaptor
private final SocketChannelImpl sc;
// Timeout "option" value for reads
private volatile int timeout = 0;
private volatile int timeout;
private SocketAdaptor(SocketChannelImpl sc) throws SocketException {
super((SocketImpl) null);
......
......@@ -56,8 +56,8 @@ class SocketChannelImpl
private final int fdVal;
// IDs of native threads doing reads and writes, for signalling
private volatile long readerThread = 0;
private volatile long writerThread = 0;
private volatile long readerThread;
private volatile long writerThread;
// Lock held by current reading or connecting thread
private final Object readLock = new Object();
......
......@@ -25,13 +25,10 @@
package sun.nio.ch;
import java.lang.ref.SoftReference;
import java.lang.reflect.*;
import java.io.IOException;
import java.io.FileDescriptor;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.*;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.*;
......@@ -295,7 +292,7 @@ public class Util {
return pageSize;
}
private static volatile Constructor<?> directByteBufferConstructor = null;
private static volatile Constructor<?> directByteBufferConstructor;
private static void initDBBConstructor() {
AccessController.doPrivileged(new PrivilegedAction<Void>() {
......@@ -340,7 +337,7 @@ public class Util {
return dbb;
}
private static volatile Constructor<?> directByteBufferRConstructor = null;
private static volatile Constructor<?> directByteBufferRConstructor;
private static void initDBBRConstructor() {
AccessController.doPrivileged(new PrivilegedAction<Void>() {
......@@ -388,7 +385,7 @@ public class Util {
// -- Bug compatibility --
private static volatile String bugLevel = null;
private static volatile String bugLevel;
static boolean atBugLevel(String bl) { // package-private
if (bugLevel == null) {
......
......@@ -39,10 +39,10 @@ public class StreamDecoder extends Reader
private static final int MIN_BYTE_BUFFER_SIZE = 32;
private static final int DEFAULT_BYTE_BUFFER_SIZE = 8192;
private volatile boolean isOpen = true;
private volatile boolean closed;
private void ensureOpen() throws IOException {
if (!isOpen)
if (closed)
throw new IOException("Stream closed");
}
......@@ -188,15 +188,15 @@ public class StreamDecoder extends Reader
public void close() throws IOException {
synchronized (lock) {
if (!isOpen)
if (closed)
return;
implClose();
isOpen = false;
closed = true;
}
}
private boolean isOpen() {
return isOpen;
return !closed;
}
......
......@@ -38,10 +38,10 @@ public class StreamEncoder extends Writer
private static final int DEFAULT_BYTE_BUFFER_SIZE = 8192;
private volatile boolean isOpen = true;
private volatile boolean closed;
private void ensureOpen() throws IOException {
if (!isOpen)
if (closed)
throw new IOException("Stream closed");
}
......@@ -156,15 +156,15 @@ public class StreamEncoder extends Writer
public void close() throws IOException {
synchronized (lock) {
if (!isOpen)
if (closed)
return;
implClose();
isOpen = false;
closed = true;
}
}
private boolean isOpen() {
return isOpen;
return !closed;
}
......
......@@ -44,9 +44,9 @@ class MethodAccessorGenerator extends AccessorGenerator {
// Only used if forSerialization is true
private static final short NUM_SERIALIZATION_CPOOL_ENTRIES = (short) 2;
private static volatile int methodSymnum = 0;
private static volatile int constructorSymnum = 0;
private static volatile int serializationConstructorSymnum = 0;
private static volatile int methodSymnum;
private static volatile int constructorSymnum;
private static volatile int serializationConstructorSymnum;
private Class<?> declaringClass;
private Class<?>[] parameterTypes;
......
......@@ -299,7 +299,7 @@ class AnnotationInvocationHandler implements InvocationHandler, Serializable {
}});
}
private transient volatile Method[] memberMethods = null;
private transient volatile Method[] memberMethods;
/**
* Validates that a method is structurally appropriate for an
......
......@@ -130,7 +130,7 @@ final class SSLSessionImpl extends ExtendedSSLSession {
* also since counters make shorter debugging IDs than the big ones
* we use in the protocol for uniqueness-over-time.
*/
private static volatile int counter = 0;
private static volatile int counter;
/*
* Use of session caches is globally enabled/disabled.
......
......@@ -1290,7 +1290,7 @@ public class X509CRLImpl extends X509CRL implements DerEncoder {
implements Comparable<X509IssuerSerial> {
final X500Principal issuer;
final BigInteger serial;
volatile int hashcode = 0;
volatile int hashcode;
/**
* Create an X509IssuerSerial.
......@@ -1358,13 +1358,16 @@ public class X509CRLImpl extends X509CRL implements DerEncoder {
* @return the hash code value
*/
public int hashCode() {
if (hashcode == 0) {
int result = 17;
result = 37*result + issuer.hashCode();
result = 37*result + serial.hashCode();
hashcode = result;
int h = hashcode;
if (h == 0) {
h = 17;
h = 37*h + issuer.hashCode();
h = 37*h + serial.hashCode();
if (h != 0) {
hashcode = h;
}
}
return hashcode;
return h;
}
@Override
......
......@@ -25,13 +25,6 @@
package sun.util.calendar;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.Properties;
import java.util.TimeZone;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
......@@ -76,7 +69,7 @@ public abstract class CalendarSystem {
/////////////////////// Calendar Factory Methods /////////////////////////
private static volatile boolean initialized = false;
private static volatile boolean initialized;
// Map of calendar names and calendar class names
private static ConcurrentMap<String, String> names;
......
......@@ -46,7 +46,7 @@ public final class BaseLocale {
private final String region;
private final String variant;
private volatile int hash = 0;
private volatile int hash;
// This method must be called only when creating the Locale.* constants.
private BaseLocale(String language, String region) {
......@@ -147,7 +147,9 @@ public final class BaseLocale {
h = 31 * h + script.hashCode();
h = 31 * h + region.hashCode();
h = 31 * h + variant.hashCode();
hash = h;
if (h != 0) {
hash = h;
}
}
return h;
}
......
......@@ -114,20 +114,20 @@ public class JRELocaleProviderAdapter extends LocaleProviderAdapter implements R
}
}
private volatile BreakIteratorProvider breakIteratorProvider = null;
private volatile CollatorProvider collatorProvider = null;
private volatile DateFormatProvider dateFormatProvider = null;
private volatile DateFormatSymbolsProvider dateFormatSymbolsProvider = null;
private volatile DecimalFormatSymbolsProvider decimalFormatSymbolsProvider = null;
private volatile NumberFormatProvider numberFormatProvider = null;
private volatile CurrencyNameProvider currencyNameProvider = null;
private volatile LocaleNameProvider localeNameProvider = null;
private volatile TimeZoneNameProvider timeZoneNameProvider = null;
private volatile CalendarDataProvider calendarDataProvider = null;
private volatile CalendarNameProvider calendarNameProvider = null;
private volatile CalendarProvider calendarProvider = null;
private volatile BreakIteratorProvider breakIteratorProvider;
private volatile CollatorProvider collatorProvider;
private volatile DateFormatProvider dateFormatProvider;
private volatile DateFormatSymbolsProvider dateFormatSymbolsProvider;
private volatile DecimalFormatSymbolsProvider decimalFormatSymbolsProvider;
private volatile NumberFormatProvider numberFormatProvider;
private volatile CurrencyNameProvider currencyNameProvider;
private volatile LocaleNameProvider localeNameProvider;
private volatile TimeZoneNameProvider timeZoneNameProvider;
private volatile CalendarDataProvider calendarDataProvider;
private volatile CalendarNameProvider calendarNameProvider;
private volatile CalendarProvider calendarProvider;
/*
* Getter methods for java.text.spi.* providers
......
......@@ -107,7 +107,7 @@ public abstract class LocaleProviderAdapter {
* Default fallback adapter type, which should return something meaningful in any case.
* This is either CLDR or FALLBACK.
*/
static volatile LocaleProviderAdapter.Type defaultLocaleProviderAdapter = null;
static volatile LocaleProviderAdapter.Type defaultLocaleProviderAdapter;
/**
* Adapter lookup cache.
......
......@@ -164,6 +164,6 @@ public abstract class OpenListResourceBundle extends ResourceBundle {
return new HashSet<>();
}
private volatile Map<String, Object> lookup = null;
private volatile Map<String, Object> lookup;
private volatile Set<String> keyset;
}
......@@ -47,7 +47,7 @@ class SinkChannelImpl
int fdVal;
// ID of native thread doing write, for signalling
private volatile long thread = 0;
private volatile long thread;
// Lock held by current reading thread
private final Object lock = new Object();
......
......@@ -47,7 +47,7 @@ class SourceChannelImpl
int fdVal;
// ID of native thread doing read, for signalling
private volatile long thread = 0;
private volatile long thread;
// Lock held by current reading thread
private final Object lock = new Object();
......
......@@ -52,7 +52,7 @@ class MimeTypesFileTypeDetector extends AbstractFileTypeDetector {
private Map<String,String> mimeTypeMap;
// set to true when file loaded
private volatile boolean loaded = false;
private volatile boolean loaded;
public MimeTypesFileTypeDetector(Path filePath) {
mimeTypesFile = filePath;
......
......@@ -119,7 +119,7 @@ final class WindowsSelectorImpl extends SelectorImpl {
// Lock for interrupt triggering and clearing
private final Object interruptLock = new Object();
private volatile boolean interruptTriggered = false;
private volatile boolean interruptTriggered;
WindowsSelectorImpl(SelectorProvider sp) throws IOException {
super(sp);
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册