Skip to content

Commit dbab8c5

Browse files
kun-songbeiwei30
authored andcommitted
[Enhancement] Use ThreadLocalRandom and try-with-resource (#3239)
* polish * fix code reviews * empty
1 parent ea45921 commit dbab8c5

File tree

4 files changed

+48
-65
lines changed

4 files changed

+48
-65
lines changed

dubbo-common/src/main/java/org/apache/dubbo/common/utils/NetUtils.java

Lines changed: 32 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -32,47 +32,41 @@
3232
import java.net.UnknownHostException;
3333
import java.util.Enumeration;
3434
import java.util.Map;
35-
import java.util.Random;
35+
import java.util.Optional;
36+
import java.util.concurrent.ThreadLocalRandom;
3637
import java.util.regex.Pattern;
3738

3839
/**
3940
* IP and Port Helper for RPC
4041
*/
4142
public class NetUtils {
42-
4343
private static final Logger logger = LoggerFactory.getLogger(NetUtils.class);
44-
private static final int RND_PORT_START = 30000;
4544

45+
// returned port range is [30000, 39999]
46+
private static final int RND_PORT_START = 30000;
4647
private static final int RND_PORT_RANGE = 10000;
4748

48-
private static final Random RANDOM = new Random(System.currentTimeMillis());
49+
// valid port range is (0, 65535]
4950
private static final int MIN_PORT = 0;
5051
private static final int MAX_PORT = 65535;
52+
5153
private static final Pattern ADDRESS_PATTERN = Pattern.compile("^\\d{1,3}(\\.\\d{1,3}){3}\\:\\d{1,5}$");
5254
private static final Pattern LOCAL_IP_PATTERN = Pattern.compile("127(\\.\\d{1,3}){3}$");
5355
private static final Pattern IP_PATTERN = Pattern.compile("\\d{1,3}(\\.\\d{1,3}){3,5}$");
54-
private static final Map<String, String> hostNameCache = new LRUCache<String, String>(1000);
56+
57+
private static final Map<String, String> hostNameCache = new LRUCache<>(1000);
5558
private static volatile InetAddress LOCAL_ADDRESS = null;
5659

5760
public static int getRandomPort() {
58-
return RND_PORT_START + RANDOM.nextInt(RND_PORT_RANGE);
61+
return RND_PORT_START + ThreadLocalRandom.current().nextInt(RND_PORT_RANGE);
5962
}
6063

6164
public static int getAvailablePort() {
62-
ServerSocket ss = null;
63-
try {
64-
ss = new ServerSocket();
65+
try (ServerSocket ss = new ServerSocket()) {
6566
ss.bind(null);
6667
return ss.getLocalPort();
6768
} catch (IOException e) {
6869
return getRandomPort();
69-
} finally {
70-
if (ss != null) {
71-
try {
72-
ss.close();
73-
} catch (IOException e) {
74-
}
75-
}
7670
}
7771
}
7872

@@ -81,19 +75,10 @@ public static int getAvailablePort(int port) {
8175
return getAvailablePort();
8276
}
8377
for (int i = port; i < MAX_PORT; i++) {
84-
ServerSocket ss = null;
85-
try {
86-
ss = new ServerSocket(i);
78+
try (ServerSocket ss = new ServerSocket(i)) {
8779
return i;
8880
} catch (IOException e) {
8981
// continue
90-
} finally {
91-
if (ss != null) {
92-
try {
93-
ss.close();
94-
} catch (IOException e) {
95-
}
96-
}
9782
}
9883
}
9984
return port;
@@ -134,7 +119,7 @@ public static InetSocketAddress getLocalSocketAddress(String host, int port) {
134119
new InetSocketAddress(port) : new InetSocketAddress(host, port);
135120
}
136121

137-
static boolean isValidAddress(InetAddress address) {
122+
static boolean isValidV4Address(InetAddress address) {
138123
if (address == null || address.isLoopbackAddress()) {
139124
return false;
140125
}
@@ -233,21 +218,31 @@ public static InetAddress getLocalAddress() {
233218
return localAddress;
234219
}
235220

221+
private static Optional<InetAddress> toValidAddress(InetAddress address) {
222+
if (address instanceof Inet6Address) {
223+
Inet6Address v6Address = (Inet6Address) address;
224+
if (isValidV6Address(v6Address)) {
225+
return Optional.ofNullable(normalizeV6Address(v6Address));
226+
}
227+
}
228+
if (isValidV4Address(address)) {
229+
return Optional.of(address);
230+
}
231+
return Optional.empty();
232+
}
233+
236234
private static InetAddress getLocalAddress0() {
237235
InetAddress localAddress = null;
238236
try {
239237
localAddress = InetAddress.getLocalHost();
240-
if (localAddress instanceof Inet6Address) {
241-
Inet6Address address = (Inet6Address) localAddress;
242-
if (isValidV6Address(address)) {
243-
return normalizeV6Address(address);
244-
}
245-
} else if (isValidAddress(localAddress)) {
246-
return localAddress;
238+
Optional<InetAddress> addressOp = toValidAddress(localAddress);
239+
if (addressOp.isPresent()) {
240+
return addressOp.get();
247241
}
248242
} catch (Throwable e) {
249243
logger.warn(e);
250244
}
245+
251246
try {
252247
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
253248
if (null == interfaces) {
@@ -259,14 +254,9 @@ private static InetAddress getLocalAddress0() {
259254
Enumeration<InetAddress> addresses = network.getInetAddresses();
260255
while (addresses.hasMoreElements()) {
261256
try {
262-
InetAddress address = addresses.nextElement();
263-
if (address instanceof Inet6Address) {
264-
Inet6Address v6Address = (Inet6Address) address;
265-
if (isValidV6Address(v6Address)) {
266-
return normalizeV6Address(v6Address);
267-
}
268-
} else if (isValidAddress(address)) {
269-
return address;
257+
Optional<InetAddress> addressOp = toValidAddress(addresses.nextElement());
258+
if (addressOp.isPresent()) {
259+
return addressOp.get();
270260
}
271261
} catch (Throwable e) {
272262
logger.warn(e);

dubbo-common/src/test/java/org/apache/dubbo/common/utils/NetUtilsTest.java

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -104,22 +104,22 @@ public void testGetLocalSocketAddress() throws Exception {
104104

105105
@Test
106106
public void testIsValidAddress() throws Exception {
107-
assertFalse(NetUtils.isValidAddress((InetAddress) null));
107+
assertFalse(NetUtils.isValidV4Address((InetAddress) null));
108108
InetAddress address = mock(InetAddress.class);
109109
when(address.isLoopbackAddress()).thenReturn(true);
110-
assertFalse(NetUtils.isValidAddress(address));
110+
assertFalse(NetUtils.isValidV4Address(address));
111111
address = mock(InetAddress.class);
112112
when(address.getHostAddress()).thenReturn("localhost");
113-
assertFalse(NetUtils.isValidAddress(address));
113+
assertFalse(NetUtils.isValidV4Address(address));
114114
address = mock(InetAddress.class);
115115
when(address.getHostAddress()).thenReturn("0.0.0.0");
116-
assertFalse(NetUtils.isValidAddress(address));
116+
assertFalse(NetUtils.isValidV4Address(address));
117117
address = mock(InetAddress.class);
118118
when(address.getHostAddress()).thenReturn("127.0.0.1");
119-
assertFalse(NetUtils.isValidAddress(address));
119+
assertFalse(NetUtils.isValidV4Address(address));
120120
address = mock(InetAddress.class);
121121
when(address.getHostAddress()).thenReturn("1.2.3.4");
122-
assertTrue(NetUtils.isValidAddress(address));
122+
assertTrue(NetUtils.isValidV4Address(address));
123123
}
124124

125125
@Test

dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/support/AbstractMetadataReport.java

Lines changed: 6 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -40,12 +40,12 @@
4040
import java.util.Iterator;
4141
import java.util.Map;
4242
import java.util.Properties;
43-
import java.util.Random;
4443
import java.util.concurrent.ConcurrentHashMap;
4544
import java.util.concurrent.ExecutorService;
4645
import java.util.concurrent.Executors;
4746
import java.util.concurrent.ScheduledExecutorService;
4847
import java.util.concurrent.ScheduledFuture;
48+
import java.util.concurrent.ThreadLocalRandom;
4949
import java.util.concurrent.TimeUnit;
5050
import java.util.concurrent.atomic.AtomicBoolean;
5151
import java.util.concurrent.atomic.AtomicInteger;
@@ -62,13 +62,13 @@ public abstract class AbstractMetadataReport implements MetadataReport {
6262
// Log output
6363
protected final Logger logger = LoggerFactory.getLogger(getClass());
6464

65-
// Local disk cache, where the special key value.registies records the list of registry centers, and the others are the list of notified service providers
65+
// Local disk cache, where the special key value.registries records the list of registry centers, and the others are the list of notified service providers
6666
final Properties properties = new Properties();
6767
private final ExecutorService reportCacheExecutor = Executors.newFixedThreadPool(1, new NamedThreadFactory("DubboSaveMetadataReport", true));
68-
final Map<MetadataIdentifier, Object> allMetadataReports = new ConcurrentHashMap<MetadataIdentifier, Object>(4);
68+
final Map<MetadataIdentifier, Object> allMetadataReports = new ConcurrentHashMap<>(4);
6969

7070
private final AtomicLong lastCacheChanged = new AtomicLong();
71-
final Map<MetadataIdentifier, Object> failedReports = new ConcurrentHashMap<MetadataIdentifier, Object>(4);
71+
final Map<MetadataIdentifier, Object> failedReports = new ConcurrentHashMap<>(4);
7272
private URL reportURL;
7373
boolean syncReport;
7474
// Local disk cache file
@@ -101,12 +101,7 @@ public AbstractMetadataReport(URL reportServerURL) {
101101
// cycle report the data switch
102102
if (reportServerURL.getParameter(Constants.CYCLE_REPORT_KEY, Constants.DEFAULT_METADATA_REPORT_CYCLE_REPORT)) {
103103
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("DubboMetadataReportTimer", true));
104-
scheduler.scheduleAtFixedRate(new Runnable() {
105-
@Override
106-
public void run() {
107-
publishAll();
108-
}
109-
}, calculateStartTime(), ONE_DAY_IN_MIll, TimeUnit.MILLISECONDS);
104+
scheduler.scheduleAtFixedRate(this::publishAll, calculateStartTime(), ONE_DAY_IN_MIll, TimeUnit.MILLISECONDS);
110105
}
111106
}
112107

@@ -335,8 +330,7 @@ long calculateStartTime() {
335330
calendar.set(Calendar.SECOND, 0);
336331
calendar.set(Calendar.MILLISECOND, 0);
337332
long subtract = calendar.getTimeInMillis() + ONE_DAY_IN_MIll - nowMill;
338-
Random r = new Random();
339-
return subtract + (FOUR_HOURS_IN_MIll / 2) + r.nextInt(FOUR_HOURS_IN_MIll);
333+
return subtract + (FOUR_HOURS_IN_MIll / 2) + ThreadLocalRandom.current().nextInt(FOUR_HOURS_IN_MIll);
340334
}
341335

342336
class MetadataReportRetry {

dubbo-registry/dubbo-registry-redis/src/main/java/org/apache/dubbo/registry/redis/RedisRegistry.java

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -43,13 +43,13 @@
4343
import java.util.HashSet;
4444
import java.util.List;
4545
import java.util.Map;
46-
import java.util.Random;
4746
import java.util.Set;
4847
import java.util.concurrent.ConcurrentHashMap;
4948
import java.util.concurrent.ConcurrentMap;
5049
import java.util.concurrent.Executors;
5150
import java.util.concurrent.ScheduledExecutorService;
5251
import java.util.concurrent.ScheduledFuture;
52+
import java.util.concurrent.ThreadLocalRandom;
5353
import java.util.concurrent.TimeUnit;
5454
import java.util.concurrent.atomic.AtomicInteger;
5555

@@ -72,7 +72,7 @@ public class RedisRegistry extends FailbackRegistry {
7272

7373
private final Map<String, JedisPool> jedisPools = new ConcurrentHashMap<>();
7474

75-
private final ConcurrentMap<String, Notifier> notifiers = new ConcurrentHashMap<String, Notifier>();
75+
private final ConcurrentMap<String, Notifier> notifiers = new ConcurrentHashMap<>();
7676

7777
private final int reconnectPeriod;
7878

@@ -122,7 +122,7 @@ public RedisRegistry(URL url) {
122122
}
123123
replicate = "replicate".equals(cluster);
124124

125-
List<String> addresses = new ArrayList<String>();
125+
List<String> addresses = new ArrayList<>();
126126
addresses.add(url.getAddress());
127127
String[] backups = url.getParameter(Constants.BACKUP_KEY, new String[0]);
128128
if (ArrayUtils.isNotEmpty(backups)) {
@@ -518,7 +518,6 @@ private class Notifier extends Thread {
518518
private final String service;
519519
private final AtomicInteger connectSkip = new AtomicInteger();
520520
private final AtomicInteger connectSkipped = new AtomicInteger();
521-
private final Random random = new Random();
522521
private volatile Jedis jedis;
523522
private volatile boolean first = true;
524523
private volatile boolean running = true;
@@ -540,7 +539,7 @@ private boolean isSkip() {
540539
int skip = connectSkip.get(); // Growth of skipping times
541540
if (skip >= 10) { // If the number of skipping times increases by more than 10, take the random number
542541
if (connectRandom == 0) {
543-
connectRandom = random.nextInt(10);
542+
connectRandom = ThreadLocalRandom.current().nextInt(10);
544543
}
545544
skip = 10 + connectRandom;
546545
}

0 commit comments

Comments
 (0)