View Javadoc
1   /*
2    * Copyright 2015 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   https://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  
17  package io.netty.resolver.dns;
18  
19  import io.netty.util.internal.PlatformDependent;
20  
21  import java.net.InetSocketAddress;
22  import java.util.Collections;
23  import java.util.List;
24  
25  final class ShuffledDnsServerAddressStream implements DnsServerAddressStream {
26  
27      private final List<InetSocketAddress> addresses;
28      private int i;
29  
30      /**
31       * Create a new instance.
32       * @param addresses The addresses are not cloned. It is assumed the caller has cloned this array or otherwise will
33       *                  not modify the contents.
34       */
35      ShuffledDnsServerAddressStream(List<InetSocketAddress> addresses) {
36          this.addresses = addresses;
37  
38          shuffle();
39      }
40  
41      private ShuffledDnsServerAddressStream(List<InetSocketAddress> addresses, int startIdx) {
42          this.addresses = addresses;
43          i = startIdx;
44      }
45  
46      private void shuffle() {
47          Collections.shuffle(addresses, PlatformDependent.threadLocalRandom());
48      }
49  
50      @Override
51      public InetSocketAddress next() {
52          int i = this.i;
53          InetSocketAddress next = addresses.get(i);
54          if (++ i < addresses.size()) {
55              this.i = i;
56          } else {
57              this.i = 0;
58              shuffle();
59          }
60          return next;
61      }
62  
63      @Override
64      public int size() {
65          return addresses.size();
66      }
67  
68      @Override
69      public ShuffledDnsServerAddressStream duplicate() {
70          return new ShuffledDnsServerAddressStream(addresses, i);
71      }
72  
73      @Override
74      public String toString() {
75          return SequentialDnsServerAddressStream.toString("shuffled", i, addresses);
76      }
77  }