1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
32
33
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 }