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.netty5.resolver.dns;
18  
19  import java.net.InetSocketAddress;
20  import java.util.Collections;
21  import java.util.List;
22  import java.util.concurrent.ThreadLocalRandom;
23  
24  final class ShuffledDnsServerAddressStream implements DnsServerAddressStream {
25  
26      private final List<InetSocketAddress> addresses;
27      private int i;
28  
29      /**
30       * Create a new instance.
31       * @param addresses The addresses are not cloned. It is assumed the caller has cloned this array or otherwise will
32       *                  not modify the contents.
33       */
34      ShuffledDnsServerAddressStream(List<InetSocketAddress> addresses) {
35          this.addresses = addresses;
36  
37          shuffle();
38      }
39  
40      private ShuffledDnsServerAddressStream(List<InetSocketAddress> addresses, int startIdx) {
41          this.addresses = addresses;
42          i = startIdx;
43      }
44  
45      private void shuffle() {
46          Collections.shuffle(addresses, ThreadLocalRandom.current());
47      }
48  
49      @Override
50      public InetSocketAddress next() {
51          int i = this.i;
52          InetSocketAddress next = addresses.get(i);
53          if (++ i < addresses.size()) {
54              this.i = i;
55          } else {
56              this.i = 0;
57              shuffle();
58          }
59          return next;
60      }
61  
62      @Override
63      public int size() {
64          return addresses.size();
65      }
66  
67      @Override
68      public ShuffledDnsServerAddressStream duplicate() {
69          return new ShuffledDnsServerAddressStream(addresses, i);
70      }
71  
72      @Override
73      public String toString() {
74          return SequentialDnsServerAddressStream.toString("shuffled", i, addresses);
75      }
76  }