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