all: remove java6 type args

This commit is contained in:
Carl Mastrangelo 2019-02-04 10:03:50 -08:00 committed by GitHub
parent a31473ef20
commit 3a39b81cf5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
145 changed files with 486 additions and 489 deletions

View File

@ -29,7 +29,7 @@ class AltsHandshakerStub {
private final StreamObserver<HandshakerResp> reader = new Reader(); private final StreamObserver<HandshakerResp> reader = new Reader();
private final StreamObserver<HandshakerReq> writer; private final StreamObserver<HandshakerReq> writer;
private final ArrayBlockingQueue<Optional<HandshakerResp>> responseQueue = private final ArrayBlockingQueue<Optional<HandshakerResp>> responseQueue =
new ArrayBlockingQueue<Optional<HandshakerResp>>(1); new ArrayBlockingQueue<>(1);
private final AtomicReference<String> exceptionMessage = new AtomicReference<>(); private final AtomicReference<String> exceptionMessage = new AtomicReference<>();
AltsHandshakerStub(HandshakerServiceStub serviceStub) { AltsHandshakerStub(HandshakerServiceStub serviceStub) {

View File

@ -99,7 +99,7 @@ public final class AltsTsiHandshaker implements TsiHandshaker {
@Override @Override
public TsiPeer extractPeer() throws GeneralSecurityException { public TsiPeer extractPeer() throws GeneralSecurityException {
Preconditions.checkState(!isInProgress(), "Handshake is not complete."); Preconditions.checkState(!isInProgress(), "Handshake is not complete.");
List<TsiPeer.Property<?>> peerProperties = new ArrayList<TsiPeer.Property<?>>(); List<TsiPeer.Property<?>> peerProperties = new ArrayList<>();
peerProperties.add( peerProperties.add(
new TsiPeer.StringProperty( new TsiPeer.StringProperty(
TSI_SERVICE_ACCOUNT_PEER_PROPERTY, TSI_SERVICE_ACCOUNT_PEER_PROPERTY,

View File

@ -210,7 +210,7 @@ public class AltsProtocolNegotiatorTest {
// Capture the protected data written to the wire. // Capture the protected data written to the wire.
assertEquals(1, channel.outboundMessages().size()); assertEquals(1, channel.outboundMessages().size());
ByteBuf protectedData = channel.<ByteBuf>readOutbound(); ByteBuf protectedData = channel.readOutbound();
assertEquals(message.length(), writeCount.get()); assertEquals(message.length(), writeCount.get());
// Read the protected message at the server and verify it matches the original message. // Read the protected message at the server and verify it matches the original message.
@ -276,7 +276,7 @@ public class AltsProtocolNegotiatorTest {
// Read the protected message at the client and verify that it matches the original message. // Read the protected message at the client and verify that it matches the original message.
assertEquals(1, channel.inboundMessages().size()); assertEquals(1, channel.inboundMessages().size());
ByteBuf receivedData1 = channel.<ByteBuf>readInbound(); ByteBuf receivedData1 = channel.readInbound();
int receivedLen1 = receivedData1.readableBytes(); int receivedLen1 = receivedData1.readableBytes();
byte[] receivedBytes = new byte[receivedLen1]; byte[] receivedBytes = new byte[receivedLen1];
receivedData1.readBytes(receivedBytes, 0, receivedLen1); receivedData1.readBytes(receivedBytes, 0, receivedLen1);
@ -364,7 +364,7 @@ public class AltsProtocolNegotiatorTest {
private void doHandshake() throws Exception { private void doHandshake() throws Exception {
// Capture the client frame and add to the server. // Capture the client frame and add to the server.
assertEquals(1, channel.outboundMessages().size()); assertEquals(1, channel.outboundMessages().size());
ByteBuf clientFrame = channel.<ByteBuf>readOutbound(); ByteBuf clientFrame = channel.readOutbound();
assertTrue(serverHandshaker.processBytesFromPeer(clientFrame)); assertTrue(serverHandshaker.processBytesFromPeer(clientFrame));
// Get the server response handshake frames. // Get the server response handshake frames.
@ -374,7 +374,7 @@ public class AltsProtocolNegotiatorTest {
// Capture the next client frame and add to the server. // Capture the next client frame and add to the server.
assertEquals(1, channel.outboundMessages().size()); assertEquals(1, channel.outboundMessages().size());
clientFrame = channel.<ByteBuf>readOutbound(); clientFrame = channel.readOutbound();
assertTrue(serverHandshaker.processBytesFromPeer(clientFrame)); assertTrue(serverHandshaker.processBytesFromPeer(clientFrame));
// Get the server response handshake frames. // Get the server response handshake frames.

View File

@ -221,7 +221,7 @@ public class GoogleAuthLibraryCallCredentialsTest {
ListMultimap<String, String> values = LinkedListMultimap.create(); ListMultimap<String, String> values = LinkedListMultimap.create();
values.put("Authorization", "token1"); values.put("Authorization", "token1");
when(credentials.getRequestMetadata(eq(expectedUri))) when(credentials.getRequestMetadata(eq(expectedUri)))
.thenReturn(null, Multimaps.<String, String>asMap(values), null); .thenReturn(null, Multimaps.asMap(values), null);
GoogleAuthLibraryCallCredentials callCredentials = GoogleAuthLibraryCallCredentials callCredentials =
new GoogleAuthLibraryCallCredentials(credentials); new GoogleAuthLibraryCallCredentials(credentials);

View File

@ -432,7 +432,7 @@ public abstract class AbstractBenchmark {
final ClientCall<ByteBuf, ByteBuf> streamingCall = final ClientCall<ByteBuf, ByteBuf> streamingCall =
channel.newCall(pingPongMethod, CALL_OPTIONS); channel.newCall(pingPongMethod, CALL_OPTIONS);
final AtomicReference<StreamObserver<ByteBuf>> requestObserverRef = final AtomicReference<StreamObserver<ByteBuf>> requestObserverRef =
new AtomicReference<StreamObserver<ByteBuf>>(); new AtomicReference<>();
final AtomicBoolean ignoreMessages = new AtomicBoolean(); final AtomicBoolean ignoreMessages = new AtomicBoolean();
StreamObserver<ByteBuf> requestObserver = ClientCalls.asyncBidiStreamingCall( StreamObserver<ByteBuf> requestObserver = ClientCalls.asyncBidiStreamingCall(
streamingCall, streamingCall,
@ -486,7 +486,7 @@ public abstract class AbstractBenchmark {
final ClientCall<ByteBuf, ByteBuf> streamingCall = final ClientCall<ByteBuf, ByteBuf> streamingCall =
channel.newCall(flowControlledStreaming, CALL_OPTIONS); channel.newCall(flowControlledStreaming, CALL_OPTIONS);
final AtomicReference<StreamObserver<ByteBuf>> requestObserverRef = final AtomicReference<StreamObserver<ByteBuf>> requestObserverRef =
new AtomicReference<StreamObserver<ByteBuf>>(); new AtomicReference<>();
final AtomicBoolean ignoreMessages = new AtomicBoolean(); final AtomicBoolean ignoreMessages = new AtomicBoolean();
StreamObserver<ByteBuf> requestObserver = ClientCalls.asyncBidiStreamingCall( StreamObserver<ByteBuf> requestObserver = ClientCalls.asyncBidiStreamingCall(
streamingCall, streamingCall,

View File

@ -379,7 +379,7 @@ class LoadClient {
while (!shutdown) { while (!shutdown) {
maxOutstanding.acquireUninterruptibly(); maxOutstanding.acquireUninterruptibly();
final AtomicReference<StreamObserver<Messages.SimpleRequest>> requestObserver = final AtomicReference<StreamObserver<Messages.SimpleRequest>> requestObserver =
new AtomicReference<StreamObserver<Messages.SimpleRequest>>(); new AtomicReference<>();
requestObserver.set(stub.streamingCall( requestObserver.set(stub.streamingCall(
new StreamObserver<Messages.SimpleResponse>() { new StreamObserver<Messages.SimpleResponse>() {
long now = System.nanoTime(); long now = System.nanoTime();

View File

@ -109,7 +109,7 @@ public abstract class AbstractConfigurationBuilder<T extends Configuration>
public final T build(String[] args) { public final T build(String[] args) {
T config = newConfiguration(); T config = newConfiguration();
Map<String, Param> paramMap = getParamMap(); Map<String, Param> paramMap = getParamMap();
Set<String> appliedParams = new TreeSet<String>(CASE_INSENSITIVE_ORDER); Set<String> appliedParams = new TreeSet<>(CASE_INSENSITIVE_ORDER);
for (String arg : args) { for (String arg : args) {
if (!arg.startsWith("--")) { if (!arg.startsWith("--")) {
@ -197,7 +197,7 @@ public abstract class AbstractConfigurationBuilder<T extends Configuration>
protected abstract T build0(T config); protected abstract T build0(T config);
private Map<String, Param> getParamMap() { private Map<String, Param> getParamMap() {
Map<String, Param> map = new TreeMap<String, Param>(CASE_INSENSITIVE_ORDER); Map<String, Param> map = new TreeMap<>(CASE_INSENSITIVE_ORDER);
for (Param param : getParams()) { for (Param param : getParams()) {
map.put(param.getName(), param); map.put(param.getName(), param);
} }

View File

@ -122,7 +122,7 @@ public class AsyncClient {
long endTime) throws Exception { long endTime) throws Exception {
// Initiate the concurrent calls // Initiate the concurrent calls
List<Future<Histogram>> futures = List<Future<Histogram>> futures =
new ArrayList<Future<Histogram>>(config.outstandingRpcsPerChannel); new ArrayList<>(config.outstandingRpcsPerChannel);
for (int i = 0; i < config.channels; i++) { for (int i = 0; i < config.channels; i++) {
for (int j = 0; j < config.outstandingRpcsPerChannel; j++) { for (int j = 0; j < config.outstandingRpcsPerChannel; j++) {
Channel channel = channels.get(i); Channel channel = channels.get(i);

View File

@ -59,7 +59,7 @@ public class LoadWorkerTest {
worker.start(); worker.start();
channel = NettyChannelBuilder.forAddress("localhost", port).usePlaintext().build(); channel = NettyChannelBuilder.forAddress("localhost", port).usePlaintext().build();
workerServiceStub = WorkerServiceGrpc.newStub(channel); workerServiceStub = WorkerServiceGrpc.newStub(channel);
marksQueue = new LinkedBlockingQueue<Stats.ClientStats>(); marksQueue = new LinkedBlockingQueue<>();
} }
@Test @Test

View File

@ -33,7 +33,7 @@ public class ReadBenchmark {
@State(Scope.Benchmark) @State(Scope.Benchmark)
public static class ContextState { public static class ContextState {
List<Context.Key<Object>> keys = new ArrayList<Context.Key<Object>>(); List<Context.Key<Object>> keys = new ArrayList<>();
List<Context> contexts = new ArrayList<>(); List<Context> contexts = new ArrayList<>();
@Setup @Setup

View File

@ -100,7 +100,7 @@ public class Context {
private static final Logger log = Logger.getLogger(Context.class.getName()); private static final Logger log = Logger.getLogger(Context.class.getName());
private static final PersistentHashArrayMappedTrie<Key<?>, Object> EMPTY_ENTRIES = private static final PersistentHashArrayMappedTrie<Key<?>, Object> EMPTY_ENTRIES =
new PersistentHashArrayMappedTrie<Key<?>, Object>(); new PersistentHashArrayMappedTrie<>();
// Long chains of contexts are suspicious and usually indicate a misuse of Context. // Long chains of contexts are suspicious and usually indicate a misuse of Context.
// The threshold is arbitrarily chosen. // The threshold is arbitrarily chosen.
@ -120,7 +120,7 @@ public class Context {
// much easier to avoid circular loading since there can still be references to Context as long as // much easier to avoid circular loading since there can still be references to Context as long as
// they don't depend on storage, like key() and currentContextExecutor(). It also makes it easier // they don't depend on storage, like key() and currentContextExecutor(). It also makes it easier
// to handle exceptions. // to handle exceptions.
private static final AtomicReference<Storage> storage = new AtomicReference<Storage>(); private static final AtomicReference<Storage> storage = new AtomicReference<>();
// For testing // For testing
static Storage storage() { static Storage storage() {
@ -159,7 +159,7 @@ public class Context {
* the name is intended for debugging purposes and does not impact behavior. * the name is intended for debugging purposes and does not impact behavior.
*/ */
public static <T> Key<T> key(String name) { public static <T> Key<T> key(String name) {
return new Key<T>(name); return new Key<>(name);
} }
/** /**
@ -167,7 +167,7 @@ public class Context {
* have the same name; the name is intended for debugging purposes and does not impact behavior. * have the same name; the name is intended for debugging purposes and does not impact behavior.
*/ */
public static <T> Key<T> keyWithDefault(String name, T defaultValue) { public static <T> Key<T> keyWithDefault(String name, T defaultValue) {
return new Key<T>(name, defaultValue); return new Key<>(name, defaultValue);
} }
/** /**

View File

@ -62,9 +62,9 @@ final class PersistentHashArrayMappedTrie<K,V> {
*/ */
public PersistentHashArrayMappedTrie<K,V> put(K key, V value) { public PersistentHashArrayMappedTrie<K,V> put(K key, V value) {
if (root == null) { if (root == null) {
return new PersistentHashArrayMappedTrie<K,V>(new Leaf<K,V>(key, value)); return new PersistentHashArrayMappedTrie<>(new Leaf<>(key, value));
} else { } else {
return new PersistentHashArrayMappedTrie<K,V>(root.put(key, value, key.hashCode(), 0)); return new PersistentHashArrayMappedTrie<>(root.put(key, value, key.hashCode(), 0));
} }
} }
@ -99,13 +99,13 @@ final class PersistentHashArrayMappedTrie<K,V> {
if (thisHash != hash) { if (thisHash != hash) {
// Insert // Insert
return CompressedIndex.combine( return CompressedIndex.combine(
new Leaf<K,V>(key, value), hash, this, thisHash, bitsConsumed); new Leaf<>(key, value), hash, this, thisHash, bitsConsumed);
} else if (this.key == key) { } else if (this.key == key) {
// Replace // Replace
return new Leaf<K,V>(key, value); return new Leaf<>(key, value);
} else { } else {
// Hash collision // Hash collision
return new CollisionLeaf<K,V>(this.key, this.value, key, value); return new CollisionLeaf<>(this.key, this.value, key, value);
} }
} }
@ -158,21 +158,21 @@ final class PersistentHashArrayMappedTrie<K,V> {
if (thisHash != hash) { if (thisHash != hash) {
// Insert // Insert
return CompressedIndex.combine( return CompressedIndex.combine(
new Leaf<K,V>(key, value), hash, this, thisHash, bitsConsumed); new Leaf<>(key, value), hash, this, thisHash, bitsConsumed);
} else if ((keyIndex = indexOfKey(key)) != -1) { } else if ((keyIndex = indexOfKey(key)) != -1) {
// Replace // Replace
K[] newKeys = Arrays.copyOf(keys, keys.length); K[] newKeys = Arrays.copyOf(keys, keys.length);
V[] newValues = Arrays.copyOf(values, keys.length); V[] newValues = Arrays.copyOf(values, keys.length);
newKeys[keyIndex] = key; newKeys[keyIndex] = key;
newValues[keyIndex] = value; newValues[keyIndex] = value;
return new CollisionLeaf<K,V>(newKeys, newValues); return new CollisionLeaf<>(newKeys, newValues);
} else { } else {
// Yet another hash collision // Yet another hash collision
K[] newKeys = Arrays.copyOf(keys, keys.length + 1); K[] newKeys = Arrays.copyOf(keys, keys.length + 1);
V[] newValues = Arrays.copyOf(values, keys.length + 1); V[] newValues = Arrays.copyOf(values, keys.length + 1);
newKeys[keys.length] = key; newKeys[keys.length] = key;
newValues[keys.length] = value; newValues[keys.length] = value;
return new CollisionLeaf<K,V>(newKeys, newValues); return new CollisionLeaf<>(newKeys, newValues);
} }
} }
@ -238,14 +238,14 @@ final class PersistentHashArrayMappedTrie<K,V> {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
Node<K,V>[] newValues = (Node<K,V>[]) new Node<?,?>[values.length + 1]; Node<K,V>[] newValues = (Node<K,V>[]) new Node<?,?>[values.length + 1];
System.arraycopy(values, 0, newValues, 0, compressedIndex); System.arraycopy(values, 0, newValues, 0, compressedIndex);
newValues[compressedIndex] = new Leaf<K,V>(key, value); newValues[compressedIndex] = new Leaf<>(key, value);
System.arraycopy( System.arraycopy(
values, values,
compressedIndex, compressedIndex,
newValues, newValues,
compressedIndex + 1, compressedIndex + 1,
values.length - compressedIndex); values.length - compressedIndex);
return new CompressedIndex<K,V>(newBitmap, newValues, size() + 1); return new CompressedIndex<>(newBitmap, newValues, size() + 1);
} else { } else {
// Replace // Replace
Node<K,V>[] newValues = Arrays.copyOf(values, values.length); Node<K,V>[] newValues = Arrays.copyOf(values, values.length);
@ -254,7 +254,7 @@ final class PersistentHashArrayMappedTrie<K,V> {
int newSize = size(); int newSize = size();
newSize += newValues[compressedIndex].size(); newSize += newValues[compressedIndex].size();
newSize -= values[compressedIndex].size(); newSize -= values[compressedIndex].size();
return new CompressedIndex<K,V>(bitmap, newValues, newSize); return new CompressedIndex<>(bitmap, newValues, newSize);
} }
} }
@ -267,7 +267,7 @@ final class PersistentHashArrayMappedTrie<K,V> {
Node<K,V> node = combine(node1, hash1, node2, hash2, bitsConsumed + BITS); Node<K,V> node = combine(node1, hash1, node2, hash2, bitsConsumed + BITS);
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
Node<K,V>[] values = (Node<K,V>[]) new Node<?,?>[] {node}; Node<K,V>[] values = (Node<K,V>[]) new Node<?,?>[] {node};
return new CompressedIndex<K,V>(indexBit1, values, node.size()); return new CompressedIndex<>(indexBit1, values, node.size());
} else { } else {
// Make node1 the smallest // Make node1 the smallest
if (uncompressedIndex(hash1, bitsConsumed) > uncompressedIndex(hash2, bitsConsumed)) { if (uncompressedIndex(hash1, bitsConsumed) > uncompressedIndex(hash2, bitsConsumed)) {
@ -277,7 +277,7 @@ final class PersistentHashArrayMappedTrie<K,V> {
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
Node<K,V>[] values = (Node<K,V>[]) new Node<?,?>[] {node1, node2}; Node<K,V>[] values = (Node<K,V>[]) new Node<?,?>[] {node1, node2};
return new CompressedIndex<K,V>(indexBit1 | indexBit2, values, node1.size() + node2.size()); return new CompressedIndex<>(indexBit1 | indexBit2, values, node1.size() + node2.size());
} }
} }

View File

@ -29,7 +29,7 @@ final class ThreadLocalContextStorage extends Context.Storage {
* Currently bound context. * Currently bound context.
*/ */
// VisibleForTesting // VisibleForTesting
static final ThreadLocal<Context> localContext = new ThreadLocal<Context>(); static final ThreadLocal<Context> localContext = new ThreadLocal<>();
@Override @Override
public Context doAttach(Context toAttach) { public Context doAttach(Context toAttach) {

View File

@ -166,7 +166,7 @@ public class ContextTest {
@Test @Test
public void detachingNonCurrentLogsSevereMessage() { public void detachingNonCurrentLogsSevereMessage() {
final AtomicReference<LogRecord> logRef = new AtomicReference<LogRecord>(); final AtomicReference<LogRecord> logRef = new AtomicReference<>();
Handler handler = new Handler() { Handler handler = new Handler() {
@Override @Override
public void publish(LogRecord record) { public void publish(LogRecord record) {
@ -284,9 +284,9 @@ public class ContextTest {
} }
Context.CancellableContext base = Context.current().withCancellation(); Context.CancellableContext base = Context.current().withCancellation();
final AtomicReference<Context> observed1 = new AtomicReference<Context>(); final AtomicReference<Context> observed1 = new AtomicReference<>();
base.addListener(new SetContextCancellationListener(observed1), MoreExecutors.directExecutor()); base.addListener(new SetContextCancellationListener(observed1), MoreExecutors.directExecutor());
final AtomicReference<Context> observed2 = new AtomicReference<Context>(); final AtomicReference<Context> observed2 = new AtomicReference<>();
base.addListener(new SetContextCancellationListener(observed2), MoreExecutors.directExecutor()); base.addListener(new SetContextCancellationListener(observed2), MoreExecutors.directExecutor());
assertNull(observed1.get()); assertNull(observed1.get());
assertNull(observed2.get()); assertNull(observed2.get());
@ -294,14 +294,14 @@ public class ContextTest {
assertSame(base, observed1.get()); assertSame(base, observed1.get());
assertSame(base, observed2.get()); assertSame(base, observed2.get());
final AtomicReference<Context> observed3 = new AtomicReference<Context>(); final AtomicReference<Context> observed3 = new AtomicReference<>();
base.addListener(new SetContextCancellationListener(observed3), MoreExecutors.directExecutor()); base.addListener(new SetContextCancellationListener(observed3), MoreExecutors.directExecutor());
assertSame(base, observed3.get()); assertSame(base, observed3.get());
} }
@Test @Test
public void exceptionOfExecutorDoesntThrow() { public void exceptionOfExecutorDoesntThrow() {
final AtomicReference<Throwable> loggedThrowable = new AtomicReference<Throwable>(); final AtomicReference<Throwable> loggedThrowable = new AtomicReference<>();
Handler logHandler = new Handler() { Handler logHandler = new Handler() {
@Override @Override
public void publish(LogRecord record) { public void publish(LogRecord record) {
@ -325,7 +325,7 @@ public class ContextTest {
logger.addHandler(logHandler); logger.addHandler(logHandler);
try { try {
Context.CancellableContext base = Context.current().withCancellation(); Context.CancellableContext base = Context.current().withCancellation();
final AtomicReference<Runnable> observed1 = new AtomicReference<Runnable>(); final AtomicReference<Runnable> observed1 = new AtomicReference<>();
final Error err = new Error(); final Error err = new Error();
base.addListener(cancellationListener, new Executor() { base.addListener(cancellationListener, new Executor() {
@Override @Override
@ -342,7 +342,7 @@ public class ContextTest {
final Error err2 = new Error(); final Error err2 = new Error();
loggedThrowable.set(null); loggedThrowable.set(null);
final AtomicReference<Runnable> observed2 = new AtomicReference<Runnable>(); final AtomicReference<Runnable> observed2 = new AtomicReference<>();
base.addListener(cancellationListener, new Executor() { base.addListener(cancellationListener, new Executor() {
@Override @Override
public void execute(Runnable runnable) { public void execute(Runnable runnable) {
@ -596,7 +596,7 @@ public class ContextTest {
assertSame(parent.getDeadline(), sooner); assertSame(parent.getDeadline(), sooner);
assertSame(child.getDeadline(), sooner); assertSame(child.getDeadline(), sooner);
final CountDownLatch latch = new CountDownLatch(1); final CountDownLatch latch = new CountDownLatch(1);
final AtomicReference<Exception> error = new AtomicReference<Exception>(); final AtomicReference<Exception> error = new AtomicReference<>();
child.addListener(new Context.CancellationListener() { child.addListener(new Context.CancellationListener() {
@Override @Override
public void cancelled(Context context) { public void cancelled(Context context) {
@ -709,7 +709,7 @@ public class ContextTest {
} }
private static class QueuedExecutor implements Executor { private static class QueuedExecutor implements Executor {
private final Queue<Runnable> runnables = new ArrayDeque<Runnable>(); private final Queue<Runnable> runnables = new ArrayDeque<>();
@Override @Override
public void execute(Runnable r) { public void execute(Runnable r) {
@ -939,7 +939,7 @@ public class ContextTest {
@Test @Test
public void errorWhenAncestryLengthLong() { public void errorWhenAncestryLengthLong() {
final AtomicReference<LogRecord> logRef = new AtomicReference<LogRecord>(); final AtomicReference<LogRecord> logRef = new AtomicReference<>();
Handler handler = new Handler() { Handler handler = new Handler() {
@Override @Override
public void publish(LogRecord record) { public void publish(LogRecord record) {

View File

@ -35,7 +35,7 @@ public class PersistentHashArrayMappedTrieTest {
Key key = new Key(0); Key key = new Key(0);
Object value1 = new Object(); Object value1 = new Object();
Object value2 = new Object(); Object value2 = new Object();
Leaf<Key, Object> leaf = new Leaf<Key, Object>(key, value1); Leaf<Key, Object> leaf = new Leaf<>(key, value1);
Node<Key, Object> ret = leaf.put(key, value2, key.hashCode(), 0); Node<Key, Object> ret = leaf.put(key, value2, key.hashCode(), 0);
assertTrue(ret instanceof Leaf); assertTrue(ret instanceof Leaf);
assertSame(value2, ret.get(key, key.hashCode(), 0)); assertSame(value2, ret.get(key, key.hashCode(), 0));
@ -52,7 +52,7 @@ public class PersistentHashArrayMappedTrieTest {
Key key2 = new Key(0); Key key2 = new Key(0);
Object value1 = new Object(); Object value1 = new Object();
Object value2 = new Object(); Object value2 = new Object();
Leaf<Key, Object> leaf = new Leaf<Key, Object>(key1, value1); Leaf<Key, Object> leaf = new Leaf<>(key1, value1);
Node<Key, Object> ret = leaf.put(key2, value2, key2.hashCode(), 0); Node<Key, Object> ret = leaf.put(key2, value2, key2.hashCode(), 0);
assertTrue(ret instanceof CollisionLeaf); assertTrue(ret instanceof CollisionLeaf);
assertSame(value1, ret.get(key1, key1.hashCode(), 0)); assertSame(value1, ret.get(key1, key1.hashCode(), 0));
@ -71,7 +71,7 @@ public class PersistentHashArrayMappedTrieTest {
Key key2 = new Key(1); Key key2 = new Key(1);
Object value1 = new Object(); Object value1 = new Object();
Object value2 = new Object(); Object value2 = new Object();
Leaf<Key, Object> leaf = new Leaf<Key, Object>(key1, value1); Leaf<Key, Object> leaf = new Leaf<>(key1, value1);
Node<Key, Object> ret = leaf.put(key2, value2, key2.hashCode(), 0); Node<Key, Object> ret = leaf.put(key2, value2, key2.hashCode(), 0);
assertTrue(ret instanceof CompressedIndex); assertTrue(ret instanceof CompressedIndex);
assertSame(value1, ret.get(key1, key1.hashCode(), 0)); assertSame(value1, ret.get(key1, key1.hashCode(), 0));
@ -87,12 +87,12 @@ public class PersistentHashArrayMappedTrieTest {
@Test(expected = AssertionError.class) @Test(expected = AssertionError.class)
public void collisionLeaf_assertKeysDifferent() { public void collisionLeaf_assertKeysDifferent() {
Key key1 = new Key(0); Key key1 = new Key(0);
new CollisionLeaf<Key, Object>(key1, new Object(), key1, new Object()); new CollisionLeaf<>(key1, new Object(), key1, new Object());
} }
@Test(expected = AssertionError.class) @Test(expected = AssertionError.class)
public void collisionLeaf_assertHashesSame() { public void collisionLeaf_assertHashesSame() {
new CollisionLeaf<Key, Object>(new Key(0), new Object(), new Key(1), new Object()); new CollisionLeaf<>(new Key(0), new Object(), new Key(1), new Object());
} }
@Test @Test
@ -104,7 +104,7 @@ public class PersistentHashArrayMappedTrieTest {
Object value2 = new Object(); Object value2 = new Object();
Object insertValue = new Object(); Object insertValue = new Object();
CollisionLeaf<Key, Object> leaf = CollisionLeaf<Key, Object> leaf =
new CollisionLeaf<Key, Object>(key1, value1, key2, value2); new CollisionLeaf<>(key1, value1, key2, value2);
Node<Key, Object> ret = leaf.put(insertKey, insertValue, insertKey.hashCode(), 0); Node<Key, Object> ret = leaf.put(insertKey, insertValue, insertKey.hashCode(), 0);
assertTrue(ret instanceof CompressedIndex); assertTrue(ret instanceof CompressedIndex);
@ -127,7 +127,7 @@ public class PersistentHashArrayMappedTrieTest {
Key key = new Key(replaceKey.hashCode()); Key key = new Key(replaceKey.hashCode());
Object value = new Object(); Object value = new Object();
CollisionLeaf<Key, Object> leaf = CollisionLeaf<Key, Object> leaf =
new CollisionLeaf<Key, Object>(replaceKey, originalValue, key, value); new CollisionLeaf<>(replaceKey, originalValue, key, value);
Object replaceValue = new Object(); Object replaceValue = new Object();
Node<Key, Object> ret = leaf.put(replaceKey, replaceValue, replaceKey.hashCode(), 0); Node<Key, Object> ret = leaf.put(replaceKey, replaceValue, replaceKey.hashCode(), 0);
assertTrue(ret instanceof CollisionLeaf); assertTrue(ret instanceof CollisionLeaf);
@ -150,7 +150,7 @@ public class PersistentHashArrayMappedTrieTest {
Object value2 = new Object(); Object value2 = new Object();
Object value3 = new Object(); Object value3 = new Object();
CollisionLeaf<Key, Object> leaf = CollisionLeaf<Key, Object> leaf =
new CollisionLeaf<Key, Object>(key1, value1, key2, value2); new CollisionLeaf<>(key1, value1, key2, value2);
Node<Key, Object> ret = leaf.put(key3, value3, key3.hashCode(), 0); Node<Key, Object> ret = leaf.put(key3, value3, key3.hashCode(), 0);
assertTrue(ret instanceof CollisionLeaf); assertTrue(ret instanceof CollisionLeaf);
@ -172,8 +172,8 @@ public class PersistentHashArrayMappedTrieTest {
final Key key2 = new Key(19); final Key key2 = new Key(19);
final Object value1 = new Object(); final Object value1 = new Object();
final Object value2 = new Object(); final Object value2 = new Object();
Leaf<Key, Object> leaf1 = new Leaf<Key, Object>(key1, value1); Leaf<Key, Object> leaf1 = new Leaf<>(key1, value1);
Leaf<Key, Object> leaf2 = new Leaf<Key, Object>(key2, value2); Leaf<Key, Object> leaf2 = new Leaf<>(key2, value2);
class Verifier { class Verifier {
private void verify(Node<Key, Object> ret) { private void verify(Node<Key, Object> ret) {
CompressedIndex<Key, Object> collisionLeaf = (CompressedIndex<Key, Object>) ret; CompressedIndex<Key, Object> collisionLeaf = (CompressedIndex<Key, Object>) ret;
@ -203,8 +203,8 @@ public class PersistentHashArrayMappedTrieTest {
final Key key2 = new Key(31 << 5 | 1); // 5 bit regions: (31, 1) final Key key2 = new Key(31 << 5 | 1); // 5 bit regions: (31, 1)
final Object value1 = new Object(); final Object value1 = new Object();
final Object value2 = new Object(); final Object value2 = new Object();
Leaf<Key, Object> leaf1 = new Leaf<Key, Object>(key1, value1); Leaf<Key, Object> leaf1 = new Leaf<>(key1, value1);
Leaf<Key, Object> leaf2 = new Leaf<Key, Object>(key2, value2); Leaf<Key, Object> leaf2 = new Leaf<>(key2, value2);
class Verifier { class Verifier {
private void verify(Node<Key, Object> ret) { private void verify(Node<Key, Object> ret) {
CompressedIndex<Key, Object> collisionInternal = (CompressedIndex<Key, Object>) ret; CompressedIndex<Key, Object> collisionInternal = (CompressedIndex<Key, Object>) ret;

View File

@ -49,7 +49,7 @@ public class CallOptionsBenchmark {
*/ */
@Setup @Setup
public void setUp() throws Exception { public void setUp() throws Exception {
customOptions = new ArrayList<CallOptions.Key<String>>(customOptionsCount); customOptions = new ArrayList<>(customOptionsCount);
for (int i = 0; i < customOptionsCount; i++) { for (int i = 0; i < customOptionsCount; i++) {
customOptions.add(CallOptions.Key.createWithDefault("name " + i, "defaultvalue")); customOptions.add(CallOptions.Key.createWithDefault("name " + i, "defaultvalue"));
} }
@ -59,7 +59,7 @@ public class CallOptionsBenchmark {
allOpts = allOpts.withOption(customOptions.get(i), "value"); allOpts = allOpts.withOption(customOptions.get(i), "value");
} }
shuffledCustomOptions = new ArrayList<CallOptions.Key<String>>(customOptions); shuffledCustomOptions = new ArrayList<>(customOptions);
// Make the shuffling deterministic // Make the shuffling deterministic
Collections.shuffle(shuffledCustomOptions, new Random(1)); Collections.shuffle(shuffledCustomOptions, new Random(1));
} }

View File

@ -40,7 +40,7 @@ public class StatsTraceContextBenchmark {
private final Metadata emptyMetadata = new Metadata(); private final Metadata emptyMetadata = new Metadata();
private final List<ServerStreamTracer.Factory> serverStreamTracerFactories = private final List<ServerStreamTracer.Factory> serverStreamTracerFactories =
Collections.<ServerStreamTracer.Factory>emptyList(); Collections.emptyList();
/** /**
* Javadoc comment. * Javadoc comment.

View File

@ -135,7 +135,7 @@ public final class Attributes {
*/ */
@Deprecated @Deprecated
public static <T> Key<T> of(String debugString) { public static <T> Key<T> of(String debugString) {
return new Key<T>(debugString); return new Key<>(debugString);
} }
/** /**
@ -146,7 +146,7 @@ public final class Attributes {
* @return Key object * @return Key object
*/ */
public static <T> Key<T> create(String debugString) { public static <T> Key<T> create(String debugString) {
return new Key<T>(debugString); return new Key<>(debugString);
} }
} }
@ -222,7 +222,7 @@ public final class Attributes {
private Map<Key<?>, Object> data(int size) { private Map<Key<?>, Object> data(int size) {
if (newdata == null) { if (newdata == null) {
newdata = new IdentityHashMap<Key<?>, Object>(size); newdata = new IdentityHashMap<>(size);
} }
return newdata; return newdata;
} }

View File

@ -216,7 +216,7 @@ public final class CallOptions {
public CallOptions withStreamTracerFactory(ClientStreamTracer.Factory factory) { public CallOptions withStreamTracerFactory(ClientStreamTracer.Factory factory) {
CallOptions newOptions = new CallOptions(this); CallOptions newOptions = new CallOptions(this);
ArrayList<ClientStreamTracer.Factory> newList = ArrayList<ClientStreamTracer.Factory> newList =
new ArrayList<ClientStreamTracer.Factory>(streamTracerFactories.size() + 1); new ArrayList<>(streamTracerFactories.size() + 1);
newList.addAll(streamTracerFactories); newList.addAll(streamTracerFactories);
newList.add(factory); newList.add(factory);
newOptions.streamTracerFactories = Collections.unmodifiableList(newList); newOptions.streamTracerFactories = Collections.unmodifiableList(newList);
@ -269,7 +269,7 @@ public final class CallOptions {
@Deprecated @Deprecated
public static <T> Key<T> of(String debugString, T defaultValue) { public static <T> Key<T> of(String debugString, T defaultValue) {
Preconditions.checkNotNull(debugString, "debugString"); Preconditions.checkNotNull(debugString, "debugString");
return new Key<T>(debugString, defaultValue); return new Key<>(debugString, defaultValue);
} }
/** /**
@ -283,7 +283,7 @@ public final class CallOptions {
*/ */
public static <T> Key<T> create(String debugString) { public static <T> Key<T> create(String debugString) {
Preconditions.checkNotNull(debugString, "debugString"); Preconditions.checkNotNull(debugString, "debugString");
return new Key<T>(debugString, /*defaultValue=*/ null); return new Key<>(debugString, /*defaultValue=*/ null);
} }
/** /**
@ -297,7 +297,7 @@ public final class CallOptions {
*/ */
public static <T> Key<T> createWithDefault(String debugString, T defaultValue) { public static <T> Key<T> createWithDefault(String debugString, T defaultValue) {
Preconditions.checkNotNull(debugString, "debugString"); Preconditions.checkNotNull(debugString, "debugString");
return new Key<T>(debugString, defaultValue); return new Key<>(debugString, defaultValue);
} }
} }

View File

@ -53,7 +53,7 @@ public final class CompressorRegistry {
@VisibleForTesting @VisibleForTesting
CompressorRegistry(Compressor ...cs) { CompressorRegistry(Compressor ...cs) {
compressors = new ConcurrentHashMap<String, Compressor>(); compressors = new ConcurrentHashMap<>();
for (Compressor c : cs) { for (Compressor c : cs) {
compressors.put(c.getMessageEncoding(), c); compressors.put(c.getMessageEncoding(), c);
} }

View File

@ -48,7 +48,7 @@ public final class Contexts {
ServerCallHandler<ReqT, RespT> next) { ServerCallHandler<ReqT, RespT> next) {
Context previous = context.attach(); Context previous = context.attach();
try { try {
return new ContextualizedServerCallListener<ReqT>( return new ContextualizedServerCallListener<>(
next.startCall(call, headers), next.startCall(call, headers),
context); context);
} finally { } finally {

View File

@ -74,7 +74,7 @@ public final class DecompressorRegistry {
newSize++; newSize++;
} }
Map<String, DecompressorInfo> newDecompressors = Map<String, DecompressorInfo> newDecompressors =
new LinkedHashMap<String, DecompressorInfo>(newSize); new LinkedHashMap<>(newSize);
for (DecompressorInfo di : parent.decompressors.values()) { for (DecompressorInfo di : parent.decompressors.values()) {
String previousEncoding = di.decompressor.getMessageEncoding(); String previousEncoding = di.decompressor.getMessageEncoding();
if (!previousEncoding.equals(encoding)) { if (!previousEncoding.equals(encoding)) {
@ -90,7 +90,7 @@ public final class DecompressorRegistry {
} }
private DecompressorRegistry() { private DecompressorRegistry() {
decompressors = new LinkedHashMap<String, DecompressorInfo>(0); decompressors = new LinkedHashMap<>(0);
advertisedDecompressors = new byte[0]; advertisedDecompressors = new byte[0];
} }
@ -115,7 +115,7 @@ public final class DecompressorRegistry {
*/ */
@ExperimentalApi("https://github.com/grpc/grpc-java/issues/1704") @ExperimentalApi("https://github.com/grpc/grpc-java/issues/1704")
public Set<String> getAdvertisedMessageEncodings() { public Set<String> getAdvertisedMessageEncodings() {
Set<String> advertisedDecompressors = new HashSet<String>(decompressors.size()); Set<String> advertisedDecompressors = new HashSet<>(decompressors.size());
for (Entry<String, DecompressorInfo> entry : decompressors.entrySet()) { for (Entry<String, DecompressorInfo> entry : decompressors.entrySet()) {
if (entry.getValue().advertised) { if (entry.getValue().advertised) {
advertisedDecompressors.add(entry.getKey()); advertisedDecompressors.add(entry.getKey());

View File

@ -50,16 +50,16 @@ public final class InternalChannelz {
private static final InternalChannelz INSTANCE = new InternalChannelz(); private static final InternalChannelz INSTANCE = new InternalChannelz();
private final ConcurrentNavigableMap<Long, InternalInstrumented<ServerStats>> servers private final ConcurrentNavigableMap<Long, InternalInstrumented<ServerStats>> servers
= new ConcurrentSkipListMap<Long, InternalInstrumented<ServerStats>>(); = new ConcurrentSkipListMap<>();
private final ConcurrentNavigableMap<Long, InternalInstrumented<ChannelStats>> rootChannels private final ConcurrentNavigableMap<Long, InternalInstrumented<ChannelStats>> rootChannels
= new ConcurrentSkipListMap<Long, InternalInstrumented<ChannelStats>>(); = new ConcurrentSkipListMap<>();
private final ConcurrentMap<Long, InternalInstrumented<ChannelStats>> subchannels private final ConcurrentMap<Long, InternalInstrumented<ChannelStats>> subchannels
= new ConcurrentHashMap<Long, InternalInstrumented<ChannelStats>>(); = new ConcurrentHashMap<>();
// An InProcessTransport can appear in both otherSockets and perServerSockets simultaneously // An InProcessTransport can appear in both otherSockets and perServerSockets simultaneously
private final ConcurrentMap<Long, InternalInstrumented<SocketStats>> otherSockets private final ConcurrentMap<Long, InternalInstrumented<SocketStats>> otherSockets
= new ConcurrentHashMap<Long, InternalInstrumented<SocketStats>>(); = new ConcurrentHashMap<>();
private final ConcurrentMap<Long, ServerSocketMap> perServerSockets private final ConcurrentMap<Long, ServerSocketMap> perServerSockets
= new ConcurrentHashMap<Long, ServerSocketMap>(); = new ConcurrentHashMap<>();
// A convenience class to avoid deeply nested types. // A convenience class to avoid deeply nested types.
private static final class ServerSocketMap private static final class ServerSocketMap
@ -144,7 +144,7 @@ public final class InternalChannelz {
/** Returns a {@link RootChannelList}. */ /** Returns a {@link RootChannelList}. */
public RootChannelList getRootChannels(long fromId, int maxPageSize) { public RootChannelList getRootChannels(long fromId, int maxPageSize) {
List<InternalInstrumented<ChannelStats>> channelList List<InternalInstrumented<ChannelStats>> channelList
= new ArrayList<InternalInstrumented<ChannelStats>>(); = new ArrayList<>();
Iterator<InternalInstrumented<ChannelStats>> iterator Iterator<InternalInstrumented<ChannelStats>> iterator
= rootChannels.tailMap(fromId).values().iterator(); = rootChannels.tailMap(fromId).values().iterator();
@ -169,7 +169,7 @@ public final class InternalChannelz {
/** Returns a server list. */ /** Returns a server list. */
public ServerList getServers(long fromId, int maxPageSize) { public ServerList getServers(long fromId, int maxPageSize) {
List<InternalInstrumented<ServerStats>> serverList List<InternalInstrumented<ServerStats>> serverList
= new ArrayList<InternalInstrumented<ServerStats>>(maxPageSize); = new ArrayList<>(maxPageSize);
Iterator<InternalInstrumented<ServerStats>> iterator Iterator<InternalInstrumented<ServerStats>> iterator
= servers.tailMap(fromId).values().iterator(); = servers.tailMap(fromId).values().iterator();
@ -992,11 +992,11 @@ public final class InternalChannelz {
this.soTimeoutMillis = timeoutMillis; this.soTimeoutMillis = timeoutMillis;
this.lingerSeconds = lingerSeconds; this.lingerSeconds = lingerSeconds;
this.tcpInfo = tcpInfo; this.tcpInfo = tcpInfo;
this.others = Collections.unmodifiableMap(new HashMap<String, String>(others)); this.others = Collections.unmodifiableMap(new HashMap<>(others));
} }
public static final class Builder { public static final class Builder {
private final Map<String, String> others = new HashMap<String, String>(); private final Map<String, String> others = new HashMap<>();
private TcpInfo tcpInfo; private TcpInfo tcpInfo;
private Integer timeoutMillis; private Integer timeoutMillis;

View File

@ -45,9 +45,9 @@ public final class LoadBalancerRegistry {
private static final Iterable<Class<?>> HARDCODED_CLASSES = getHardCodedClasses(); private static final Iterable<Class<?>> HARDCODED_CLASSES = getHardCodedClasses();
private final LinkedHashSet<LoadBalancerProvider> allProviders = private final LinkedHashSet<LoadBalancerProvider> allProviders =
new LinkedHashSet<LoadBalancerProvider>(); new LinkedHashSet<>();
private final LinkedHashMap<String, LoadBalancerProvider> effectiveProviders = private final LinkedHashMap<String, LoadBalancerProvider> effectiveProviders =
new LinkedHashMap<String, LoadBalancerProvider>(); new LinkedHashMap<>();
/** /**
* Register a provider. * Register a provider.
@ -131,7 +131,7 @@ public final class LoadBalancerRegistry {
*/ */
@VisibleForTesting @VisibleForTesting
synchronized Map<String, LoadBalancerProvider> providers() { synchronized Map<String, LoadBalancerProvider> providers() {
return new LinkedHashMap<String, LoadBalancerProvider>(effectiveProviders); return new LinkedHashMap<>(effectiveProviders);
} }
@VisibleForTesting @VisibleForTesting
@ -139,7 +139,7 @@ public final class LoadBalancerRegistry {
// Class.forName(String) is used to remove the need for ProGuard configuration. Note that // Class.forName(String) is used to remove the need for ProGuard configuration. Note that
// ProGuard does not detect usages of Class.forName(String, boolean, ClassLoader): // ProGuard does not detect usages of Class.forName(String, boolean, ClassLoader):
// https://sourceforge.net/p/proguard/bugs/418/ // https://sourceforge.net/p/proguard/bugs/418/
ArrayList<Class<?>> list = new ArrayList<Class<?>>(); ArrayList<Class<?>> list = new ArrayList<>();
try { try {
list.add(Class.forName("io.grpc.internal.PickFirstLoadBalancerProvider")); list.add(Class.forName("io.grpc.internal.PickFirstLoadBalancerProvider"));
} catch (ClassNotFoundException e) { } catch (ClassNotFoundException e) {

View File

@ -102,7 +102,7 @@ public abstract class ManagedChannelProvider {
private static final class HardcodedClasses implements Iterable<Class<?>> { private static final class HardcodedClasses implements Iterable<Class<?>> {
@Override @Override
public Iterator<Class<?>> iterator() { public Iterator<Class<?>> iterator() {
List<Class<?>> list = new ArrayList<Class<?>>(); List<Class<?>> list = new ArrayList<>();
try { try {
list.add(Class.forName("io.grpc.okhttp.OkHttpChannelProvider")); list.add(Class.forName("io.grpc.okhttp.OkHttpChannelProvider"));
} catch (ClassNotFoundException ex) { } catch (ClassNotFoundException ex) {

View File

@ -253,7 +253,7 @@ public final class Metadata {
public <T> Iterable<T> getAll(final Key<T> key) { public <T> Iterable<T> getAll(final Key<T> key) {
for (int i = 0; i < size; i++) { for (int i = 0; i < size; i++) {
if (bytesEqual(key.asciiName(), name(i))) { if (bytesEqual(key.asciiName(), name(i))) {
return new IterableAt<T>(key, i); return new IterableAt<>(key, i);
} }
} }
return null; return null;
@ -269,7 +269,7 @@ public final class Metadata {
if (isEmpty()) { if (isEmpty()) {
return Collections.emptySet(); return Collections.emptySet();
} }
Set<String> ks = new HashSet<String>(size); Set<String> ks = new HashSet<>(size);
for (int i = 0; i < size; i++) { for (int i = 0; i < size; i++) {
ks.add(new String(name(i), 0 /* hibyte */)); ks.add(new String(name(i), 0 /* hibyte */));
} }
@ -442,7 +442,7 @@ public final class Metadata {
public void merge(Metadata other, Set<Key<?>> keys) { public void merge(Metadata other, Set<Key<?>> keys) {
Preconditions.checkNotNull(other, "other"); Preconditions.checkNotNull(other, "other");
// Use ByteBuffer for equals and hashCode. // Use ByteBuffer for equals and hashCode.
Map<ByteBuffer, Key<?>> asciiKeys = new HashMap<ByteBuffer, Key<?>>(keys.size()); Map<ByteBuffer, Key<?>> asciiKeys = new HashMap<>(keys.size());
for (Key<?> key : keys) { for (Key<?> key : keys) {
asciiKeys.put(ByteBuffer.wrap(key.asciiName()), key); asciiKeys.put(ByteBuffer.wrap(key.asciiName()), key);
} }
@ -576,7 +576,7 @@ public final class Metadata {
* end with {@link #BINARY_HEADER_SUFFIX}. * end with {@link #BINARY_HEADER_SUFFIX}.
*/ */
public static <T> Key<T> of(String name, BinaryMarshaller<T> marshaller) { public static <T> Key<T> of(String name, BinaryMarshaller<T> marshaller) {
return new BinaryKey<T>(name, marshaller); return new BinaryKey<>(name, marshaller);
} }
/** /**
@ -590,11 +590,11 @@ public final class Metadata {
} }
static <T> Key<T> of(String name, boolean pseudo, AsciiMarshaller<T> marshaller) { static <T> Key<T> of(String name, boolean pseudo, AsciiMarshaller<T> marshaller) {
return new AsciiKey<T>(name, pseudo, marshaller); return new AsciiKey<>(name, pseudo, marshaller);
} }
static <T> Key<T> of(String name, boolean pseudo, TrustedAsciiMarshaller<T> marshaller) { static <T> Key<T> of(String name, boolean pseudo, TrustedAsciiMarshaller<T> marshaller) {
return new TrustedAsciiKey<T>(name, pseudo, marshaller); return new TrustedAsciiKey<>(name, pseudo, marshaller);
} }
private final String originalName; private final String originalName;

View File

@ -50,7 +50,7 @@ public final class MethodDescriptor<ReqT, RespT> {
// Must be set to InternalKnownTransport.values().length // Must be set to InternalKnownTransport.values().length
// Not referenced to break the dependency. // Not referenced to break the dependency.
private final AtomicReferenceArray<Object> rawMethodNames = new AtomicReferenceArray<Object>(1); private final AtomicReferenceArray<Object> rawMethodNames = new AtomicReferenceArray<>(1);
/** /**
@ -211,7 +211,7 @@ public final class MethodDescriptor<ReqT, RespT> {
MethodType type, String fullMethodName, MethodType type, String fullMethodName,
Marshaller<RequestT> requestMarshaller, Marshaller<RequestT> requestMarshaller,
Marshaller<ResponseT> responseMarshaller) { Marshaller<ResponseT> responseMarshaller) {
return new MethodDescriptor<RequestT, ResponseT>( return new MethodDescriptor<>(
type, fullMethodName, requestMarshaller, responseMarshaller, null, false, false, false); type, fullMethodName, requestMarshaller, responseMarshaller, null, false, false, false);
} }
@ -564,7 +564,7 @@ public final class MethodDescriptor<ReqT, RespT> {
*/ */
@CheckReturnValue @CheckReturnValue
public MethodDescriptor<ReqT, RespT> build() { public MethodDescriptor<ReqT, RespT> build() {
return new MethodDescriptor<ReqT, RespT>( return new MethodDescriptor<>(
type, type,
fullMethodName, fullMethodName,
requestMarshaller, requestMarshaller,

View File

@ -175,9 +175,9 @@ public final class ServerInterceptors {
final ServerServiceDefinition serviceDef, final ServerServiceDefinition serviceDef,
final MethodDescriptor.Marshaller<T> marshaller) { final MethodDescriptor.Marshaller<T> marshaller) {
List<ServerMethodDefinition<?, ?>> wrappedMethods = List<ServerMethodDefinition<?, ?>> wrappedMethods =
new ArrayList<ServerMethodDefinition<?, ?>>(); new ArrayList<>();
List<MethodDescriptor<?, ?>> wrappedDescriptors = List<MethodDescriptor<?, ?>> wrappedDescriptors =
new ArrayList<MethodDescriptor<?, ?>>(); new ArrayList<>();
// Wrap the descriptors // Wrap the descriptors
for (final ServerMethodDefinition<?, ?> definition : serviceDef.getMethods()) { for (final ServerMethodDefinition<?, ?> definition : serviceDef.getMethods()) {
final MethodDescriptor<?, ?> originalMethodDescriptor = definition.getMethodDescriptor(); final MethodDescriptor<?, ?> originalMethodDescriptor = definition.getMethodDescriptor();
@ -210,7 +210,7 @@ public final class ServerInterceptors {
static final class InterceptCallHandler<ReqT, RespT> implements ServerCallHandler<ReqT, RespT> { static final class InterceptCallHandler<ReqT, RespT> implements ServerCallHandler<ReqT, RespT> {
public static <ReqT, RespT> InterceptCallHandler<ReqT, RespT> create( public static <ReqT, RespT> InterceptCallHandler<ReqT, RespT> create(
ServerInterceptor interceptor, ServerCallHandler<ReqT, RespT> callHandler) { ServerInterceptor interceptor, ServerCallHandler<ReqT, RespT> callHandler) {
return new InterceptCallHandler<ReqT, RespT>(interceptor, callHandler); return new InterceptCallHandler<>(interceptor, callHandler);
} }
private final ServerInterceptor interceptor; private final ServerInterceptor interceptor;

View File

@ -41,7 +41,7 @@ public final class ServerMethodDefinition<ReqT, RespT> {
public static <ReqT, RespT> ServerMethodDefinition<ReqT, RespT> create( public static <ReqT, RespT> ServerMethodDefinition<ReqT, RespT> create(
MethodDescriptor<ReqT, RespT> method, MethodDescriptor<ReqT, RespT> method,
ServerCallHandler<ReqT, RespT> handler) { ServerCallHandler<ReqT, RespT> handler) {
return new ServerMethodDefinition<ReqT, RespT>(method, handler); return new ServerMethodDefinition<>(method, handler);
} }
/** The {@code MethodDescriptor} for this method. */ /** The {@code MethodDescriptor} for this method. */
@ -62,6 +62,6 @@ public final class ServerMethodDefinition<ReqT, RespT> {
*/ */
public ServerMethodDefinition<ReqT, RespT> withServerCallHandler( public ServerMethodDefinition<ReqT, RespT> withServerCallHandler(
ServerCallHandler<ReqT, RespT> handler) { ServerCallHandler<ReqT, RespT> handler) {
return new ServerMethodDefinition<ReqT, RespT>(method, handler); return new ServerMethodDefinition<>(method, handler);
} }
} }

View File

@ -44,8 +44,7 @@ public final class ServerServiceDefinition {
private ServerServiceDefinition( private ServerServiceDefinition(
ServiceDescriptor serviceDescriptor, Map<String, ServerMethodDefinition<?, ?>> methods) { ServiceDescriptor serviceDescriptor, Map<String, ServerMethodDefinition<?, ?>> methods) {
this.serviceDescriptor = checkNotNull(serviceDescriptor, "serviceDescriptor"); this.serviceDescriptor = checkNotNull(serviceDescriptor, "serviceDescriptor");
this.methods = this.methods = Collections.unmodifiableMap(new HashMap<>(methods));
Collections.unmodifiableMap(new HashMap<String, ServerMethodDefinition<?, ?>>(methods));
} }
/** /**
@ -78,8 +77,7 @@ public final class ServerServiceDefinition {
public static final class Builder { public static final class Builder {
private final String serviceName; private final String serviceName;
private final ServiceDescriptor serviceDescriptor; private final ServiceDescriptor serviceDescriptor;
private final Map<String, ServerMethodDefinition<?, ?>> methods = private final Map<String, ServerMethodDefinition<?, ?>> methods = new HashMap<>();
new HashMap<String, ServerMethodDefinition<?, ?>>();
private Builder(String serviceName) { private Builder(String serviceName) {
this.serviceName = checkNotNull(serviceName, "serviceName"); this.serviceName = checkNotNull(serviceName, "serviceName");
@ -125,14 +123,13 @@ public final class ServerServiceDefinition {
ServiceDescriptor serviceDescriptor = this.serviceDescriptor; ServiceDescriptor serviceDescriptor = this.serviceDescriptor;
if (serviceDescriptor == null) { if (serviceDescriptor == null) {
List<MethodDescriptor<?, ?>> methodDescriptors List<MethodDescriptor<?, ?>> methodDescriptors
= new ArrayList<MethodDescriptor<?, ?>>(methods.size()); = new ArrayList<>(methods.size());
for (ServerMethodDefinition<?, ?> serverMethod : methods.values()) { for (ServerMethodDefinition<?, ?> serverMethod : methods.values()) {
methodDescriptors.add(serverMethod.getMethodDescriptor()); methodDescriptors.add(serverMethod.getMethodDescriptor());
} }
serviceDescriptor = new ServiceDescriptor(serviceName, methodDescriptors); serviceDescriptor = new ServiceDescriptor(serviceName, methodDescriptors);
} }
Map<String, ServerMethodDefinition<?, ?>> tmpMethods = Map<String, ServerMethodDefinition<?, ?>> tmpMethods = new HashMap<>(methods);
new HashMap<String, ServerMethodDefinition<?, ?>>(methods);
for (MethodDescriptor<?, ?> descriptorMethod : serviceDescriptor.getMethods()) { for (MethodDescriptor<?, ?> descriptorMethod : serviceDescriptor.getMethods()) {
ServerMethodDefinition<?, ?> removed = tmpMethods.remove( ServerMethodDefinition<?, ?> removed = tmpMethods.remove(
descriptorMethod.getFullMethodName()); descriptorMethod.getFullMethodName());

View File

@ -94,7 +94,7 @@ public abstract class ServerStreamTracer extends StreamTracer {
private static <ReqT, RespT> ReadOnlyServerCall<ReqT, RespT> create( private static <ReqT, RespT> ReadOnlyServerCall<ReqT, RespT> create(
ServerCallInfo<ReqT, RespT> callInfo) { ServerCallInfo<ReqT, RespT> callInfo) {
return new ReadOnlyServerCall<ReqT, RespT>(callInfo); return new ReadOnlyServerCall<>(callInfo);
} }
private ReadOnlyServerCall(ServerCallInfo<ReqT, RespT> callInfo) { private ReadOnlyServerCall(ServerCallInfo<ReqT, RespT> callInfo) {

View File

@ -67,7 +67,7 @@ public final class ServiceDescriptor {
private ServiceDescriptor(Builder b) { private ServiceDescriptor(Builder b) {
this.name = b.name; this.name = b.name;
validateMethodNames(name, b.methods); validateMethodNames(name, b.methods);
this.methods = Collections.unmodifiableList(new ArrayList<MethodDescriptor<?, ?>>(b.methods)); this.methods = Collections.unmodifiableList(new ArrayList<>(b.methods));
this.schemaDescriptor = b.schemaDescriptor; this.schemaDescriptor = b.schemaDescriptor;
} }
@ -107,7 +107,7 @@ public final class ServiceDescriptor {
} }
static void validateMethodNames(String serviceName, Collection<MethodDescriptor<?, ?>> methods) { static void validateMethodNames(String serviceName, Collection<MethodDescriptor<?, ?>> methods) {
Set<String> allNames = new HashSet<String>(methods.size()); Set<String> allNames = new HashSet<>(methods.size());
for (MethodDescriptor<?, ?> method : methods) { for (MethodDescriptor<?, ?> method : methods) {
checkNotNull(method, "method"); checkNotNull(method, "method");
String methodServiceName = String methodServiceName =
@ -139,7 +139,7 @@ public final class ServiceDescriptor {
} }
private String name; private String name;
private List<MethodDescriptor<?, ?>> methods = new ArrayList<MethodDescriptor<?, ?>>(); private List<MethodDescriptor<?, ?>> methods = new ArrayList<>();
private Object schemaDescriptor; private Object schemaDescriptor;
/** /**

View File

@ -234,7 +234,7 @@ public final class Status {
private static final List<Status> STATUS_LIST = buildStatusList(); private static final List<Status> STATUS_LIST = buildStatusList();
private static List<Status> buildStatusList() { private static List<Status> buildStatusList() {
TreeMap<Integer, Status> canonicalizer = new TreeMap<Integer, Status>(); TreeMap<Integer, Status> canonicalizer = new TreeMap<>();
for (Code code : Code.values()) { for (Code code : Code.values()) {
Status replaced = canonicalizer.put(code.value(), new Status(code)); Status replaced = canonicalizer.put(code.value(), new Status(code));
if (replaced != null) { if (replaced != null) {

View File

@ -56,7 +56,7 @@ public final class SynchronizationContext implements Executor {
private final UncaughtExceptionHandler uncaughtExceptionHandler; private final UncaughtExceptionHandler uncaughtExceptionHandler;
@GuardedBy("lock") @GuardedBy("lock")
private final Queue<Runnable> queue = new ArrayDeque<Runnable>(); private final Queue<Runnable> queue = new ArrayDeque<>();
@GuardedBy("lock") @GuardedBy("lock")
private Thread drainingThread; private Thread drainingThread;

View File

@ -37,7 +37,7 @@ import javax.annotation.concurrent.ThreadSafe;
@ThreadSafe @ThreadSafe
final class InProcessServer implements InternalServer { final class InProcessServer implements InternalServer {
private static final ConcurrentMap<String, InProcessServer> registry private static final ConcurrentMap<String, InProcessServer> registry
= new ConcurrentHashMap<String, InProcessServer>(); = new ConcurrentHashMap<>();
static InProcessServer findServer(String name) { static InProcessServer findServer(String name) {
return registry.get(name); return registry.get(name);

View File

@ -120,7 +120,7 @@ public final class InProcessServerBuilder
*/ */
public InProcessServerBuilder scheduledExecutorService( public InProcessServerBuilder scheduledExecutorService(
ScheduledExecutorService scheduledExecutorService) { ScheduledExecutorService scheduledExecutorService) {
schedulerPool = new FixedObjectPool<ScheduledExecutorService>( schedulerPool = new FixedObjectPool<>(
checkNotNull(scheduledExecutorService, "scheduledExecutorService")); checkNotNull(scheduledExecutorService, "scheduledExecutorService"));
return this; return this;
} }

View File

@ -91,7 +91,7 @@ final class InProcessTransport implements ServerTransport, ConnectionClientTrans
@GuardedBy("this") @GuardedBy("this")
private Status shutdownStatus; private Status shutdownStatus;
@GuardedBy("this") @GuardedBy("this")
private Set<InProcessStream> streams = new HashSet<InProcessStream>(); private Set<InProcessStream> streams = new HashSet<>();
@GuardedBy("this") @GuardedBy("this")
private List<ServerStreamTracer.Factory> serverStreamTracerFactories; private List<ServerStreamTracer.Factory> serverStreamTracerFactories;
private final Attributes attributes = Attributes.newBuilder() private final Attributes attributes = Attributes.newBuilder()
@ -368,7 +368,7 @@ final class InProcessTransport implements ServerTransport, ConnectionClientTrans
private int clientRequested; private int clientRequested;
@GuardedBy("this") @GuardedBy("this")
private ArrayDeque<StreamListener.MessageProducer> clientReceiveQueue = private ArrayDeque<StreamListener.MessageProducer> clientReceiveQueue =
new ArrayDeque<StreamListener.MessageProducer>(); new ArrayDeque<>();
@GuardedBy("this") @GuardedBy("this")
private Status clientNotifyStatus; private Status clientNotifyStatus;
@GuardedBy("this") @GuardedBy("this")
@ -614,7 +614,7 @@ final class InProcessTransport implements ServerTransport, ConnectionClientTrans
private int serverRequested; private int serverRequested;
@GuardedBy("this") @GuardedBy("this")
private ArrayDeque<StreamListener.MessageProducer> serverReceiveQueue = private ArrayDeque<StreamListener.MessageProducer> serverReceiveQueue =
new ArrayDeque<StreamListener.MessageProducer>(); new ArrayDeque<>();
@GuardedBy("this") @GuardedBy("this")
private boolean serverNotifyHalfClose; private boolean serverNotifyHalfClose;
// Only is intended to prevent double-close when server closes. // Only is intended to prevent double-close when server closes.

View File

@ -209,7 +209,7 @@ public abstract class AbstractManagedChannelImplBuilder
@Override @Override
public final T executor(Executor executor) { public final T executor(Executor executor) {
if (executor != null) { if (executor != null) {
this.executorPool = new FixedObjectPool<Executor>(executor); this.executorPool = new FixedObjectPool<>(executor);
} else { } else {
this.executorPool = DEFAULT_EXECUTOR_POOL; this.executorPool = DEFAULT_EXECUTOR_POOL;
} }

View File

@ -41,7 +41,7 @@ public class ApplicationThreadDeframer implements Deframer, MessageDeframer.List
private final TransportExecutor transportExecutor; private final TransportExecutor transportExecutor;
/** Queue for messages returned by the deframer when deframing in the application thread. */ /** Queue for messages returned by the deframer when deframing in the application thread. */
private final Queue<InputStream> messageReadQueue = new ArrayDeque<InputStream>(); private final Queue<InputStream> messageReadQueue = new ArrayDeque<>();
ApplicationThreadDeframer( ApplicationThreadDeframer(
MessageDeframer.Listener listener, MessageDeframer.Listener listener,

View File

@ -33,7 +33,7 @@ import java.util.Queue;
public class CompositeReadableBuffer extends AbstractReadableBuffer { public class CompositeReadableBuffer extends AbstractReadableBuffer {
private int readableBytes; private int readableBytes;
private final Queue<ReadableBuffer> buffers = new ArrayDeque<ReadableBuffer>(); private final Queue<ReadableBuffer> buffers = new ArrayDeque<>();
/** /**
* Adds a new {@link ReadableBuffer} at the end of the buffer list. After a buffer is added, it is * Adds a new {@link ReadableBuffer} at the end of the buffer list. After a buffer is added, it is

View File

@ -65,7 +65,7 @@ final class DelayedClientTransport implements ManagedClientTransport {
@Nonnull @Nonnull
@GuardedBy("lock") @GuardedBy("lock")
private Collection<PendingStream> pendingStreams = new LinkedHashSet<PendingStream>(); private Collection<PendingStream> pendingStreams = new LinkedHashSet<>();
/** /**
* When {@code shutdownStatus != null && !hasPendingStreams()}, then the transport is considered * When {@code shutdownStatus != null && !hasPendingStreams()}, then the transport is considered
@ -240,7 +240,7 @@ final class DelayedClientTransport implements ManagedClientTransport {
savedReportTransportTerminated = reportTransportTerminated; savedReportTransportTerminated = reportTransportTerminated;
reportTransportTerminated = null; reportTransportTerminated = null;
if (!pendingStreams.isEmpty()) { if (!pendingStreams.isEmpty()) {
pendingStreams = Collections.<PendingStream>emptyList(); pendingStreams = Collections.emptyList();
} }
} }
if (savedReportTransportTerminated != null) { if (savedReportTransportTerminated != null) {
@ -322,7 +322,7 @@ final class DelayedClientTransport implements ManagedClientTransport {
// Because delayed transport is long-lived, we take this opportunity to down-size the // Because delayed transport is long-lived, we take this opportunity to down-size the
// hashmap. // hashmap.
if (pendingStreams.isEmpty()) { if (pendingStreams.isEmpty()) {
pendingStreams = new LinkedHashSet<PendingStream>(); pendingStreams = new LinkedHashSet<>();
} }
if (!hasPendingStreams()) { if (!hasPendingStreams()) {
// There may be a brief gap between delayed transport clearing in-use state, and first real // There may be a brief gap between delayed transport clearing in-use state, and first real

View File

@ -417,7 +417,7 @@ final class DnsNameResolver extends NameResolver {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@VisibleForTesting @VisibleForTesting
static List<Map<String, Object>> parseTxtResults(List<String> txtRecords) { static List<Map<String, Object>> parseTxtResults(List<String> txtRecords) {
List<Map<String, Object>> serviceConfigs = new ArrayList<Map<String, Object>>(); List<Map<String, Object>> serviceConfigs = new ArrayList<>();
for (String txtRecord : txtRecords) { for (String txtRecord : txtRecords) {
if (txtRecord.startsWith(SERVICE_CONFIG_PREFIX)) { if (txtRecord.startsWith(SERVICE_CONFIG_PREFIX)) {
List<Map<String, Object>> choices; List<Map<String, Object>> choices;

View File

@ -51,7 +51,7 @@ public class Http2Ping {
* The registered callbacks and the executor used to invoke them. * The registered callbacks and the executor used to invoke them.
*/ */
@GuardedBy("this") private Map<PingCallback, Executor> callbacks @GuardedBy("this") private Map<PingCallback, Executor> callbacks
= new LinkedHashMap<PingCallback, Executor>(); = new LinkedHashMap<>();
/** /**
* False until the operation completes, either successfully (other side sent acknowledgement) or * False until the operation completes, either successfully (other side sent acknowledgement) or

View File

@ -25,7 +25,7 @@ import javax.annotation.concurrent.NotThreadSafe;
@NotThreadSafe @NotThreadSafe
public abstract class InUseStateAggregator<T> { public abstract class InUseStateAggregator<T> {
private final HashSet<T> inUseObjects = new HashSet<T>(); private final HashSet<T> inUseObjects = new HashSet<>();
/** /**
* Update the in-use state of an object. Initially no object is in use. * Update the in-use state of an object. Initially no object is in use.

View File

@ -57,7 +57,7 @@ final class InternalHandlerRegistry extends HandlerRegistry {
// Store per-service first, to make sure services are added/replaced atomically. // Store per-service first, to make sure services are added/replaced atomically.
private final HashMap<String, ServerServiceDefinition> services = private final HashMap<String, ServerServiceDefinition> services =
new LinkedHashMap<String, ServerServiceDefinition>(); new LinkedHashMap<>();
Builder addService(ServerServiceDefinition service) { Builder addService(ServerServiceDefinition service) {
services.put(service.getServiceDescriptor().getName(), service); services.put(service.getServiceDescriptor().getName(), service);
@ -66,7 +66,7 @@ final class InternalHandlerRegistry extends HandlerRegistry {
InternalHandlerRegistry build() { InternalHandlerRegistry build() {
Map<String, ServerMethodDefinition<?, ?>> map = Map<String, ServerMethodDefinition<?, ?>> map =
new HashMap<String, ServerMethodDefinition<?, ?>>(); new HashMap<>();
for (ServerServiceDefinition service : services.values()) { for (ServerServiceDefinition service : services.values()) {
for (ServerMethodDefinition<?, ?> method : service.getMethods()) { for (ServerMethodDefinition<?, ?> method : service.getMethods()) {
map.put(method.getMethodDescriptor().getFullMethodName(), method); map.put(method.getMethodDescriptor().getFullMethodName(), method);

View File

@ -251,7 +251,7 @@ final class JndiResourceResolverFactory implements DnsNameResolver.ResourceResol
List<String> records = new ArrayList<>(); List<String> records = new ArrayList<>();
@SuppressWarnings("JdkObsolete") @SuppressWarnings("JdkObsolete")
Hashtable<String, String> env = new Hashtable<String, String>(); Hashtable<String, String> env = new Hashtable<>();
env.put("com.sun.jndi.ldap.connect.timeout", "5000"); env.put("com.sun.jndi.ldap.connect.timeout", "5000");
env.put("com.sun.jndi.ldap.read.timeout", "5000"); env.put("com.sun.jndi.ldap.read.timeout", "5000");
DirContext dirContext = new InitialDirContext(env); DirContext dirContext = new InitialDirContext(env);

View File

@ -79,7 +79,7 @@ public final class JsonParser {
private static Map<String, Object> parseJsonObject(JsonReader jr) throws IOException { private static Map<String, Object> parseJsonObject(JsonReader jr) throws IOException {
jr.beginObject(); jr.beginObject();
Map<String, Object> obj = new LinkedHashMap<String, Object>(); Map<String, Object> obj = new LinkedHashMap<>();
while (jr.hasNext()) { while (jr.hasNext()) {
String name = jr.nextName(); String name = jr.nextName();
Object value = parseRecursive(jr); Object value = parseRecursive(jr);

View File

@ -195,10 +195,10 @@ final class ManagedChannelImpl extends ManagedChannel implements
// Must be mutated from syncContext // Must be mutated from syncContext
// If any monitoring hook to be added later needs to get a snapshot of this Set, we could // If any monitoring hook to be added later needs to get a snapshot of this Set, we could
// switch to a ConcurrentHashMap. // switch to a ConcurrentHashMap.
private final Set<InternalSubchannel> subchannels = new HashSet<InternalSubchannel>(16, .75f); private final Set<InternalSubchannel> subchannels = new HashSet<>(16, .75f);
// Must be mutated from syncContext // Must be mutated from syncContext
private final Set<OobChannel> oobChannels = new HashSet<OobChannel>(1, .75f); private final Set<OobChannel> oobChannels = new HashSet<>(1, .75f);
// reprocess() must be run from syncContext // reprocess() must be run from syncContext
private final DelayedClientTransport delayedTransport; private final DelayedClientTransport delayedTransport;
@ -815,14 +815,14 @@ final class ManagedChannelImpl extends ManagedChannel implements
@Override @Override
public <ReqT, RespT> ClientCall<ReqT, RespT> newCall(MethodDescriptor<ReqT, RespT> method, public <ReqT, RespT> ClientCall<ReqT, RespT> newCall(MethodDescriptor<ReqT, RespT> method,
CallOptions callOptions) { CallOptions callOptions) {
return new ClientCallImpl<ReqT, RespT>( return new ClientCallImpl<>(
method, method,
getCallExecutor(callOptions), getCallExecutor(callOptions),
callOptions, callOptions,
transportProvider, transportProvider,
terminated ? null : transportFactory.getScheduledExecutorService(), terminated ? null : transportFactory.getScheduledExecutorService(),
channelCallTracer, channelCallTracer,
retryEnabled) retryEnabled)
.setFullStreamDecompression(fullStreamDecompression) .setFullStreamDecompression(fullStreamDecompression)
.setDecompressorRegistry(decompressorRegistry) .setDecompressorRegistry(decompressorRegistry)
.setCompressorRegistry(compressorRegistry); .setCompressorRegistry(compressorRegistry);

View File

@ -30,10 +30,10 @@ import java.util.logging.Logger;
final class ManagedChannelOrphanWrapper extends ForwardingManagedChannel { final class ManagedChannelOrphanWrapper extends ForwardingManagedChannel {
private static final ReferenceQueue<ManagedChannelOrphanWrapper> refqueue = private static final ReferenceQueue<ManagedChannelOrphanWrapper> refqueue =
new ReferenceQueue<ManagedChannelOrphanWrapper>(); new ReferenceQueue<>();
// Retain the References so they don't get GC'd // Retain the References so they don't get GC'd
private static final ConcurrentMap<ManagedChannelReference, ManagedChannelReference> refs = private static final ConcurrentMap<ManagedChannelReference, ManagedChannelReference> refs =
new ConcurrentHashMap<ManagedChannelReference, ManagedChannelReference>(); new ConcurrentHashMap<>();
private static final Logger logger = private static final Logger logger =
Logger.getLogger(ManagedChannelOrphanWrapper.class.getName()); Logger.getLogger(ManagedChannelOrphanWrapper.class.getName());
@ -89,7 +89,7 @@ final class ManagedChannelOrphanWrapper extends ForwardingManagedChannel {
ReferenceQueue<ManagedChannelOrphanWrapper> refqueue, ReferenceQueue<ManagedChannelOrphanWrapper> refqueue,
ConcurrentMap<ManagedChannelReference, ManagedChannelReference> refs) { ConcurrentMap<ManagedChannelReference, ManagedChannelReference> refs) {
super(orphanable, refqueue); super(orphanable, refqueue);
allocationSite = new SoftReference<RuntimeException>( allocationSite = new SoftReference<>(
ENABLE_ALLOCATION_TRACKING ENABLE_ALLOCATION_TRACKING
? new RuntimeException("ManagedChannel allocation site") ? new RuntimeException("ManagedChannel allocation site")
: missingCallSite); : missingCallSite);

View File

@ -191,7 +191,7 @@ final class OobChannel extends ManagedChannel implements InternalInstrumented<Ch
@Override @Override
public <RequestT, ResponseT> ClientCall<RequestT, ResponseT> newCall( public <RequestT, ResponseT> ClientCall<RequestT, ResponseT> newCall(
MethodDescriptor<RequestT, ResponseT> methodDescriptor, CallOptions callOptions) { MethodDescriptor<RequestT, ResponseT> methodDescriptor, CallOptions callOptions) {
return new ClientCallImpl<RequestT, ResponseT>(methodDescriptor, return new ClientCallImpl<>(methodDescriptor,
callOptions.getExecutor() == null ? executor : callOptions.getExecutor(), callOptions.getExecutor() == null ? executor : callOptions.getExecutor(),
callOptions, transportProvider, deadlineCancellationExecutor, channelCallsTracer, callOptions, transportProvider, deadlineCancellationExecutor, channelCallsTracer,
false /* retryEnabled */); false /* retryEnabled */);

View File

@ -74,7 +74,7 @@ class SerializeReentrantCallsDirectExecutor implements Executor {
private void enqueue(Runnable r) { private void enqueue(Runnable r) {
if (taskQueue == null) { if (taskQueue == null) {
taskQueue = new ArrayDeque<Runnable>(4); taskQueue = new ArrayDeque<>(4);
} }
taskQueue.add(r); taskQueue.add(r);
} }

View File

@ -62,7 +62,7 @@ public final class SerializingExecutor implements Executor, Runnable {
private final Executor executor; private final Executor executor;
/** A list of Runnables to be run in order. */ /** A list of Runnables to be run in order. */
private final Queue<Runnable> runQueue = new ConcurrentLinkedQueue<Runnable>(); private final Queue<Runnable> runQueue = new ConcurrentLinkedQueue<>();
private volatile int runState = STOPPED; private volatile int runState = STOPPED;

View File

@ -190,7 +190,7 @@ final class ServerCallImpl<ReqT, RespT> extends ServerCall<ReqT, RespT> {
} }
ServerStreamListener newServerStreamListener(ServerCall.Listener<ReqT> listener) { ServerStreamListener newServerStreamListener(ServerCall.Listener<ReqT> listener) {
return new ServerStreamListenerImpl<ReqT>(this, listener, context); return new ServerStreamListenerImpl<>(this, listener, context);
} }
@Override @Override

View File

@ -554,7 +554,7 @@ public final class ServerImpl extends io.grpc.Server implements InternalInstrume
Context.CancellableContext context, StatsTraceContext statsTraceCtx) { Context.CancellableContext context, StatsTraceContext statsTraceCtx) {
// TODO(ejona86): should we update fullMethodName to have the canonical path of the method? // TODO(ejona86): should we update fullMethodName to have the canonical path of the method?
statsTraceCtx.serverCallStarted( statsTraceCtx.serverCallStarted(
new ServerCallInfoImpl<ReqT, RespT>( new ServerCallInfoImpl<>(
methodDef.getMethodDescriptor(), // notify with original method descriptor methodDef.getMethodDescriptor(), // notify with original method descriptor
stream.getAttributes(), stream.getAttributes(),
stream.getAuthority())); stream.getAuthority()));
@ -574,7 +574,7 @@ public final class ServerImpl extends io.grpc.Server implements InternalInstrume
ServerStream stream, ServerStream stream,
Metadata headers, Metadata headers,
Context.CancellableContext context) { Context.CancellableContext context) {
ServerCallImpl<WReqT, WRespT> call = new ServerCallImpl<WReqT, WRespT>( ServerCallImpl<WReqT, WRespT> call = new ServerCallImpl<>(
stream, stream,
methodDef.getMethodDescriptor(), methodDef.getMethodDescriptor(),
headers, headers,

View File

@ -54,10 +54,10 @@ final class ServiceConfigInterceptor implements ClientInterceptor {
// Map from method name to MethodInfo // Map from method name to MethodInfo
@VisibleForTesting @VisibleForTesting
final AtomicReference<Map<String, MethodInfo>> serviceMethodMap final AtomicReference<Map<String, MethodInfo>> serviceMethodMap
= new AtomicReference<Map<String, MethodInfo>>(); = new AtomicReference<>();
@VisibleForTesting @VisibleForTesting
final AtomicReference<Map<String, MethodInfo>> serviceMap final AtomicReference<Map<String, MethodInfo>> serviceMap
= new AtomicReference<Map<String, MethodInfo>>(); = new AtomicReference<>();
private final boolean retryEnabled; private final boolean retryEnabled;
private final int maxRetryAttemptsLimit; private final int maxRetryAttemptsLimit;
@ -74,8 +74,8 @@ final class ServiceConfigInterceptor implements ClientInterceptor {
} }
void handleUpdate(@Nonnull Map<String, Object> serviceConfig) { void handleUpdate(@Nonnull Map<String, Object> serviceConfig) {
Map<String, MethodInfo> newServiceMethodConfigs = new HashMap<String, MethodInfo>(); Map<String, MethodInfo> newServiceMethodConfigs = new HashMap<>();
Map<String, MethodInfo> newServiceConfigs = new HashMap<String, MethodInfo>(); Map<String, MethodInfo> newServiceConfigs = new HashMap<>();
// Try and do as much validation here before we swap out the existing configuration. In case // Try and do as much validation here before we swap out the existing configuration. In case
// the input is invalid, we don't want to lose the existing configuration. // the input is invalid, we don't want to lose the existing configuration.

View File

@ -53,7 +53,7 @@ public final class SharedResourceHolder {
}); });
private final IdentityHashMap<Resource<?>, Instance> instances = private final IdentityHashMap<Resource<?>, Instance> instances =
new IdentityHashMap<Resource<?>, Instance>(); new IdentityHashMap<>();
private final ScheduledExecutorFactory destroyerFactory; private final ScheduledExecutorFactory destroyerFactory;

View File

@ -27,7 +27,7 @@ public final class SharedResourcePool<T> implements ObjectPool<T> {
} }
public static <T> SharedResourcePool<T> forResource(SharedResourceHolder.Resource<T> resource) { public static <T> SharedResourcePool<T> forResource(SharedResourceHolder.Resource<T> resource) {
return new SharedResourcePool<T>(resource); return new SharedResourcePool<>(resource);
} }
@Override @Override

View File

@ -106,7 +106,7 @@ final class SubchannelChannel extends Channel {
public void sendMessage(RequestT message) {} public void sendMessage(RequestT message) {}
}; };
} }
return new ClientCallImpl<RequestT, ResponseT>(methodDescriptor, return new ClientCallImpl<>(methodDescriptor,
effectiveExecutor, effectiveExecutor,
callOptions.withOption(GrpcUtil.CALL_OPTIONS_RPC_OWNED_BY_BALANCER, Boolean.TRUE), callOptions.withOption(GrpcUtil.CALL_OPTIONS_RPC_OWNED_BY_BALANCER, Boolean.TRUE),
transportProvider, deadlineCancellationExecutor, callsTracer, false /* retryEnabled */); transportProvider, deadlineCancellationExecutor, callsTracer, false /* retryEnabled */);

View File

@ -40,7 +40,7 @@ import javax.annotation.concurrent.ThreadSafe;
@ExperimentalApi("https://github.com/grpc/grpc-java/issues/933") @ExperimentalApi("https://github.com/grpc/grpc-java/issues/933")
public final class MutableHandlerRegistry extends HandlerRegistry { public final class MutableHandlerRegistry extends HandlerRegistry {
private final ConcurrentMap<String, ServerServiceDefinition> services private final ConcurrentMap<String, ServerServiceDefinition> services
= new ConcurrentHashMap<String, ServerServiceDefinition>(); = new ConcurrentHashMap<>();
/** /**
* Registers a service. * Registers a service.

View File

@ -72,7 +72,7 @@ final class RoundRobinLoadBalancer extends LoadBalancer {
private final Helper helper; private final Helper helper;
private final Map<EquivalentAddressGroup, Subchannel> subchannels = private final Map<EquivalentAddressGroup, Subchannel> subchannels =
new HashMap<EquivalentAddressGroup, Subchannel>(); new HashMap<>();
private final Random random; private final Random random;
private ConnectivityState currentState; private ConnectivityState currentState;
@ -122,11 +122,11 @@ final class RoundRobinLoadBalancer extends LoadBalancer {
// after creation but since we can mutate the values we leverage that and set // after creation but since we can mutate the values we leverage that and set
// AtomicReference which will allow mutating state info for given channel. // AtomicReference which will allow mutating state info for given channel.
.set(STATE_INFO, .set(STATE_INFO,
new Ref<ConnectivityStateInfo>(ConnectivityStateInfo.forNonError(IDLE))); new Ref<>(ConnectivityStateInfo.forNonError(IDLE)));
Ref<Subchannel> stickyRef = null; Ref<Subchannel> stickyRef = null;
if (stickinessState != null) { if (stickinessState != null) {
subchannelAttrs.set(STICKY_REF, stickyRef = new Ref<Subchannel>(null)); subchannelAttrs.set(STICKY_REF, stickyRef = new Ref<>(null));
} }
Subchannel subchannel = checkNotNull( Subchannel subchannel = checkNotNull(
@ -248,7 +248,7 @@ final class RoundRobinLoadBalancer extends LoadBalancer {
* remove all attributes. * remove all attributes.
*/ */
private static Set<EquivalentAddressGroup> stripAttrs(List<EquivalentAddressGroup> groupList) { private static Set<EquivalentAddressGroup> stripAttrs(List<EquivalentAddressGroup> groupList) {
Set<EquivalentAddressGroup> addrs = new HashSet<EquivalentAddressGroup>(groupList.size()); Set<EquivalentAddressGroup> addrs = new HashSet<>(groupList.size());
for (EquivalentAddressGroup group : groupList) { for (EquivalentAddressGroup group : groupList) {
addrs.add(new EquivalentAddressGroup(group.getAddresses())); addrs.add(new EquivalentAddressGroup(group.getAddresses()));
} }
@ -271,7 +271,7 @@ final class RoundRobinLoadBalancer extends LoadBalancer {
} }
private static <T> Set<T> setsDifference(Set<T> a, Set<T> b) { private static <T> Set<T> setsDifference(Set<T> a, Set<T> b) {
Set<T> aCopy = new HashSet<T>(a); Set<T> aCopy = new HashSet<>(a);
aCopy.removeAll(b); aCopy.removeAll(b);
return aCopy; return aCopy;
} }
@ -293,9 +293,9 @@ final class RoundRobinLoadBalancer extends LoadBalancer {
final Key<String> key; final Key<String> key;
final ConcurrentMap<String, Ref<Subchannel>> stickinessMap = final ConcurrentMap<String, Ref<Subchannel>> stickinessMap =
new ConcurrentHashMap<String, Ref<Subchannel>>(); new ConcurrentHashMap<>();
final Queue<String> evictionQueue = new ConcurrentLinkedQueue<String>(); final Queue<String> evictionQueue = new ConcurrentLinkedQueue<>();
StickinessState(@Nonnull String stickinessKey) { StickinessState(@Nonnull String stickinessKey) {
this.key = Key.of(stickinessKey, Metadata.ASCII_STRING_MARSHALLER); this.key = Key.of(stickinessKey, Metadata.ASCII_STRING_MARSHALLER);
@ -425,7 +425,7 @@ final class RoundRobinLoadBalancer extends LoadBalancer {
// the lists cannot contain duplicate subchannels // the lists cannot contain duplicate subchannels
return other == this || (stickinessState == other.stickinessState return other == this || (stickinessState == other.stickinessState
&& list.size() == other.list.size() && list.size() == other.list.size()
&& new HashSet<Subchannel>(list).containsAll(other.list)); && new HashSet<>(list).containsAll(other.list));
} }
} }

View File

@ -56,7 +56,7 @@ public final class TransmitStatusRuntimeExceptionInterceptor implements ServerIn
@Override @Override
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall( public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(
ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) { ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) {
final ServerCall<ReqT, RespT> serverCall = new SerializingServerCall<ReqT, RespT>(call); final ServerCall<ReqT, RespT> serverCall = new SerializingServerCall<>(call);
ServerCall.Listener<ReqT> listener = next.startCall(serverCall, headers); ServerCall.Listener<ReqT> listener = next.startCall(serverCall, headers);
return new ForwardingServerCallListener.SimpleForwardingServerCallListener<ReqT>(listener) { return new ForwardingServerCallListener.SimpleForwardingServerCallListener<ReqT>(listener) {
@Override @Override

View File

@ -48,7 +48,7 @@ public class ContextsTest {
/** For use in comparing context by reference. */ /** For use in comparing context by reference. */
private Context uniqueContext = Context.ROOT.withValue(contextKey, new Object()); private Context uniqueContext = Context.ROOT.withValue(contextKey, new Object());
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private ServerCall<Object, Object> call = new NoopServerCall<Object, Object>(); private ServerCall<Object, Object> call = new NoopServerCall<>();
private Metadata headers = new Metadata(); private Metadata headers = new Metadata();
@Test @Test

View File

@ -49,7 +49,7 @@ public class DecompressorRegistryTest {
@Test @Test
public void getKnownMessageEncodings_checkDefaultMessageEncodingsExist() { public void getKnownMessageEncodings_checkDefaultMessageEncodingsExist() {
Set<String> knownEncodings = new HashSet<String>(); Set<String> knownEncodings = new HashSet<>();
knownEncodings.add("identity"); knownEncodings.add("identity");
knownEncodings.add("gzip"); knownEncodings.add("gzip");

View File

@ -140,7 +140,7 @@ public class MetadataTest {
Metadata metadata = new Metadata(); Metadata metadata = new Metadata();
metadata.put(KEY, lance); metadata.put(KEY, lance);
assertEquals(lance, metadata.get(KEY)); assertEquals(lance, metadata.get(KEY));
Iterator<Fish> fishes = metadata.<Fish>getAll(KEY).iterator(); Iterator<Fish> fishes = metadata.getAll(KEY).iterator();
assertTrue(fishes.hasNext()); assertTrue(fishes.hasNext());
assertEquals(fishes.next(), lance); assertEquals(fishes.next(), lance);
assertFalse(fishes.hasNext()); assertFalse(fishes.hasNext());
@ -192,7 +192,7 @@ public class MetadataTest {
h1.merge(h2); h1.merge(h2);
Iterator<Fish> fishes = h1.<Fish>getAll(KEY).iterator(); Iterator<Fish> fishes = h1.getAll(KEY).iterator();
assertTrue(fishes.hasNext()); assertTrue(fishes.hasNext());
assertEquals(fishes.next(), lance); assertEquals(fishes.next(), lance);
assertFalse(fishes.hasNext()); assertFalse(fishes.hasNext());

View File

@ -41,7 +41,7 @@ public class NameResolverProviderTest {
@Test @Test
public void getDefaultScheme_noProvider() { public void getDefaultScheme_noProvider() {
List<NameResolverProvider> providers = Collections.<NameResolverProvider>emptyList(); List<NameResolverProvider> providers = Collections.emptyList();
NameResolver.Factory factory = NameResolverProvider.asFactory(providers); NameResolver.Factory factory = NameResolverProvider.asFactory(providers);
try { try {
factory.getDefaultScheme(); factory.getDefaultScheme();
@ -67,7 +67,7 @@ public class NameResolverProviderTest {
@Test @Test
public void newNameResolver_noProvider() { public void newNameResolver_noProvider() {
List<NameResolverProvider> providers = Collections.<NameResolverProvider>emptyList(); List<NameResolverProvider> providers = Collections.emptyList();
NameResolver.Factory factory = NameResolverProvider.asFactory(providers); NameResolver.Factory factory = NameResolverProvider.asFactory(providers);
try { try {
factory.newNameResolver(uri, attributes); factory.newNameResolver(uri, attributes);

View File

@ -63,7 +63,7 @@ public class ServerInterceptorsTest {
private MethodDescriptor<String, Integer> flowMethod; private MethodDescriptor<String, Integer> flowMethod;
private ServerCall<String, Integer> call = new NoopServerCall<String, Integer>(); private ServerCall<String, Integer> call = new NoopServerCall<>();
private ServerServiceDefinition serviceDefinition; private ServerServiceDefinition serviceDefinition;
@ -269,7 +269,7 @@ public class ServerInterceptorsTest {
@Test @Test
public void argumentsPassed() { public void argumentsPassed() {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
final ServerCall<String, Integer> call2 = new NoopServerCall<String, Integer>(); final ServerCall<String, Integer> call2 = new NoopServerCall<>();
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
final ServerCall.Listener<String> listener2 = mock(ServerCall.Listener.class); final ServerCall.Listener<String> listener2 = mock(ServerCall.Listener.class);
@ -398,7 +398,7 @@ public class ServerInterceptorsTest {
.intercept(inputStreamMessageService, interceptor2); .intercept(inputStreamMessageService, interceptor2);
ServerMethodDefinition<InputStream, InputStream> serverMethod = ServerMethodDefinition<InputStream, InputStream> serverMethod =
(ServerMethodDefinition<InputStream, InputStream>) intercepted2.getMethod("basic/wrapped"); (ServerMethodDefinition<InputStream, InputStream>) intercepted2.getMethod("basic/wrapped");
ServerCall<InputStream, InputStream> call2 = new NoopServerCall<InputStream, InputStream>(); ServerCall<InputStream, InputStream> call2 = new NoopServerCall<>();
byte[] bytes = {}; byte[] bytes = {};
serverMethod serverMethod
.getServerCallHandler() .getServerCallHandler()
@ -425,7 +425,7 @@ public class ServerInterceptorsTest {
} }
private ServerCallHandler<String, Integer> anyCallHandler() { private ServerCallHandler<String, Integer> anyCallHandler() {
return Mockito.<ServerCallHandler<String, Integer>>any(); return Mockito.any();
} }
private static class NoopInterceptor implements ServerInterceptor { private static class NoopInterceptor implements ServerInterceptor {

View File

@ -41,7 +41,7 @@ final class ServiceProvidersTestUtil {
String callableClassName, String callableClassName,
ClassLoader cl, ClassLoader cl,
Set<String> hardcodedClassNames) throws Exception { Set<String> hardcodedClassNames) throws Exception {
final Set<String> notLoaded = new HashSet<String>(hardcodedClassNames); final Set<String> notLoaded = new HashSet<>(hardcodedClassNames);
cl = new ClassLoader(cl) { cl = new ClassLoader(cl) {
@Override @Override
public Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { public Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {

View File

@ -99,8 +99,8 @@ public class SynchronizationContextTest {
final CountDownLatch task1Running = new CountDownLatch(1); final CountDownLatch task1Running = new CountDownLatch(1);
final CountDownLatch task1Proceed = new CountDownLatch(1); final CountDownLatch task1Proceed = new CountDownLatch(1);
final CountDownLatch sideThreadDone = new CountDownLatch(1); final CountDownLatch sideThreadDone = new CountDownLatch(1);
final AtomicReference<Thread> task1Thread = new AtomicReference<Thread>(); final AtomicReference<Thread> task1Thread = new AtomicReference<>();
final AtomicReference<Thread> task2Thread = new AtomicReference<Thread>(); final AtomicReference<Thread> task2Thread = new AtomicReference<>();
doAnswer(new Answer<Void>() { doAnswer(new Answer<Void>() {
@Override @Override

View File

@ -85,7 +85,7 @@ public class AbstractServerStreamTest {
*/ */
@Test @Test
public void frameShouldBeIgnoredAfterDeframerClosed() { public void frameShouldBeIgnoredAfterDeframerClosed() {
final Queue<InputStream> streamListenerMessageQueue = new LinkedList<InputStream>(); final Queue<InputStream> streamListenerMessageQueue = new LinkedList<>();
stream.transportState().setListener(new ServerStreamListenerBase() { stream.transportState().setListener(new ServerStreamListenerBase() {
@Override @Override
public void messagesAvailable(MessageProducer producer) { public void messagesAvailable(MessageProducer producer) {

View File

@ -117,7 +117,7 @@ public class ApplicationThreadDeframerTest {
public void messagesAvailableDrainsToMessageReadQueue_returnedByInitializingMessageProducer() public void messagesAvailableDrainsToMessageReadQueue_returnedByInitializingMessageProducer()
throws Exception { throws Exception {
byte[][] messageBytes = {{1, 2, 3}, {4}, {5, 6}}; byte[][] messageBytes = {{1, 2, 3}, {4}, {5, 6}};
Queue<InputStream> messages = new LinkedList<InputStream>(); Queue<InputStream> messages = new LinkedList<>();
for (int i = 0; i < messageBytes.length; i++) { for (int i = 0; i < messageBytes.length; i++) {
messages.add(new ByteArrayInputStream(messageBytes[i])); messages.add(new ByteArrayInputStream(messageBytes[i]));
} }

View File

@ -191,7 +191,7 @@ public class AutoConfiguredLoadBalancerFactoryTest {
@Test @Test
public void handleResolvedAddressGroups_shutsDownOldBalancer() { public void handleResolvedAddressGroups_shutsDownOldBalancer() {
Map<String, Object> serviceConfig = new HashMap<String, Object>(); Map<String, Object> serviceConfig = new HashMap<>();
serviceConfig.put("loadBalancingPolicy", "round_robin"); serviceConfig.put("loadBalancingPolicy", "round_robin");
Attributes serviceConfigAttrs = Attributes serviceConfigAttrs =
Attributes.newBuilder() Attributes.newBuilder()
@ -407,7 +407,7 @@ public class AutoConfiguredLoadBalancerFactoryTest {
public void decideLoadBalancerProvider_grpclbOverridesServiceConfigLbPolicy() throws Exception { public void decideLoadBalancerProvider_grpclbOverridesServiceConfigLbPolicy() throws Exception {
AutoConfiguredLoadBalancer lb = AutoConfiguredLoadBalancer lb =
(AutoConfiguredLoadBalancer) lbf.newLoadBalancer(new TestHelper()); (AutoConfiguredLoadBalancer) lbf.newLoadBalancer(new TestHelper());
Map<String, Object> serviceConfig = new HashMap<String, Object>(); Map<String, Object> serviceConfig = new HashMap<>();
serviceConfig.put("loadBalancingPolicy", "round_robin"); serviceConfig.put("loadBalancingPolicy", "round_robin");
List<EquivalentAddressGroup> servers = List<EquivalentAddressGroup> servers =
Collections.singletonList( Collections.singletonList(
@ -590,7 +590,7 @@ public class AutoConfiguredLoadBalancerFactoryTest {
verify(channelLogger).log( verify(channelLogger).log(
eq(ChannelLogLevel.DEBUG), eq(ChannelLogLevel.DEBUG),
eq("{0} specified by Service Config are not available"), eq("{0} specified by Service Config are not available"),
eq(new LinkedHashSet<String>(Arrays.asList("magic_balancer")))); eq(new LinkedHashSet<>(Arrays.asList("magic_balancer"))));
} }
@Test @Test
@ -652,7 +652,7 @@ public class AutoConfiguredLoadBalancerFactoryTest {
verifyNoMoreInteractions(channelLogger); verifyNoMoreInteractions(channelLogger);
Map<String, Object> serviceConfig = new HashMap<String, Object>(); Map<String, Object> serviceConfig = new HashMap<>();
serviceConfig.put("loadBalancingPolicy", "round_robin"); serviceConfig.put("loadBalancingPolicy", "round_robin");
lb.handleResolvedAddressGroups(servers, lb.handleResolvedAddressGroups(servers,
Attributes.newBuilder() Attributes.newBuilder()

View File

@ -231,7 +231,7 @@ public class CensusModulesTest {
} }
}).build()); }).build());
final AtomicReference<CallOptions> capturedCallOptions = new AtomicReference<CallOptions>(); final AtomicReference<CallOptions> capturedCallOptions = new AtomicReference<>();
ClientInterceptor callOptionsCaptureInterceptor = new ClientInterceptor() { ClientInterceptor callOptionsCaptureInterceptor = new ClientInterceptor() {
@Override @Override
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall( public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
@ -830,7 +830,7 @@ public class CensusModulesTest {
headers.put( headers.put(
Metadata.Key.of("never-used-key-bin", Metadata.BINARY_BYTE_MARSHALLER), Metadata.Key.of("never-used-key-bin", Metadata.BINARY_BYTE_MARSHALLER),
new byte[] {}); new byte[] {});
Set<String> originalHeaderKeys = new HashSet<String>(headers.keys()); Set<String> originalHeaderKeys = new HashSet<>(headers.keys());
CensusTracingModule.ClientCallTracer callTracer = CensusTracingModule.ClientCallTracer callTracer =
censusTracing.newClientCallTracer(BlankSpan.INSTANCE, method); censusTracing.newClientCallTracer(BlankSpan.INSTANCE, method);
@ -1020,7 +1020,7 @@ public class CensusModulesTest {
assertSame(spyServerSpan, ContextUtils.CONTEXT_SPAN_KEY.get(filteredContext)); assertSame(spyServerSpan, ContextUtils.CONTEXT_SPAN_KEY.get(filteredContext));
serverStreamTracer.serverCallStarted( serverStreamTracer.serverCallStarted(
new ServerCallInfoImpl<String, String>(method, Attributes.EMPTY, null)); new ServerCallInfoImpl<>(method, Attributes.EMPTY, null));
verify(spyServerSpan, never()).end(any(EndSpanOptions.class)); verify(spyServerSpan, never()).end(any(EndSpanOptions.class));
@ -1063,7 +1063,7 @@ public class CensusModulesTest {
serverStreamTracer.filterContext(Context.ROOT); serverStreamTracer.filterContext(Context.ROOT);
serverStreamTracer.serverCallStarted( serverStreamTracer.serverCallStarted(
new ServerCallInfoImpl<String, String>(sampledMethod, Attributes.EMPTY, null)); new ServerCallInfoImpl<>(sampledMethod, Attributes.EMPTY, null));
serverStreamTracer.streamClosed(Status.CANCELLED); serverStreamTracer.streamClosed(Status.CANCELLED);

View File

@ -43,7 +43,7 @@ public class ChannelLoggerImplTest {
private final FakeClock clock = new FakeClock(); private final FakeClock clock = new FakeClock();
private final InternalLogId logId = InternalLogId.allocate("test", /*details=*/ null); private final InternalLogId logId = InternalLogId.allocate("test", /*details=*/ null);
private final String logPrefix = "[" + logId + "] "; private final String logPrefix = "[" + logId + "] ";
private final ArrayList<String> logs = new ArrayList<String>(); private final ArrayList<String> logs = new ArrayList<>();
private final Handler handler = new Handler() { private final Handler handler = new Handler() {
@Override @Override
public void publish(LogRecord record) { public void publish(LogRecord record) {

View File

@ -40,7 +40,7 @@ import org.junit.runners.JUnit4;
@RunWith(JUnit4.class) @RunWith(JUnit4.class)
public class ChannelTracerTest { public class ChannelTracerTest {
private static final Logger logger = Logger.getLogger(ChannelLogger.class.getName()); private static final Logger logger = Logger.getLogger(ChannelLogger.class.getName());
private final ArrayList<LogRecord> logs = new ArrayList<LogRecord>(); private final ArrayList<LogRecord> logs = new ArrayList<>();
private final Handler handler = new Handler() { private final Handler handler = new Handler() {
@Override @Override
public void publish(LogRecord record) { public void publish(LogRecord record) {

View File

@ -143,7 +143,7 @@ public class ClientCallImplTest {
@Test @Test
public void statusPropagatedFromStreamToCallListener() { public void statusPropagatedFromStreamToCallListener() {
DelayedExecutor executor = new DelayedExecutor(); DelayedExecutor executor = new DelayedExecutor();
ClientCallImpl<Void, Void> call = new ClientCallImpl<Void, Void>( ClientCallImpl<Void, Void> call = new ClientCallImpl<>(
method, method,
executor, executor,
baseCallOptions, baseCallOptions,
@ -165,7 +165,7 @@ public class ClientCallImplTest {
@Test @Test
public void exceptionInOnMessageTakesPrecedenceOverServer() { public void exceptionInOnMessageTakesPrecedenceOverServer() {
DelayedExecutor executor = new DelayedExecutor(); DelayedExecutor executor = new DelayedExecutor();
ClientCallImpl<Void, Void> call = new ClientCallImpl<Void, Void>( ClientCallImpl<Void, Void> call = new ClientCallImpl<>(
method, method,
executor, executor,
baseCallOptions, baseCallOptions,
@ -202,7 +202,7 @@ public class ClientCallImplTest {
@Test @Test
public void exceptionInOnHeadersTakesPrecedenceOverServer() { public void exceptionInOnHeadersTakesPrecedenceOverServer() {
DelayedExecutor executor = new DelayedExecutor(); DelayedExecutor executor = new DelayedExecutor();
ClientCallImpl<Void, Void> call = new ClientCallImpl<Void, Void>( ClientCallImpl<Void, Void> call = new ClientCallImpl<>(
method, method,
executor, executor,
baseCallOptions, baseCallOptions,
@ -237,7 +237,7 @@ public class ClientCallImplTest {
@Test @Test
public void exceptionInOnReadyTakesPrecedenceOverServer() { public void exceptionInOnReadyTakesPrecedenceOverServer() {
DelayedExecutor executor = new DelayedExecutor(); DelayedExecutor executor = new DelayedExecutor();
ClientCallImpl<Void, Void> call = new ClientCallImpl<Void, Void>( ClientCallImpl<Void, Void> call = new ClientCallImpl<>(
method, method,
executor, executor,
baseCallOptions, baseCallOptions,
@ -271,7 +271,7 @@ public class ClientCallImplTest {
@Test @Test
public void advertisedEncodingsAreSent() { public void advertisedEncodingsAreSent() {
ClientCallImpl<Void, Void> call = new ClientCallImpl<Void, Void>( ClientCallImpl<Void, Void> call = new ClientCallImpl<>(
method, method,
MoreExecutors.directExecutor(), MoreExecutors.directExecutor(),
baseCallOptions, baseCallOptions,
@ -295,7 +295,7 @@ public class ClientCallImplTest {
@Test @Test
public void authorityPropagatedToStream() { public void authorityPropagatedToStream() {
ClientCallImpl<Void, Void> call = new ClientCallImpl<Void, Void>( ClientCallImpl<Void, Void> call = new ClientCallImpl<>(
method, method,
MoreExecutors.directExecutor(), MoreExecutors.directExecutor(),
baseCallOptions.withAuthority("overridden-authority"), baseCallOptions.withAuthority("overridden-authority"),
@ -312,7 +312,7 @@ public class ClientCallImplTest {
@Test @Test
public void callOptionsPropagatedToTransport() { public void callOptionsPropagatedToTransport() {
final CallOptions callOptions = baseCallOptions.withAuthority("dummy_value"); final CallOptions callOptions = baseCallOptions.withAuthority("dummy_value");
final ClientCallImpl<Void, Void> call = new ClientCallImpl<Void, Void>( final ClientCallImpl<Void, Void> call = new ClientCallImpl<>(
method, method,
MoreExecutors.directExecutor(), MoreExecutors.directExecutor(),
callOptions, callOptions,
@ -330,7 +330,7 @@ public class ClientCallImplTest {
@Test @Test
public void authorityNotPropagatedToStream() { public void authorityNotPropagatedToStream() {
ClientCallImpl<Void, Void> call = new ClientCallImpl<Void, Void>( ClientCallImpl<Void, Void> call = new ClientCallImpl<>(
method, method,
MoreExecutors.directExecutor(), MoreExecutors.directExecutor(),
// Don't provide an authority // Don't provide an authority
@ -502,7 +502,7 @@ public class ClientCallImplTest {
Context context = Context.current().withValue(testKey, "testValue"); Context context = Context.current().withValue(testKey, "testValue");
Context previous = context.attach(); Context previous = context.attach();
ClientCallImpl<Void, Void> call = new ClientCallImpl<Void, Void>( ClientCallImpl<Void, Void> call = new ClientCallImpl<>(
method, method,
new SerializingExecutor(Executors.newSingleThreadExecutor()), new SerializingExecutor(Executors.newSingleThreadExecutor()),
baseCallOptions, baseCallOptions,
@ -580,7 +580,7 @@ public class ClientCallImplTest {
Context.CancellableContext cancellableContext = Context.current().withCancellation(); Context.CancellableContext cancellableContext = Context.current().withCancellation();
Context previous = cancellableContext.attach(); Context previous = cancellableContext.attach();
ClientCallImpl<Void, Void> call = new ClientCallImpl<Void, Void>( ClientCallImpl<Void, Void> call = new ClientCallImpl<>(
method, method,
new SerializingExecutor(Executors.newSingleThreadExecutor()), new SerializingExecutor(Executors.newSingleThreadExecutor()),
baseCallOptions, baseCallOptions,
@ -610,7 +610,7 @@ public class ClientCallImplTest {
cancellableContext.cancel(cause); cancellableContext.cancel(cause);
Context previous = cancellableContext.attach(); Context previous = cancellableContext.attach();
ClientCallImpl<Void, Void> call = new ClientCallImpl<Void, Void>( ClientCallImpl<Void, Void> call = new ClientCallImpl<>(
method, method,
new SerializingExecutor(Executors.newSingleThreadExecutor()), new SerializingExecutor(Executors.newSingleThreadExecutor()),
baseCallOptions, baseCallOptions,
@ -655,7 +655,7 @@ public class ClientCallImplTest {
public void deadlineExceededBeforeCallStarted() { public void deadlineExceededBeforeCallStarted() {
CallOptions callOptions = baseCallOptions.withDeadlineAfter(0, TimeUnit.SECONDS); CallOptions callOptions = baseCallOptions.withDeadlineAfter(0, TimeUnit.SECONDS);
fakeClock.forwardTime(System.nanoTime(), TimeUnit.NANOSECONDS); fakeClock.forwardTime(System.nanoTime(), TimeUnit.NANOSECONDS);
ClientCallImpl<Void, Void> call = new ClientCallImpl<Void, Void>( ClientCallImpl<Void, Void> call = new ClientCallImpl<>(
method, method,
new SerializingExecutor(Executors.newSingleThreadExecutor()), new SerializingExecutor(Executors.newSingleThreadExecutor()),
callOptions, callOptions,
@ -678,7 +678,7 @@ public class ClientCallImplTest {
.withDeadlineAfter(1000, TimeUnit.MILLISECONDS, deadlineCancellationExecutor); .withDeadlineAfter(1000, TimeUnit.MILLISECONDS, deadlineCancellationExecutor);
Context origContext = context.attach(); Context origContext = context.attach();
ClientCallImpl<Void, Void> call = new ClientCallImpl<Void, Void>( ClientCallImpl<Void, Void> call = new ClientCallImpl<>(
method, method,
MoreExecutors.directExecutor(), MoreExecutors.directExecutor(),
baseCallOptions, baseCallOptions,
@ -703,7 +703,7 @@ public class ClientCallImplTest {
Context origContext = context.attach(); Context origContext = context.attach();
CallOptions callOpts = baseCallOptions.withDeadlineAfter(2000, TimeUnit.MILLISECONDS); CallOptions callOpts = baseCallOptions.withDeadlineAfter(2000, TimeUnit.MILLISECONDS);
ClientCallImpl<Void, Void> call = new ClientCallImpl<Void, Void>( ClientCallImpl<Void, Void> call = new ClientCallImpl<>(
method, method,
MoreExecutors.directExecutor(), MoreExecutors.directExecutor(),
callOpts, callOpts,
@ -728,7 +728,7 @@ public class ClientCallImplTest {
Context origContext = context.attach(); Context origContext = context.attach();
CallOptions callOpts = baseCallOptions.withDeadlineAfter(1000, TimeUnit.MILLISECONDS); CallOptions callOpts = baseCallOptions.withDeadlineAfter(1000, TimeUnit.MILLISECONDS);
ClientCallImpl<Void, Void> call = new ClientCallImpl<Void, Void>( ClientCallImpl<Void, Void> call = new ClientCallImpl<>(
method, method,
MoreExecutors.directExecutor(), MoreExecutors.directExecutor(),
callOpts, callOpts,
@ -749,7 +749,7 @@ public class ClientCallImplTest {
@Test @Test
public void callOptionsDeadlineShouldBePropagatedToStream() { public void callOptionsDeadlineShouldBePropagatedToStream() {
CallOptions callOpts = baseCallOptions.withDeadlineAfter(1000, TimeUnit.MILLISECONDS); CallOptions callOpts = baseCallOptions.withDeadlineAfter(1000, TimeUnit.MILLISECONDS);
ClientCallImpl<Void, Void> call = new ClientCallImpl<Void, Void>( ClientCallImpl<Void, Void> call = new ClientCallImpl<>(
method, method,
MoreExecutors.directExecutor(), MoreExecutors.directExecutor(),
callOpts, callOpts,
@ -767,7 +767,7 @@ public class ClientCallImplTest {
@Test @Test
public void noDeadlineShouldBePropagatedToStream() { public void noDeadlineShouldBePropagatedToStream() {
ClientCallImpl<Void, Void> call = new ClientCallImpl<Void, Void>( ClientCallImpl<Void, Void> call = new ClientCallImpl<>(
method, method,
MoreExecutors.directExecutor(), MoreExecutors.directExecutor(),
baseCallOptions, baseCallOptions,
@ -785,7 +785,7 @@ public class ClientCallImplTest {
fakeClock.forwardTime(System.nanoTime(), TimeUnit.NANOSECONDS); fakeClock.forwardTime(System.nanoTime(), TimeUnit.NANOSECONDS);
// The deadline needs to be a number large enough to get encompass the call to start, otherwise // The deadline needs to be a number large enough to get encompass the call to start, otherwise
// the scheduled cancellation won't be created, and the call will fail early. // the scheduled cancellation won't be created, and the call will fail early.
ClientCallImpl<Void, Void> call = new ClientCallImpl<Void, Void>( ClientCallImpl<Void, Void> call = new ClientCallImpl<>(
method, method,
MoreExecutors.directExecutor(), MoreExecutors.directExecutor(),
baseCallOptions.withDeadline(Deadline.after(1, TimeUnit.SECONDS)), baseCallOptions.withDeadline(Deadline.after(1, TimeUnit.SECONDS)),
@ -810,7 +810,7 @@ public class ClientCallImplTest {
.withDeadlineAfter(1, TimeUnit.SECONDS, deadlineCancellationExecutor); .withDeadlineAfter(1, TimeUnit.SECONDS, deadlineCancellationExecutor);
Context origContext = context.attach(); Context origContext = context.attach();
ClientCallImpl<Void, Void> call = new ClientCallImpl<Void, Void>( ClientCallImpl<Void, Void> call = new ClientCallImpl<>(
method, method,
MoreExecutors.directExecutor(), MoreExecutors.directExecutor(),
baseCallOptions, baseCallOptions,
@ -833,7 +833,7 @@ public class ClientCallImplTest {
public void streamCancelAbortsDeadlineTimer() { public void streamCancelAbortsDeadlineTimer() {
fakeClock.forwardTime(System.nanoTime(), TimeUnit.NANOSECONDS); fakeClock.forwardTime(System.nanoTime(), TimeUnit.NANOSECONDS);
ClientCallImpl<Void, Void> call = new ClientCallImpl<Void, Void>( ClientCallImpl<Void, Void> call = new ClientCallImpl<>(
method, method,
MoreExecutors.directExecutor(), MoreExecutors.directExecutor(),
baseCallOptions.withDeadline(Deadline.after(1, TimeUnit.SECONDS)), baseCallOptions.withDeadline(Deadline.after(1, TimeUnit.SECONDS)),
@ -858,7 +858,7 @@ public class ClientCallImplTest {
*/ */
@Test @Test
public void timeoutShouldNotBeSet() { public void timeoutShouldNotBeSet() {
ClientCallImpl<Void, Void> call = new ClientCallImpl<Void, Void>( ClientCallImpl<Void, Void> call = new ClientCallImpl<>(
method, method,
MoreExecutors.directExecutor(), MoreExecutors.directExecutor(),
baseCallOptions, baseCallOptions,
@ -876,7 +876,7 @@ public class ClientCallImplTest {
@Test @Test
public void cancelInOnMessageShouldInvokeStreamCancel() throws Exception { public void cancelInOnMessageShouldInvokeStreamCancel() throws Exception {
final ClientCallImpl<Void, Void> call = new ClientCallImpl<Void, Void>( final ClientCallImpl<Void, Void> call = new ClientCallImpl<>(
method, method,
MoreExecutors.directExecutor(), MoreExecutors.directExecutor(),
baseCallOptions, baseCallOptions,
@ -914,7 +914,7 @@ public class ClientCallImplTest {
public void startAddsMaxSize() { public void startAddsMaxSize() {
CallOptions callOptions = CallOptions callOptions =
baseCallOptions.withMaxInboundMessageSize(1).withMaxOutboundMessageSize(2); baseCallOptions.withMaxInboundMessageSize(1).withMaxOutboundMessageSize(2);
ClientCallImpl<Void, Void> call = new ClientCallImpl<Void, Void>( ClientCallImpl<Void, Void> call = new ClientCallImpl<>(
method, method,
new SerializingExecutor(Executors.newSingleThreadExecutor()), new SerializingExecutor(Executors.newSingleThreadExecutor()),
callOptions, callOptions,
@ -932,7 +932,7 @@ public class ClientCallImplTest {
@Test @Test
public void getAttributes() { public void getAttributes() {
ClientCallImpl<Void, Void> call = new ClientCallImpl<Void, Void>( ClientCallImpl<Void, Void> call = new ClientCallImpl<>(
method, MoreExecutors.directExecutor(), baseCallOptions, provider, method, MoreExecutors.directExecutor(), baseCallOptions, provider,
deadlineCancellationExecutor, channelCallTracer, false /* retryEnabled */); deadlineCancellationExecutor, channelCallTracer, false /* retryEnabled */);
Attributes attrs = Attributes attrs =
@ -952,7 +952,7 @@ public class ClientCallImplTest {
} }
private static final class DelayedExecutor implements Executor { private static final class DelayedExecutor implements Executor {
private final BlockingQueue<Runnable> commands = new LinkedBlockingQueue<Runnable>(); private final BlockingQueue<Runnable> commands = new LinkedBlockingQueue<>();
@Override @Override
public void execute(Runnable command) { public void execute(Runnable command) {

View File

@ -43,7 +43,7 @@ public class ConnectivityStateManagerTest {
private final FakeClock executor = new FakeClock(); private final FakeClock executor = new FakeClock();
private final ConnectivityStateManager state = new ConnectivityStateManager(); private final ConnectivityStateManager state = new ConnectivityStateManager();
private final LinkedList<ConnectivityState> sink = new LinkedList<ConnectivityState>(); private final LinkedList<ConnectivityState> sink = new LinkedList<>();
@Test @Test
public void noCallback() { public void noCallback() {
@ -147,7 +147,7 @@ public class ConnectivityStateManagerTest {
@Test @Test
public void multipleCallbacks() { public void multipleCallbacks() {
final LinkedList<String> callbackRuns = new LinkedList<String>(); final LinkedList<String> callbackRuns = new LinkedList<>();
state.notifyWhenStateChanged(new Runnable() { state.notifyWhenStateChanged(new Runnable() {
@Override @Override
public void run() { public void run() {

View File

@ -613,7 +613,7 @@ public class DnsNameResolverTest {
@Test @Test
public void maybeChooseServiceConfig_failsOnMisspelling() { public void maybeChooseServiceConfig_failsOnMisspelling() {
Map<String, Object> bad = new LinkedHashMap<String, Object>(); Map<String, Object> bad = new LinkedHashMap<>();
bad.put("parcentage", 1.0); bad.put("parcentage", 1.0);
thrown.expectMessage("Bad key"); thrown.expectMessage("Bad key");
@ -622,7 +622,7 @@ public class DnsNameResolverTest {
@Test @Test
public void maybeChooseServiceConfig_clientLanguageMatchesJava() { public void maybeChooseServiceConfig_clientLanguageMatchesJava() {
Map<String, Object> choice = new LinkedHashMap<String, Object>(); Map<String, Object> choice = new LinkedHashMap<>();
List<Object> langs = new ArrayList<>(); List<Object> langs = new ArrayList<>();
langs.add("java"); langs.add("java");
choice.put("clientLanguage", langs); choice.put("clientLanguage", langs);
@ -633,7 +633,7 @@ public class DnsNameResolverTest {
@Test @Test
public void maybeChooseServiceConfig_clientLanguageDoesntMatchGo() { public void maybeChooseServiceConfig_clientLanguageDoesntMatchGo() {
Map<String, Object> choice = new LinkedHashMap<String, Object>(); Map<String, Object> choice = new LinkedHashMap<>();
List<Object> langs = new ArrayList<>(); List<Object> langs = new ArrayList<>();
langs.add("go"); langs.add("go");
choice.put("clientLanguage", langs); choice.put("clientLanguage", langs);
@ -644,7 +644,7 @@ public class DnsNameResolverTest {
@Test @Test
public void maybeChooseServiceConfig_clientLanguageCaseInsensitive() { public void maybeChooseServiceConfig_clientLanguageCaseInsensitive() {
Map<String, Object> choice = new LinkedHashMap<String, Object>(); Map<String, Object> choice = new LinkedHashMap<>();
List<Object> langs = new ArrayList<>(); List<Object> langs = new ArrayList<>();
langs.add("JAVA"); langs.add("JAVA");
choice.put("clientLanguage", langs); choice.put("clientLanguage", langs);
@ -655,7 +655,7 @@ public class DnsNameResolverTest {
@Test @Test
public void maybeChooseServiceConfig_clientLanguageMatchesEmtpy() { public void maybeChooseServiceConfig_clientLanguageMatchesEmtpy() {
Map<String, Object> choice = new LinkedHashMap<String, Object>(); Map<String, Object> choice = new LinkedHashMap<>();
List<Object> langs = new ArrayList<>(); List<Object> langs = new ArrayList<>();
choice.put("clientLanguage", langs); choice.put("clientLanguage", langs);
choice.put("serviceConfig", serviceConfig); choice.put("serviceConfig", serviceConfig);
@ -665,7 +665,7 @@ public class DnsNameResolverTest {
@Test @Test
public void maybeChooseServiceConfig_clientLanguageMatchesMulti() { public void maybeChooseServiceConfig_clientLanguageMatchesMulti() {
Map<String, Object> choice = new LinkedHashMap<String, Object>(); Map<String, Object> choice = new LinkedHashMap<>();
List<Object> langs = new ArrayList<>(); List<Object> langs = new ArrayList<>();
langs.add("go"); langs.add("go");
langs.add("java"); langs.add("java");
@ -677,7 +677,7 @@ public class DnsNameResolverTest {
@Test @Test
public void maybeChooseServiceConfig_percentageZeroAlwaysFails() { public void maybeChooseServiceConfig_percentageZeroAlwaysFails() {
Map<String, Object> choice = new LinkedHashMap<String, Object>(); Map<String, Object> choice = new LinkedHashMap<>();
choice.put("percentage", 0D); choice.put("percentage", 0D);
choice.put("serviceConfig", serviceConfig); choice.put("serviceConfig", serviceConfig);
@ -686,7 +686,7 @@ public class DnsNameResolverTest {
@Test @Test
public void maybeChooseServiceConfig_percentageHundredAlwaysSucceeds() { public void maybeChooseServiceConfig_percentageHundredAlwaysSucceeds() {
Map<String, Object> choice = new LinkedHashMap<String, Object>(); Map<String, Object> choice = new LinkedHashMap<>();
choice.put("percentage", 100D); choice.put("percentage", 100D);
choice.put("serviceConfig", serviceConfig); choice.put("serviceConfig", serviceConfig);
@ -695,7 +695,7 @@ public class DnsNameResolverTest {
@Test @Test
public void maybeChooseServiceConfig_percentageAboveMatches50() { public void maybeChooseServiceConfig_percentageAboveMatches50() {
Map<String, Object> choice = new LinkedHashMap<String, Object>(); Map<String, Object> choice = new LinkedHashMap<>();
choice.put("percentage", 50D); choice.put("percentage", 50D);
choice.put("serviceConfig", serviceConfig); choice.put("serviceConfig", serviceConfig);
@ -711,7 +711,7 @@ public class DnsNameResolverTest {
@Test @Test
public void maybeChooseServiceConfig_percentageAtFails50() { public void maybeChooseServiceConfig_percentageAtFails50() {
Map<String, Object> choice = new LinkedHashMap<String, Object>(); Map<String, Object> choice = new LinkedHashMap<>();
choice.put("percentage", 50D); choice.put("percentage", 50D);
choice.put("serviceConfig", serviceConfig); choice.put("serviceConfig", serviceConfig);
@ -727,7 +727,7 @@ public class DnsNameResolverTest {
@Test @Test
public void maybeChooseServiceConfig_percentageAboveMatches99() { public void maybeChooseServiceConfig_percentageAboveMatches99() {
Map<String, Object> choice = new LinkedHashMap<String, Object>(); Map<String, Object> choice = new LinkedHashMap<>();
choice.put("percentage", 99D); choice.put("percentage", 99D);
choice.put("serviceConfig", serviceConfig); choice.put("serviceConfig", serviceConfig);
@ -743,7 +743,7 @@ public class DnsNameResolverTest {
@Test @Test
public void maybeChooseServiceConfig_percentageAtFails99() { public void maybeChooseServiceConfig_percentageAtFails99() {
Map<String, Object> choice = new LinkedHashMap<String, Object>(); Map<String, Object> choice = new LinkedHashMap<>();
choice.put("percentage", 99D); choice.put("percentage", 99D);
choice.put("serviceConfig", serviceConfig); choice.put("serviceConfig", serviceConfig);
@ -759,7 +759,7 @@ public class DnsNameResolverTest {
@Test @Test
public void maybeChooseServiceConfig_percentageAboveMatches1() { public void maybeChooseServiceConfig_percentageAboveMatches1() {
Map<String, Object> choice = new LinkedHashMap<String, Object>(); Map<String, Object> choice = new LinkedHashMap<>();
choice.put("percentage", 1D); choice.put("percentage", 1D);
choice.put("serviceConfig", serviceConfig); choice.put("serviceConfig", serviceConfig);
@ -775,7 +775,7 @@ public class DnsNameResolverTest {
@Test @Test
public void maybeChooseServiceConfig_percentageAtFails1() { public void maybeChooseServiceConfig_percentageAtFails1() {
Map<String, Object> choice = new LinkedHashMap<String, Object>(); Map<String, Object> choice = new LinkedHashMap<>();
choice.put("percentage", 1D); choice.put("percentage", 1D);
choice.put("serviceConfig", serviceConfig); choice.put("serviceConfig", serviceConfig);
@ -791,7 +791,7 @@ public class DnsNameResolverTest {
@Test @Test
public void maybeChooseServiceConfig_hostnameMatches() { public void maybeChooseServiceConfig_hostnameMatches() {
Map<String, Object> choice = new LinkedHashMap<String, Object>(); Map<String, Object> choice = new LinkedHashMap<>();
List<Object> hosts = new ArrayList<>(); List<Object> hosts = new ArrayList<>();
hosts.add("localhost"); hosts.add("localhost");
choice.put("clientHostname", hosts); choice.put("clientHostname", hosts);
@ -802,7 +802,7 @@ public class DnsNameResolverTest {
@Test @Test
public void maybeChooseServiceConfig_hostnameDoesntMatch() { public void maybeChooseServiceConfig_hostnameDoesntMatch() {
Map<String, Object> choice = new LinkedHashMap<String, Object>(); Map<String, Object> choice = new LinkedHashMap<>();
List<Object> hosts = new ArrayList<>(); List<Object> hosts = new ArrayList<>();
hosts.add("localhorse"); hosts.add("localhorse");
choice.put("clientHostname", hosts); choice.put("clientHostname", hosts);
@ -813,7 +813,7 @@ public class DnsNameResolverTest {
@Test @Test
public void maybeChooseServiceConfig_clientLanguageCaseSensitive() { public void maybeChooseServiceConfig_clientLanguageCaseSensitive() {
Map<String, Object> choice = new LinkedHashMap<String, Object>(); Map<String, Object> choice = new LinkedHashMap<>();
List<Object> hosts = new ArrayList<>(); List<Object> hosts = new ArrayList<>();
hosts.add("LOCALHOST"); hosts.add("LOCALHOST");
choice.put("clientHostname", hosts); choice.put("clientHostname", hosts);
@ -824,7 +824,7 @@ public class DnsNameResolverTest {
@Test @Test
public void maybeChooseServiceConfig_hostnameMatchesEmtpy() { public void maybeChooseServiceConfig_hostnameMatchesEmtpy() {
Map<String, Object> choice = new LinkedHashMap<String, Object>(); Map<String, Object> choice = new LinkedHashMap<>();
List<Object> hosts = new ArrayList<>(); List<Object> hosts = new ArrayList<>();
choice.put("clientHostname", hosts); choice.put("clientHostname", hosts);
choice.put("serviceConfig", serviceConfig); choice.put("serviceConfig", serviceConfig);
@ -834,7 +834,7 @@ public class DnsNameResolverTest {
@Test @Test
public void maybeChooseServiceConfig_hostnameMatchesMulti() { public void maybeChooseServiceConfig_hostnameMatchesMulti() {
Map<String, Object> choice = new LinkedHashMap<String, Object>(); Map<String, Object> choice = new LinkedHashMap<>();
List<Object> hosts = new ArrayList<>(); List<Object> hosts = new ArrayList<>();
hosts.add("localhorse"); hosts.add("localhorse");
hosts.add("localhost"); hosts.add("localhost");

View File

@ -268,7 +268,7 @@ public final class FakeClock {
*/ */
public Collection<ScheduledTask> getDueTasks() { public Collection<ScheduledTask> getDueTasks() {
checkDueTasks(); checkDueTasks();
return new ArrayList<ScheduledTask>(dueTasks); return new ArrayList<>(dueTasks);
} }
/** /**

View File

@ -86,7 +86,7 @@ public final class ForwardingManagedChannelTest {
@Test @Test
public void newCall() { public void newCall() {
NoopClientCall<Void, Void> clientCall = new NoopClientCall<Void, Void>(); NoopClientCall<Void, Void> clientCall = new NoopClientCall<>();
CallOptions callOptions = CallOptions.DEFAULT.withoutWaitForReady(); CallOptions callOptions = CallOptions.DEFAULT.withoutWaitForReady();
MethodDescriptor<Void, Void> method = TestMethodDescriptors.voidMethod(); MethodDescriptor<Void, Void> method = TestMethodDescriptors.voidMethod();
when(mock.newCall(same(method), same(callOptions))).thenReturn(clientCall); when(mock.newCall(same(method), same(callOptions))).thenReturn(clientCall);

View File

@ -102,7 +102,7 @@ public class InternalSubchannelTest {
@Mock private BackoffPolicy.Provider mockBackoffPolicyProvider; @Mock private BackoffPolicy.Provider mockBackoffPolicyProvider;
@Mock private ClientTransportFactory mockTransportFactory; @Mock private ClientTransportFactory mockTransportFactory;
private final LinkedList<String> callbackInvokes = new LinkedList<String>(); private final LinkedList<String> callbackInvokes = new LinkedList<>();
private final InternalSubchannel.Callback mockInternalSubchannelCallback = private final InternalSubchannel.Callback mockInternalSubchannelCallback =
new InternalSubchannel.Callback() { new InternalSubchannel.Callback() {
@Override @Override

View File

@ -117,7 +117,7 @@ public class JsonParserTest {
@Test @Test
public void objectStringName() throws IOException { public void objectStringName() throws IOException {
LinkedHashMap<String, Object> expected = new LinkedHashMap<String, Object>(); LinkedHashMap<String, Object> expected = new LinkedHashMap<>();
expected.put("hi", Double.valueOf("2")); expected.put("hi", Double.valueOf("2"));
assertEquals(expected, JsonParser.parse("{\"hi\": 2}")); assertEquals(expected, JsonParser.parse("{\"hi\": 2}"));

View File

@ -484,7 +484,7 @@ public class ManagedChannelImplIdlenessTest {
// We need this because createSubchannel() should be called from the SynchronizationContext // We need this because createSubchannel() should be called from the SynchronizationContext
private static Subchannel createSubchannelSafely( private static Subchannel createSubchannelSafely(
final Helper helper, final EquivalentAddressGroup addressGroup, final Attributes attrs) { final Helper helper, final EquivalentAddressGroup addressGroup, final Attributes attrs) {
final AtomicReference<Subchannel> resultCapture = new AtomicReference<Subchannel>(); final AtomicReference<Subchannel> resultCapture = new AtomicReference<>();
helper.getSynchronizationContext().execute( helper.getSynchronizationContext().execute(
new Runnable() { new Runnable() {
@Override @Override

View File

@ -326,7 +326,7 @@ public class ManagedChannelImplTest {
@Test @Test
public void createSubchannelOutsideSynchronizationContextShouldLogWarning() { public void createSubchannelOutsideSynchronizationContextShouldLogWarning() {
createChannel(); createChannel();
final AtomicReference<LogRecord> logRef = new AtomicReference<LogRecord>(); final AtomicReference<LogRecord> logRef = new AtomicReference<>();
Handler handler = new Handler() { Handler handler = new Handler() {
@Override @Override
public void publish(LogRecord record) { public void publish(LogRecord record) {
@ -1711,8 +1711,8 @@ public class ManagedChannelImplTest {
CallOptions callOptions = CallOptions.DEFAULT.withCallCredentials(creds); CallOptions callOptions = CallOptions.DEFAULT.withCallCredentials(creds);
final Context.Key<String> testKey = Context.key("testing"); final Context.Key<String> testKey = Context.key("testing");
Context ctx = Context.current().withValue(testKey, "testValue"); Context ctx = Context.current().withValue(testKey, "testValue");
final LinkedList<Context> credsApplyContexts = new LinkedList<Context>(); final LinkedList<Context> credsApplyContexts = new LinkedList<>();
final LinkedList<Context> newStreamContexts = new LinkedList<Context>(); final LinkedList<Context> newStreamContexts = new LinkedList<>();
doAnswer(new Answer<Void>() { doAnswer(new Answer<Void>() {
@Override @Override
public Void answer(InvocationOnMock in) throws Throwable { public Void answer(InvocationOnMock in) throws Throwable {
@ -2599,7 +2599,7 @@ public class ManagedChannelImplTest {
assertThat(getStats(channel).channelTrace.events).hasSize(prevSize); assertThat(getStats(channel).channelTrace.events).hasSize(prevSize);
prevSize = getStats(channel).channelTrace.events.size(); prevSize = getStats(channel).channelTrace.events.size();
Map<String, Object> serviceConfig = new HashMap<String, Object>(); Map<String, Object> serviceConfig = new HashMap<>();
serviceConfig.put("methodConfig", new HashMap<String, Object>()); serviceConfig.put("methodConfig", new HashMap<String, Object>());
attributes = attributes =
Attributes.newBuilder() Attributes.newBuilder()
@ -2943,18 +2943,18 @@ public class ManagedChannelImplTest {
@Test @Test
public void retryBackoffThenChannelShutdown_retryShouldStillHappen_newCallShouldFail() { public void retryBackoffThenChannelShutdown_retryShouldStillHappen_newCallShouldFail() {
Map<String, Object> retryPolicy = new HashMap<String, Object>(); Map<String, Object> retryPolicy = new HashMap<>();
retryPolicy.put("maxAttempts", 3D); retryPolicy.put("maxAttempts", 3D);
retryPolicy.put("initialBackoff", "10s"); retryPolicy.put("initialBackoff", "10s");
retryPolicy.put("maxBackoff", "30s"); retryPolicy.put("maxBackoff", "30s");
retryPolicy.put("backoffMultiplier", 2D); retryPolicy.put("backoffMultiplier", 2D);
retryPolicy.put("retryableStatusCodes", Arrays.<Object>asList("UNAVAILABLE")); retryPolicy.put("retryableStatusCodes", Arrays.<Object>asList("UNAVAILABLE"));
Map<String, Object> methodConfig = new HashMap<String, Object>(); Map<String, Object> methodConfig = new HashMap<>();
Map<String, Object> name = new HashMap<String, Object>(); Map<String, Object> name = new HashMap<>();
name.put("service", "service"); name.put("service", "service");
methodConfig.put("name", Arrays.<Object>asList(name)); methodConfig.put("name", Arrays.<Object>asList(name));
methodConfig.put("retryPolicy", retryPolicy); methodConfig.put("retryPolicy", retryPolicy);
Map<String, Object> serviceConfig = new HashMap<String, Object>(); Map<String, Object> serviceConfig = new HashMap<>();
serviceConfig.put("methodConfig", Arrays.<Object>asList(methodConfig)); serviceConfig.put("methodConfig", Arrays.<Object>asList(methodConfig));
Attributes attributesWithRetryPolicy = Attributes Attributes attributesWithRetryPolicy = Attributes
.newBuilder().set(GrpcAttributes.NAME_RESOLVER_SERVICE_CONFIG, serviceConfig).build(); .newBuilder().set(GrpcAttributes.NAME_RESOLVER_SERVICE_CONFIG, serviceConfig).build();
@ -3050,16 +3050,16 @@ public class ManagedChannelImplTest {
@Test @Test
public void hedgingScheduledThenChannelShutdown_hedgeShouldStillHappen_newCallShouldFail() { public void hedgingScheduledThenChannelShutdown_hedgeShouldStillHappen_newCallShouldFail() {
Map<String, Object> hedgingPolicy = new HashMap<String, Object>(); Map<String, Object> hedgingPolicy = new HashMap<>();
hedgingPolicy.put("maxAttempts", 3D); hedgingPolicy.put("maxAttempts", 3D);
hedgingPolicy.put("hedgingDelay", "10s"); hedgingPolicy.put("hedgingDelay", "10s");
hedgingPolicy.put("nonFatalStatusCodes", Arrays.<Object>asList("UNAVAILABLE")); hedgingPolicy.put("nonFatalStatusCodes", Arrays.<Object>asList("UNAVAILABLE"));
Map<String, Object> methodConfig = new HashMap<String, Object>(); Map<String, Object> methodConfig = new HashMap<>();
Map<String, Object> name = new HashMap<String, Object>(); Map<String, Object> name = new HashMap<>();
name.put("service", "service"); name.put("service", "service");
methodConfig.put("name", Arrays.<Object>asList(name)); methodConfig.put("name", Arrays.<Object>asList(name));
methodConfig.put("hedgingPolicy", hedgingPolicy); methodConfig.put("hedgingPolicy", hedgingPolicy);
Map<String, Object> serviceConfig = new HashMap<String, Object>(); Map<String, Object> serviceConfig = new HashMap<>();
serviceConfig.put("methodConfig", Arrays.<Object>asList(methodConfig)); serviceConfig.put("methodConfig", Arrays.<Object>asList(methodConfig));
Attributes attributesWithRetryPolicy = Attributes Attributes attributesWithRetryPolicy = Attributes
.newBuilder().set(GrpcAttributes.NAME_RESOLVER_SERVICE_CONFIG, serviceConfig).build(); .newBuilder().set(GrpcAttributes.NAME_RESOLVER_SERVICE_CONFIG, serviceConfig).build();
@ -3286,7 +3286,7 @@ public class ManagedChannelImplTest {
final ArrayList<FakeNameResolver> resolvers = new ArrayList<>(); final ArrayList<FakeNameResolver> resolvers = new ArrayList<>();
// The Attributes argument of the next invocation of listener.onAddresses(servers, attrs) // The Attributes argument of the next invocation of listener.onAddresses(servers, attrs)
final AtomicReference<Attributes> nextResolvedAttributes = final AtomicReference<Attributes> nextResolvedAttributes =
new AtomicReference<Attributes>(Attributes.EMPTY); new AtomicReference<>(Attributes.EMPTY);
FakeNameResolverFactory( FakeNameResolverFactory(
URI expectedUri, URI expectedUri,
@ -3367,7 +3367,7 @@ public class ManagedChannelImplTest {
static final class Builder { static final class Builder {
final URI expectedUri; final URI expectedUri;
List<EquivalentAddressGroup> servers = ImmutableList.<EquivalentAddressGroup>of(); List<EquivalentAddressGroup> servers = ImmutableList.of();
boolean resolvedAtStart = true; boolean resolvedAtStart = true;
Status error = null; Status error = null;
@ -3412,7 +3412,7 @@ public class ManagedChannelImplTest {
// We need this because createSubchannel() should be called from the SynchronizationContext // We need this because createSubchannel() should be called from the SynchronizationContext
private static Subchannel createSubchannelSafely( private static Subchannel createSubchannelSafely(
final Helper helper, final EquivalentAddressGroup addressGroup, final Attributes attrs) { final Helper helper, final EquivalentAddressGroup addressGroup, final Attributes attrs) {
final AtomicReference<Subchannel> resultCapture = new AtomicReference<Subchannel>(); final AtomicReference<Subchannel> resultCapture = new AtomicReference<>();
helper.getSynchronizationContext().execute( helper.getSynchronizationContext().execute(
new Runnable() { new Runnable() {
@Override @Override

View File

@ -49,9 +49,9 @@ public final class ManagedChannelOrphanWrapperTest {
ManagedChannel mc = new TestManagedChannel(); ManagedChannel mc = new TestManagedChannel();
String channelString = mc.toString(); String channelString = mc.toString();
final ReferenceQueue<ManagedChannelOrphanWrapper> refqueue = final ReferenceQueue<ManagedChannelOrphanWrapper> refqueue =
new ReferenceQueue<ManagedChannelOrphanWrapper>(); new ReferenceQueue<>();
ConcurrentMap<ManagedChannelReference, ManagedChannelReference> refs = ConcurrentMap<ManagedChannelReference, ManagedChannelReference> refs =
new ConcurrentHashMap<ManagedChannelReference, ManagedChannelReference>(); new ConcurrentHashMap<>();
assertEquals(0, refs.size()); assertEquals(0, refs.size());
ManagedChannelOrphanWrapper channel = new ManagedChannelOrphanWrapper(mc, refqueue, refs); ManagedChannelOrphanWrapper channel = new ManagedChannelOrphanWrapper(mc, refqueue, refs);
@ -103,9 +103,9 @@ public final class ManagedChannelOrphanWrapperTest {
@Test @Test
public void refCycleIsGCed() { public void refCycleIsGCed() {
ReferenceQueue<ManagedChannelOrphanWrapper> refqueue = ReferenceQueue<ManagedChannelOrphanWrapper> refqueue =
new ReferenceQueue<ManagedChannelOrphanWrapper>(); new ReferenceQueue<>();
ConcurrentMap<ManagedChannelReference, ManagedChannelReference> refs = ConcurrentMap<ManagedChannelReference, ManagedChannelReference> refs =
new ConcurrentHashMap<ManagedChannelReference, ManagedChannelReference>(); new ConcurrentHashMap<>();
ApplicationWithChannelRef app = new ApplicationWithChannelRef(); ApplicationWithChannelRef app = new ApplicationWithChannelRef();
ChannelWithApplicationRef channelImpl = new ChannelWithApplicationRef(); ChannelWithApplicationRef channelImpl = new ChannelWithApplicationRef();
ManagedChannelOrphanWrapper channel = ManagedChannelOrphanWrapper channel =
@ -113,7 +113,7 @@ public final class ManagedChannelOrphanWrapperTest {
app.channel = channel; app.channel = channel;
channelImpl.application = app; channelImpl.application = app;
WeakReference<ApplicationWithChannelRef> appWeakRef = WeakReference<ApplicationWithChannelRef> appWeakRef =
new WeakReference<ApplicationWithChannelRef>(app); new WeakReference<>(app);
// Simulate the application and channel going out of scope. A ref cycle between app and // Simulate the application and channel going out of scope. A ref cycle between app and
// channel remains, so ensure that our tracking of orphaned channels does not prevent this // channel remains, so ensure that our tracking of orphaned channels does not prevent this

View File

@ -632,7 +632,7 @@ public class RetriableStreamTest {
ArgumentCaptor<ClientStreamListener> sublistenerCaptor1 = ArgumentCaptor<ClientStreamListener> sublistenerCaptor1 =
ArgumentCaptor.forClass(ClientStreamListener.class); ArgumentCaptor.forClass(ClientStreamListener.class);
final AtomicReference<ClientStreamListener> sublistenerCaptor2 = final AtomicReference<ClientStreamListener> sublistenerCaptor2 =
new AtomicReference<ClientStreamListener>(); new AtomicReference<>();
final Status cancelStatus = Status.CANCELLED.withDescription("c"); final Status cancelStatus = Status.CANCELLED.withDescription("c");
ClientStream mockStream1 = ClientStream mockStream1 =
mock( mock(
@ -762,7 +762,7 @@ public class RetriableStreamTest {
@Test @Test
public void isReady_whileDraining() { public void isReady_whileDraining() {
final AtomicReference<ClientStreamListener> sublistenerCaptor1 = final AtomicReference<ClientStreamListener> sublistenerCaptor1 =
new AtomicReference<ClientStreamListener>(); new AtomicReference<>();
final List<Boolean> readiness = new ArrayList<>(); final List<Boolean> readiness = new ArrayList<>();
ClientStream mockStream1 = ClientStream mockStream1 =
mock( mock(

View File

@ -88,7 +88,7 @@ public class ServerCallImplTest {
public void setUp() { public void setUp() {
MockitoAnnotations.initMocks(this); MockitoAnnotations.initMocks(this);
context = Context.ROOT.withCancellation(); context = Context.ROOT.withCancellation();
call = new ServerCallImpl<Long, Long>(stream, UNARY_METHOD, requestHeaders, context, call = new ServerCallImpl<>(stream, UNARY_METHOD, requestHeaders, context,
DecompressorRegistry.getDefaultInstance(), CompressorRegistry.getDefaultInstance(), DecompressorRegistry.getDefaultInstance(), CompressorRegistry.getDefaultInstance(),
serverCallTracer); serverCallTracer);
} }
@ -111,7 +111,7 @@ public class ServerCallImplTest {
assertEquals(0, before.callsStarted); assertEquals(0, before.callsStarted);
assertEquals(0, before.lastCallStartedNanos); assertEquals(0, before.lastCallStartedNanos);
call = new ServerCallImpl<Long, Long>(stream, UNARY_METHOD, requestHeaders, context, call = new ServerCallImpl<>(stream, UNARY_METHOD, requestHeaders, context,
DecompressorRegistry.getDefaultInstance(), CompressorRegistry.getDefaultInstance(), DecompressorRegistry.getDefaultInstance(), CompressorRegistry.getDefaultInstance(),
tracer); tracer);
@ -217,7 +217,7 @@ public class ServerCallImplTest {
private void sendMessage_serverSendsOne_closeOnSecondCall( private void sendMessage_serverSendsOne_closeOnSecondCall(
MethodDescriptor<Long, Long> method) { MethodDescriptor<Long, Long> method) {
ServerCallImpl<Long, Long> serverCall = new ServerCallImpl<Long, Long>( ServerCallImpl<Long, Long> serverCall = new ServerCallImpl<>(
stream, stream,
method, method,
requestHeaders, requestHeaders,
@ -251,7 +251,7 @@ public class ServerCallImplTest {
private void sendMessage_serverSendsOne_closeOnSecondCall_appRunToCompletion( private void sendMessage_serverSendsOne_closeOnSecondCall_appRunToCompletion(
MethodDescriptor<Long, Long> method) { MethodDescriptor<Long, Long> method) {
ServerCallImpl<Long, Long> serverCall = new ServerCallImpl<Long, Long>( ServerCallImpl<Long, Long> serverCall = new ServerCallImpl<>(
stream, stream,
method, method,
requestHeaders, requestHeaders,
@ -288,7 +288,7 @@ public class ServerCallImplTest {
private void serverSendsOne_okFailsOnMissingResponse( private void serverSendsOne_okFailsOnMissingResponse(
MethodDescriptor<Long, Long> method) { MethodDescriptor<Long, Long> method) {
ServerCallImpl<Long, Long> serverCall = new ServerCallImpl<Long, Long>( ServerCallImpl<Long, Long> serverCall = new ServerCallImpl<>(
stream, stream,
method, method,
requestHeaders, requestHeaders,
@ -343,7 +343,7 @@ public class ServerCallImplTest {
@Test @Test
public void streamListener_halfClosed() { public void streamListener_halfClosed() {
ServerStreamListenerImpl<Long> streamListener = ServerStreamListenerImpl<Long> streamListener =
new ServerCallImpl.ServerStreamListenerImpl<Long>(call, callListener, context); new ServerCallImpl.ServerStreamListenerImpl<>(call, callListener, context);
streamListener.halfClosed(); streamListener.halfClosed();
@ -353,7 +353,7 @@ public class ServerCallImplTest {
@Test @Test
public void streamListener_halfClosed_onlyOnce() { public void streamListener_halfClosed_onlyOnce() {
ServerStreamListenerImpl<Long> streamListener = ServerStreamListenerImpl<Long> streamListener =
new ServerCallImpl.ServerStreamListenerImpl<Long>(call, callListener, context); new ServerCallImpl.ServerStreamListenerImpl<>(call, callListener, context);
streamListener.halfClosed(); streamListener.halfClosed();
// canceling the call should short circuit future halfClosed() calls. // canceling the call should short circuit future halfClosed() calls.
streamListener.closed(Status.CANCELLED); streamListener.closed(Status.CANCELLED);
@ -366,7 +366,7 @@ public class ServerCallImplTest {
@Test @Test
public void streamListener_closedOk() { public void streamListener_closedOk() {
ServerStreamListenerImpl<Long> streamListener = ServerStreamListenerImpl<Long> streamListener =
new ServerCallImpl.ServerStreamListenerImpl<Long>(call, callListener, context); new ServerCallImpl.ServerStreamListenerImpl<>(call, callListener, context);
streamListener.closed(Status.OK); streamListener.closed(Status.OK);
@ -378,7 +378,7 @@ public class ServerCallImplTest {
@Test @Test
public void streamListener_closedCancelled() { public void streamListener_closedCancelled() {
ServerStreamListenerImpl<Long> streamListener = ServerStreamListenerImpl<Long> streamListener =
new ServerCallImpl.ServerStreamListenerImpl<Long>(call, callListener, context); new ServerCallImpl.ServerStreamListenerImpl<>(call, callListener, context);
streamListener.closed(Status.CANCELLED); streamListener.closed(Status.CANCELLED);
@ -390,7 +390,7 @@ public class ServerCallImplTest {
@Test @Test
public void streamListener_onReady() { public void streamListener_onReady() {
ServerStreamListenerImpl<Long> streamListener = ServerStreamListenerImpl<Long> streamListener =
new ServerCallImpl.ServerStreamListenerImpl<Long>(call, callListener, context); new ServerCallImpl.ServerStreamListenerImpl<>(call, callListener, context);
streamListener.onReady(); streamListener.onReady();
@ -400,7 +400,7 @@ public class ServerCallImplTest {
@Test @Test
public void streamListener_onReady_onlyOnce() { public void streamListener_onReady_onlyOnce() {
ServerStreamListenerImpl<Long> streamListener = ServerStreamListenerImpl<Long> streamListener =
new ServerCallImpl.ServerStreamListenerImpl<Long>(call, callListener, context); new ServerCallImpl.ServerStreamListenerImpl<>(call, callListener, context);
streamListener.onReady(); streamListener.onReady();
// canceling the call should short circuit future halfClosed() calls. // canceling the call should short circuit future halfClosed() calls.
streamListener.closed(Status.CANCELLED); streamListener.closed(Status.CANCELLED);
@ -413,7 +413,7 @@ public class ServerCallImplTest {
@Test @Test
public void streamListener_messageRead() { public void streamListener_messageRead() {
ServerStreamListenerImpl<Long> streamListener = ServerStreamListenerImpl<Long> streamListener =
new ServerCallImpl.ServerStreamListenerImpl<Long>(call, callListener, context); new ServerCallImpl.ServerStreamListenerImpl<>(call, callListener, context);
streamListener.messagesAvailable(new SingleMessageProducer(UNARY_METHOD.streamRequest(1234L))); streamListener.messagesAvailable(new SingleMessageProducer(UNARY_METHOD.streamRequest(1234L)));
verify(callListener).onMessage(1234L); verify(callListener).onMessage(1234L);
@ -422,7 +422,7 @@ public class ServerCallImplTest {
@Test @Test
public void streamListener_messageRead_onlyOnce() { public void streamListener_messageRead_onlyOnce() {
ServerStreamListenerImpl<Long> streamListener = ServerStreamListenerImpl<Long> streamListener =
new ServerCallImpl.ServerStreamListenerImpl<Long>(call, callListener, context); new ServerCallImpl.ServerStreamListenerImpl<>(call, callListener, context);
streamListener.messagesAvailable(new SingleMessageProducer(UNARY_METHOD.streamRequest(1234L))); streamListener.messagesAvailable(new SingleMessageProducer(UNARY_METHOD.streamRequest(1234L)));
// canceling the call should short circuit future halfClosed() calls. // canceling the call should short circuit future halfClosed() calls.
streamListener.closed(Status.CANCELLED); streamListener.closed(Status.CANCELLED);
@ -435,7 +435,7 @@ public class ServerCallImplTest {
@Test @Test
public void streamListener_unexpectedRuntimeException() { public void streamListener_unexpectedRuntimeException() {
ServerStreamListenerImpl<Long> streamListener = ServerStreamListenerImpl<Long> streamListener =
new ServerCallImpl.ServerStreamListenerImpl<Long>(call, callListener, context); new ServerCallImpl.ServerStreamListenerImpl<>(call, callListener, context);
doThrow(new RuntimeException("unexpected exception")) doThrow(new RuntimeException("unexpected exception"))
.when(callListener) .when(callListener)
.onMessage(any(Long.class)); .onMessage(any(Long.class));

View File

@ -504,8 +504,8 @@ public class ServerImplTest {
final Metadata.Key<String> metadataKey final Metadata.Key<String> metadataKey
= Metadata.Key.of("inception", Metadata.ASCII_STRING_MARSHALLER); = Metadata.Key.of("inception", Metadata.ASCII_STRING_MARSHALLER);
final AtomicReference<ServerCall<String, Integer>> callReference final AtomicReference<ServerCall<String, Integer>> callReference
= new AtomicReference<ServerCall<String, Integer>>(); = new AtomicReference<>();
final AtomicReference<Context> callContextReference = new AtomicReference<Context>(); final AtomicReference<Context> callContextReference = new AtomicReference<>();
mutableFallbackRegistry.addService(ServerServiceDefinition.builder( mutableFallbackRegistry.addService(ServerServiceDefinition.builder(
new ServiceDescriptor("Waiter", method)) new ServiceDescriptor("Waiter", method))
.addMethod( .addMethod(
@ -545,7 +545,7 @@ public class ServerImplTest {
ServerCall<String, Integer> call = callReference.get(); ServerCall<String, Integer> call = callReference.get();
assertNotNull(call); assertNotNull(call);
assertEquals( assertEquals(
new ServerCallInfoImpl<String, Integer>( new ServerCallInfoImpl<>(
call.getMethodDescriptor(), call.getMethodDescriptor(),
call.getAttributes(), call.getAttributes(),
call.getAuthority()), call.getAuthority()),
@ -606,9 +606,9 @@ public class ServerImplTest {
final Attributes.Key<String> key2 = Attributes.Key.create("test-key2"); final Attributes.Key<String> key2 = Attributes.Key.create("test-key2");
final Attributes.Key<String> key3 = Attributes.Key.create("test-key3"); final Attributes.Key<String> key3 = Attributes.Key.create("test-key3");
final AtomicReference<Attributes> filter1TerminationCallbackArgument = final AtomicReference<Attributes> filter1TerminationCallbackArgument =
new AtomicReference<Attributes>(); new AtomicReference<>();
final AtomicReference<Attributes> filter2TerminationCallbackArgument = final AtomicReference<Attributes> filter2TerminationCallbackArgument =
new AtomicReference<Attributes>(); new AtomicReference<>();
final AtomicInteger readyCallbackCalled = new AtomicInteger(0); final AtomicInteger readyCallbackCalled = new AtomicInteger(0);
final AtomicInteger terminationCallbackCalled = new AtomicInteger(0); final AtomicInteger terminationCallbackCalled = new AtomicInteger(0);
builder.addTransportFilter(new ServerTransportFilter() { builder.addTransportFilter(new ServerTransportFilter() {
@ -677,7 +677,7 @@ public class ServerImplTest {
@Test @Test
public void interceptors() throws Exception { public void interceptors() throws Exception {
final LinkedList<Context> capturedContexts = new LinkedList<Context>(); final LinkedList<Context> capturedContexts = new LinkedList<>();
final Context.Key<String> key1 = Context.key("key1"); final Context.Key<String> key1 = Context.key("key1");
final Context.Key<String> key2 = Context.key("key2"); final Context.Key<String> key2 = Context.key("key2");
final Context.Key<String> key3 = Context.key("key3"); final Context.Key<String> key3 = Context.key("key3");
@ -1024,9 +1024,9 @@ public class ServerImplTest {
@Test @Test
public void testClientClose_cancelTriggersImmediateCancellation() throws Exception { public void testClientClose_cancelTriggersImmediateCancellation() throws Exception {
AtomicBoolean contextCancelled = new AtomicBoolean(false); AtomicBoolean contextCancelled = new AtomicBoolean(false);
AtomicReference<Context> context = new AtomicReference<Context>(); AtomicReference<Context> context = new AtomicReference<>();
AtomicReference<ServerCall<String, Integer>> callReference AtomicReference<ServerCall<String, Integer>> callReference
= new AtomicReference<ServerCall<String, Integer>>(); = new AtomicReference<>();
ServerStreamListener streamListener = testClientClose_setup(callReference, ServerStreamListener streamListener = testClientClose_setup(callReference,
context, contextCancelled); context, contextCancelled);
@ -1047,9 +1047,9 @@ public class ServerImplTest {
@Test @Test
public void testClientClose_OkTriggersDelayedCancellation() throws Exception { public void testClientClose_OkTriggersDelayedCancellation() throws Exception {
AtomicBoolean contextCancelled = new AtomicBoolean(false); AtomicBoolean contextCancelled = new AtomicBoolean(false);
AtomicReference<Context> context = new AtomicReference<Context>(); AtomicReference<Context> context = new AtomicReference<>();
AtomicReference<ServerCall<String, Integer>> callReference AtomicReference<ServerCall<String, Integer>> callReference
= new AtomicReference<ServerCall<String, Integer>>(); = new AtomicReference<>();
ServerStreamListener streamListener = testClientClose_setup(callReference, ServerStreamListener streamListener = testClientClose_setup(callReference,
context, contextCancelled); context, contextCancelled);

View File

@ -46,7 +46,7 @@ import org.mockito.stubbing.Answer;
public class SharedResourceHolderTest { public class SharedResourceHolderTest {
private final LinkedList<MockScheduledFuture<?>> scheduledDestroyTasks = private final LinkedList<MockScheduledFuture<?>> scheduledDestroyTasks =
new LinkedList<MockScheduledFuture<?>>(); new LinkedList<>();
private SharedResourceHolder holder; private SharedResourceHolder holder;
@ -186,7 +186,7 @@ public class SharedResourceHolderTest {
Runnable command = (Runnable) args[0]; Runnable command = (Runnable) args[0];
long delay = (Long) args[1]; long delay = (Long) args[1];
TimeUnit unit = (TimeUnit) args[2]; TimeUnit unit = (TimeUnit) args[2];
MockScheduledFuture<Void> future = new MockScheduledFuture<Void>( MockScheduledFuture<Void> future = new MockScheduledFuture<>(
command, delay, unit); command, delay, unit);
scheduledDestroyTasks.add(future); scheduledDestroyTasks.add(future);
return future; return future;

View File

@ -69,7 +69,7 @@ final class TestUtils {
static BlockingQueue<MockClientTransportInfo> captureTransports( static BlockingQueue<MockClientTransportInfo> captureTransports(
ClientTransportFactory mockTransportFactory, @Nullable final Runnable startRunnable) { ClientTransportFactory mockTransportFactory, @Nullable final Runnable startRunnable) {
final BlockingQueue<MockClientTransportInfo> captor = final BlockingQueue<MockClientTransportInfo> captor =
new LinkedBlockingQueue<MockClientTransportInfo>(); new LinkedBlockingQueue<>();
doAnswer(new Answer<ConnectionClientTransport>() { doAnswer(new Answer<ConnectionClientTransport>() {
@Override @Override

View File

@ -56,7 +56,7 @@ public class ForwardingLoadBalancerHelperTest {
if (clazz.equals(EquivalentAddressGroup.class)) { if (clazz.equals(EquivalentAddressGroup.class)) {
return new EquivalentAddressGroup(Arrays.asList(mockAddr)); return new EquivalentAddressGroup(Arrays.asList(mockAddr));
} else if (clazz.equals(List.class)) { } else if (clazz.equals(List.class)) {
return Collections.<Object>emptyList(); return Collections.emptyList();
} }
return null; return null;
} }

View File

@ -186,7 +186,7 @@ public class RoundRobinLoadBalancerTest {
List<EquivalentAddressGroup> eagList = List<EquivalentAddressGroup> eagList =
Arrays.asList(new EquivalentAddressGroup(allAddrs.get(i))); Arrays.asList(new EquivalentAddressGroup(allAddrs.get(i)));
when(subchannel.getAttributes()).thenReturn(Attributes.newBuilder().set(STATE_INFO, when(subchannel.getAttributes()).thenReturn(Attributes.newBuilder().set(STATE_INFO,
new Ref<ConnectivityStateInfo>( new Ref<>(
ConnectivityStateInfo.forNonError(READY))).build()); ConnectivityStateInfo.forNonError(READY))).build());
when(subchannel.getAllAddresses()).thenReturn(eagList); when(subchannel.getAllAddresses()).thenReturn(eagList);
} }
@ -306,7 +306,7 @@ public class RoundRobinLoadBalancerTest {
Subchannel subchannel2 = mock(Subchannel.class); Subchannel subchannel2 = mock(Subchannel.class);
ReadyPicker picker = new ReadyPicker(Collections.unmodifiableList( ReadyPicker picker = new ReadyPicker(Collections.unmodifiableList(
Lists.<Subchannel>newArrayList(subchannel, subchannel1, subchannel2)), Lists.newArrayList(subchannel, subchannel1, subchannel2)),
0 /* startIndex */, null /* stickinessState */); 0 /* startIndex */, null /* stickinessState */);
assertThat(picker.getList()).containsExactly(subchannel, subchannel1, subchannel2); assertThat(picker.getList()).containsExactly(subchannel, subchannel1, subchannel2);
@ -438,7 +438,7 @@ public class RoundRobinLoadBalancerTest {
@Test @Test
public void stickinessEnabled_withoutStickyHeader() { public void stickinessEnabled_withoutStickyHeader() {
Map<String, Object> serviceConfig = new HashMap<String, Object>(); Map<String, Object> serviceConfig = new HashMap<>();
serviceConfig.put("stickinessMetadataKey", "my-sticky-key"); serviceConfig.put("stickinessMetadataKey", "my-sticky-key");
Attributes attributes = Attributes.newBuilder() Attributes attributes = Attributes.newBuilder()
.set(GrpcAttributes.NAME_RESOLVER_SERVICE_CONFIG, serviceConfig).build(); .set(GrpcAttributes.NAME_RESOLVER_SERVICE_CONFIG, serviceConfig).build();
@ -470,7 +470,7 @@ public class RoundRobinLoadBalancerTest {
@Test @Test
public void stickinessEnabled_withStickyHeader() { public void stickinessEnabled_withStickyHeader() {
Map<String, Object> serviceConfig = new HashMap<String, Object>(); Map<String, Object> serviceConfig = new HashMap<>();
serviceConfig.put("stickinessMetadataKey", "my-sticky-key"); serviceConfig.put("stickinessMetadataKey", "my-sticky-key");
Attributes attributes = Attributes.newBuilder() Attributes attributes = Attributes.newBuilder()
.set(GrpcAttributes.NAME_RESOLVER_SERVICE_CONFIG, serviceConfig).build(); .set(GrpcAttributes.NAME_RESOLVER_SERVICE_CONFIG, serviceConfig).build();
@ -500,7 +500,7 @@ public class RoundRobinLoadBalancerTest {
@Test @Test
public void stickinessEnabled_withDifferentStickyHeaders() { public void stickinessEnabled_withDifferentStickyHeaders() {
Map<String, Object> serviceConfig = new HashMap<String, Object>(); Map<String, Object> serviceConfig = new HashMap<>();
serviceConfig.put("stickinessMetadataKey", "my-sticky-key"); serviceConfig.put("stickinessMetadataKey", "my-sticky-key");
Attributes attributes = Attributes.newBuilder() Attributes attributes = Attributes.newBuilder()
.set(GrpcAttributes.NAME_RESOLVER_SERVICE_CONFIG, serviceConfig).build(); .set(GrpcAttributes.NAME_RESOLVER_SERVICE_CONFIG, serviceConfig).build();
@ -545,7 +545,7 @@ public class RoundRobinLoadBalancerTest {
@Test @Test
public void stickiness_goToTransientFailure_pick_backToReady() { public void stickiness_goToTransientFailure_pick_backToReady() {
Map<String, Object> serviceConfig = new HashMap<String, Object>(); Map<String, Object> serviceConfig = new HashMap<>();
serviceConfig.put("stickinessMetadataKey", "my-sticky-key"); serviceConfig.put("stickinessMetadataKey", "my-sticky-key");
Attributes attributes = Attributes.newBuilder() Attributes attributes = Attributes.newBuilder()
.set(GrpcAttributes.NAME_RESOLVER_SERVICE_CONFIG, serviceConfig).build(); .set(GrpcAttributes.NAME_RESOLVER_SERVICE_CONFIG, serviceConfig).build();
@ -593,7 +593,7 @@ public class RoundRobinLoadBalancerTest {
@Test @Test
public void stickiness_goToTransientFailure_backToReady_pick() { public void stickiness_goToTransientFailure_backToReady_pick() {
Map<String, Object> serviceConfig = new HashMap<String, Object>(); Map<String, Object> serviceConfig = new HashMap<>();
serviceConfig.put("stickinessMetadataKey", "my-sticky-key"); serviceConfig.put("stickinessMetadataKey", "my-sticky-key");
Attributes attributes = Attributes.newBuilder() Attributes attributes = Attributes.newBuilder()
.set(GrpcAttributes.NAME_RESOLVER_SERVICE_CONFIG, serviceConfig).build(); .set(GrpcAttributes.NAME_RESOLVER_SERVICE_CONFIG, serviceConfig).build();
@ -647,7 +647,7 @@ public class RoundRobinLoadBalancerTest {
@Test @Test
public void stickiness_oneSubchannelShutdown() { public void stickiness_oneSubchannelShutdown() {
Map<String, Object> serviceConfig = new HashMap<String, Object>(); Map<String, Object> serviceConfig = new HashMap<>();
serviceConfig.put("stickinessMetadataKey", "my-sticky-key"); serviceConfig.put("stickinessMetadataKey", "my-sticky-key");
Attributes attributes = Attributes.newBuilder() Attributes attributes = Attributes.newBuilder()
.set(GrpcAttributes.NAME_RESOLVER_SERVICE_CONFIG, serviceConfig).build(); .set(GrpcAttributes.NAME_RESOLVER_SERVICE_CONFIG, serviceConfig).build();
@ -703,14 +703,14 @@ public class RoundRobinLoadBalancerTest {
@Test @Test
public void stickiness_resolveTwice_metadataKeyChanged() { public void stickiness_resolveTwice_metadataKeyChanged() {
Map<String, Object> serviceConfig1 = new HashMap<String, Object>(); Map<String, Object> serviceConfig1 = new HashMap<>();
serviceConfig1.put("stickinessMetadataKey", "my-sticky-key1"); serviceConfig1.put("stickinessMetadataKey", "my-sticky-key1");
Attributes attributes1 = Attributes.newBuilder() Attributes attributes1 = Attributes.newBuilder()
.set(GrpcAttributes.NAME_RESOLVER_SERVICE_CONFIG, serviceConfig1).build(); .set(GrpcAttributes.NAME_RESOLVER_SERVICE_CONFIG, serviceConfig1).build();
loadBalancer.handleResolvedAddressGroups(servers, attributes1); loadBalancer.handleResolvedAddressGroups(servers, attributes1);
Map<String, ?> stickinessMap1 = loadBalancer.getStickinessMapForTest(); Map<String, ?> stickinessMap1 = loadBalancer.getStickinessMapForTest();
Map<String, Object> serviceConfig2 = new HashMap<String, Object>(); Map<String, Object> serviceConfig2 = new HashMap<>();
serviceConfig2.put("stickinessMetadataKey", "my-sticky-key2"); serviceConfig2.put("stickinessMetadataKey", "my-sticky-key2");
Attributes attributes2 = Attributes.newBuilder() Attributes attributes2 = Attributes.newBuilder()
.set(GrpcAttributes.NAME_RESOLVER_SERVICE_CONFIG, serviceConfig2).build(); .set(GrpcAttributes.NAME_RESOLVER_SERVICE_CONFIG, serviceConfig2).build();
@ -722,7 +722,7 @@ public class RoundRobinLoadBalancerTest {
@Test @Test
public void stickiness_resolveTwice_metadataKeyUnChanged() { public void stickiness_resolveTwice_metadataKeyUnChanged() {
Map<String, Object> serviceConfig1 = new HashMap<String, Object>(); Map<String, Object> serviceConfig1 = new HashMap<>();
serviceConfig1.put("stickinessMetadataKey", "my-sticky-key1"); serviceConfig1.put("stickinessMetadataKey", "my-sticky-key1");
Attributes attributes1 = Attributes.newBuilder() Attributes attributes1 = Attributes.newBuilder()
.set(GrpcAttributes.NAME_RESOLVER_SERVICE_CONFIG, serviceConfig1).build(); .set(GrpcAttributes.NAME_RESOLVER_SERVICE_CONFIG, serviceConfig1).build();

View File

@ -76,7 +76,7 @@ public class UtilServerInterceptorsTest {
final Status expectedStatus = Status.UNAVAILABLE; final Status expectedStatus = Status.UNAVAILABLE;
final Metadata expectedMetadata = new Metadata(); final Metadata expectedMetadata = new Metadata();
FakeServerCall<Void, Void> call = FakeServerCall<Void, Void> call =
new FakeServerCall<Void, Void>(expectedStatus, expectedMetadata); new FakeServerCall<>(expectedStatus, expectedMetadata);
final StatusRuntimeException exception = final StatusRuntimeException exception =
new StatusRuntimeException(expectedStatus, expectedMetadata); new StatusRuntimeException(expectedStatus, expectedMetadata);
listener = new VoidCallListener() { listener = new VoidCallListener() {
@ -126,7 +126,7 @@ public class UtilServerInterceptorsTest {
final Metadata expectedMetadata = new Metadata(); final Metadata expectedMetadata = new Metadata();
FakeServerCall<Void, Void> call = FakeServerCall<Void, Void> call =
new FakeServerCall<Void, Void>(expectedStatus, expectedMetadata); new FakeServerCall<>(expectedStatus, expectedMetadata);
final StatusRuntimeException exception = final StatusRuntimeException exception =
new StatusRuntimeException(expectedStatus, expectedMetadata); new StatusRuntimeException(expectedStatus, expectedMetadata);

View File

@ -159,7 +159,7 @@ public class RouteGuideServerTest {
assertTrue(latch.await(1, TimeUnit.SECONDS)); assertTrue(latch.await(1, TimeUnit.SECONDS));
// verify // verify
assertEquals(new HashSet<Feature>(Arrays.asList(f2, f3)), result); assertEquals(new HashSet<>(Arrays.asList(f2, f3)), result);
} }
@Test @Test

View File

@ -34,7 +34,7 @@ import java.util.concurrent.TimeUnit;
*/ */
final class CachedSubchannelPool implements SubchannelPool { final class CachedSubchannelPool implements SubchannelPool {
private final HashMap<EquivalentAddressGroup, CacheEntry> cache = private final HashMap<EquivalentAddressGroup, CacheEntry> cache =
new HashMap<EquivalentAddressGroup, CacheEntry>(); new HashMap<>();
private Helper helper; private Helper helper;

View File

@ -64,7 +64,7 @@ final class GrpclbClientLoadRecorder extends ClientStreamTracer.Factory {
// Specific finish types // Specific finish types
@GuardedBy("this") @GuardedBy("this")
private Map<String, LongHolder> callsDroppedPerToken = new HashMap<String, LongHolder>(1); private Map<String, LongHolder> callsDroppedPerToken = new HashMap<>(1);
@SuppressWarnings("unused") @SuppressWarnings("unused")
private volatile long callsFailedToSend; private volatile long callsFailedToSend;
@SuppressWarnings("unused") @SuppressWarnings("unused")
@ -112,7 +112,7 @@ final class GrpclbClientLoadRecorder extends ClientStreamTracer.Factory {
synchronized (this) { synchronized (this) {
if (!callsDroppedPerToken.isEmpty()) { if (!callsDroppedPerToken.isEmpty()) {
localCallsDroppedPerToken = callsDroppedPerToken; localCallsDroppedPerToken = callsDroppedPerToken;
callsDroppedPerToken = new HashMap<String, LongHolder>(localCallsDroppedPerToken.size()); callsDroppedPerToken = new HashMap<>(localCallsDroppedPerToken.size());
} }
} }
for (Entry<String, LongHolder> entry : localCallsDroppedPerToken.entrySet()) { for (Entry<String, LongHolder> entry : localCallsDroppedPerToken.entrySet()) {

View File

@ -335,7 +335,7 @@ final class GrpclbState {
logger.log( logger.log(
ChannelLogLevel.INFO, "Using RR list={0}, drop={1}", newBackendAddrList, newDropList); ChannelLogLevel.INFO, "Using RR list={0}, drop={1}", newBackendAddrList, newDropList);
HashMap<EquivalentAddressGroup, Subchannel> newSubchannelMap = HashMap<EquivalentAddressGroup, Subchannel> newSubchannelMap =
new HashMap<EquivalentAddressGroup, Subchannel>(); new HashMap<>();
List<BackendEntry> newBackendList = new ArrayList<>(); List<BackendEntry> newBackendList = new ArrayList<>();
for (BackendAddressGroup backendAddr : newBackendAddrList) { for (BackendAddressGroup backendAddr : newBackendAddrList) {
@ -346,7 +346,7 @@ final class GrpclbState {
if (subchannel == null) { if (subchannel == null) {
Attributes subchannelAttrs = Attributes.newBuilder() Attributes subchannelAttrs = Attributes.newBuilder()
.set(STATE_INFO, .set(STATE_INFO,
new AtomicReference<ConnectivityStateInfo>( new AtomicReference<>(
ConnectivityStateInfo.forNonError(IDLE))) ConnectivityStateInfo.forNonError(IDLE)))
.build(); .build();
subchannel = subchannelPool.takeOrCreateSubchannel(eag, subchannelAttrs); subchannel = subchannelPool.takeOrCreateSubchannel(eag, subchannelAttrs);

View File

@ -141,7 +141,7 @@ public class GrpclbLoadBalancerTest {
private Helper helper; private Helper helper;
@Mock @Mock
private SubchannelPool subchannelPool; private SubchannelPool subchannelPool;
private final ArrayList<String> logs = new ArrayList<String>(); private final ArrayList<String> logs = new ArrayList<>();
private final ChannelLogger channelLogger = new ChannelLogger() { private final ChannelLogger channelLogger = new ChannelLogger() {
@Override @Override
public void log(ChannelLogLevel level, String msg) { public void log(ChannelLogLevel level, String msg) {
@ -159,9 +159,9 @@ public class GrpclbLoadBalancerTest {
private ArgumentCaptor<StreamObserver<LoadBalanceResponse>> lbResponseObserverCaptor; private ArgumentCaptor<StreamObserver<LoadBalanceResponse>> lbResponseObserverCaptor;
private final FakeClock fakeClock = new FakeClock(); private final FakeClock fakeClock = new FakeClock();
private final LinkedList<StreamObserver<LoadBalanceRequest>> lbRequestObservers = private final LinkedList<StreamObserver<LoadBalanceRequest>> lbRequestObservers =
new LinkedList<StreamObserver<LoadBalanceRequest>>(); new LinkedList<>();
private final LinkedList<Subchannel> mockSubchannels = new LinkedList<Subchannel>(); private final LinkedList<Subchannel> mockSubchannels = new LinkedList<>();
private final LinkedList<ManagedChannel> fakeOobChannels = new LinkedList<ManagedChannel>(); private final LinkedList<ManagedChannel> fakeOobChannels = new LinkedList<>();
private final ArrayList<Subchannel> subchannelTracker = new ArrayList<>(); private final ArrayList<Subchannel> subchannelTracker = new ArrayList<>();
private final ArrayList<ManagedChannel> oobChannelTracker = new ArrayList<>(); private final ArrayList<ManagedChannel> oobChannelTracker = new ArrayList<>();
private final ArrayList<String> failingLbAuthorities = new ArrayList<>(); private final ArrayList<String> failingLbAuthorities = new ArrayList<>();

View File

@ -109,7 +109,7 @@ public class StressTestClient {
private Server metricsServer; private Server metricsServer;
private final Map<String, Metrics.GaugeResponse> gauges = private final Map<String, Metrics.GaugeResponse> gauges =
new ConcurrentHashMap<String, Metrics.GaugeResponse>(); new ConcurrentHashMap<>();
private volatile boolean shutdown; private volatile boolean shutdown;
@ -117,7 +117,7 @@ public class StressTestClient {
* List of futures that {@link #blockUntilStressTestComplete()} waits for. * List of futures that {@link #blockUntilStressTestComplete()} waits for.
*/ */
private final List<ListenableFuture<?>> workerFutures = private final List<ListenableFuture<?>> workerFutures =
new ArrayList<ListenableFuture<?>>(); new ArrayList<>();
private final List<ManagedChannel> channels = new ArrayList<>(); private final List<ManagedChannel> channels = new ArrayList<>();
private ListeningExecutorService threadpool; private ListeningExecutorService threadpool;
@ -325,7 +325,7 @@ public class StressTestClient {
} }
private static List<List<String>> parseCommaSeparatedTuples(String str) { private static List<List<String>> parseCommaSeparatedTuples(String str) {
List<List<String>> tuples = new ArrayList<List<String>>(); List<List<String>> tuples = new ArrayList<>();
for (String tupleStr : Splitter.on(',').split(str)) { for (String tupleStr : Splitter.on(',').split(str)) {
int splitIdx = tupleStr.lastIndexOf(':'); int splitIdx = tupleStr.lastIndexOf(':');
if (splitIdx == -1) { if (splitIdx == -1) {

View File

@ -372,7 +372,7 @@ public class TestServiceImpl extends TestServiceGrpc.TestServiceImplBase {
* Breaks down the request and creates a queue of response chunks for the given request. * Breaks down the request and creates a queue of response chunks for the given request.
*/ */
public Queue<Chunk> toChunkQueue(StreamingOutputCallRequest request) { public Queue<Chunk> toChunkQueue(StreamingOutputCallRequest request) {
Queue<Chunk> chunkQueue = new ArrayDeque<Chunk>(); Queue<Chunk> chunkQueue = new ArrayDeque<>();
int offset = 0; int offset = 0;
for (ResponseParameters params : request.getResponseParametersList()) { for (ResponseParameters params : request.getResponseParametersList()) {
chunkQueue.add(new Chunk(params.getIntervalUs(), offset, params.getSize())); chunkQueue.add(new Chunk(params.getIntervalUs(), offset, params.getSize()));

View File

@ -55,9 +55,9 @@ public class ChannelAndServerBuilderTest {
ClassPath.from(loader).getTopLevelClassesRecursive("io.grpc"); ClassPath.from(loader).getTopLevelClassesRecursive("io.grpc");
// Java 9 doesn't expose the URLClassLoader, which breaks searching through the classpath // Java 9 doesn't expose the URLClassLoader, which breaks searching through the classpath
if (classInfos.isEmpty()) { if (classInfos.isEmpty()) {
return new ArrayList<Object[]>(); return new ArrayList<>();
} }
List<Object[]> classes = new ArrayList<Object[]>(); List<Object[]> classes = new ArrayList<>();
for (ClassInfo classInfo : classInfos) { for (ClassInfo classInfo : classInfos) {
Class<?> clazz = Class.forName(classInfo.getName(), false /*initialize*/, loader); Class<?> clazz = Class.forName(classInfo.getName(), false /*initialize*/, loader);
if (ServerBuilder.class.isAssignableFrom(clazz) && clazz != ServerBuilder.class) { if (ServerBuilder.class.isAssignableFrom(clazz) && clazz != ServerBuilder.class) {

Some files were not shown because too many files have changed in this diff Show More