The DNS Cache of the JVM is maintained in the private field of the InetAddress class and is set by reflection. For specific implementation, see
Pay attention to the thread safety of setting the DNS Cache of JVM The DNS Cache of the JVM is obviously shared globally, so the setting is guaranteed to be thread-safe and there is no concurrency problem.
Taking JDK 8 as an example, by looking at the implementation of the InetAddress class, it can be determined that thread safety is ensured by the synchronized block with the addressCache field as the lock.
The key code is as follows:
/*
* Cache the given hostname and addresses.
*/
private static void cacheAddresses(String hostname,
InetAddress[] addresses,
boolean success) {
hostname = hostname.toLowerCase();
synchronized (addressCache) {
cacheInitIfNeeded();
if (success) {
addressCache.put(hostname, addresses);
} else {
negativeCache.put(hostname, addresses);
}
}
}
In the InetAddressCacheUtilForOld
class, the read and write to the DNS Cache also consistently adds a synchronized block with addressCache
field as the lock to ensure thread safety.
The implementation of this library uses the non-public API of the JDK
, and different JDK
implementations will be different, that is, compatible logic is required, and different versions of JDK
are tested to ensure functionality.
The LTS JDK
versions(8/11/17) and recent versions are tested , other JDK
versions should work properly.
- The source code of the class
InetAddress
:JDK 6
InetAddress
JDK 7
InetAddress
JDK 8
InetAddress
JDK 9
InetAddress
JDK 11
InetAddress
JVM Networking Properties
-java docs
- Domain Name System - wikipedia
Java DNS
FAQ- The
javahost
project of@tanhaichao
(Thanks for your work!)- the documentation of the project.
- The solution of how to set up Java DNS Cache comes from this project. When I first encountered the host binding problem in the continuous integration project, I also used the project to solve it 👍