JavaのDNSキャッシュ

いままでそんなことなかったのだが、本日自作JavaアプリでUnknownHostExceptionがたびたび発生した。たぶんプロバイダ提供のDNSサーバが不調なのかなーという気がするのだが、はっきりしない。ちょっと調べてみたメモ。

OSのDNSキャッシュ

OS(のDNSゾルバ)はDNSキャッシュを持っている
DNSキャッシュはWindowsの場合、以下のコマンドで確認できる

ipconfig /displaydns キャッシュの一覧の表示
ipconfig /flushdns キャッシュのクリア

displaydnsしたときのTime To Liveというのがキャッシュを保持する時間(秒)

JavaDNSキャッシュ

また、JavaでもDNSキャッシュを持っている
キャッシュの保持時間の設定は、以下のセキュリティプロパティーで行う
設定ファイルは以下の場所にある。JREJDKで場所がJAVA_HOMEが違うので注意。


%JAVA_HOME%\lib\security\java.security


抜粋


# The Java-level namelookup cache policy for successful lookups:
#
# any negative value: caching forever
# any positive value: the number of seconds to cache an address for
# zero: do not cache
#
# default value is forever (FOREVER). For security reasons, this
# caching is made forever when a security manager is set. When a security
# manager is not set, the default behavior is to cache for 30 seconds.
#
# NOTE: setting this to anything other than the default value can have
# serious security implications. Do not set it unless
# you are sure you are not exposed to DNS spoofing attack.
#
#networkaddress.cache.ttl=-1

# The Java-level namelookup cache policy for failed lookups:
#
# any negative value: cache forever
# any positive value: the number of seconds to cache negative lookup results
# zero: do not cache
#
# In some Microsoft Windows networking environments that employ
# the WINS name service in addition to DNS, name service lookups
# that fail may take a noticeably long time to return (approx. 5 seconds).
# For this reason the default caching policy is to maintain these
# results for 10 seconds.
#
#
networkaddress.cache.negative.ttl=10

networkaddress.cache.ttlがキャッシュを保持する時間(秒)
デフォルトではコメントアウトされており、デフォルトの動作は無限(セキュリティーマネージャをセットした場合)、または30秒(セキュリティーマネージャをセットしてない場合)とのこと

networkaddress.cache.negative.ttlが名前解決に失敗した場合に、失敗情報を保持する時間(秒)
あんまり連続してOSに名前解決しにいっても、失敗しまくるだけなので、少し間をあけるのがよいらしい
デフォルトは10秒


また、java.securityファイルで設定する場合は、上記を使うが、コマンド行オプションで値を渡す場合は、代わりに sun.net.inetaddr.ttl sun.net.inetaddr.negative.ttl を使うらしい(ためしてない)。


参考
ネットワークのプロパティー(UTF-8)
http://java.sun.com/javase/ja/6/docs/ja/technotes/guides/net/properties.html
URLConnectionのDNSキャッシュ
http://d.hatena.ne.jp/trash717/20070627/p1


とりあえず、自分の場合は、朝PCをつけてアプリ起動した後、夜消すまで、キャッシュしてるのが都合がいいので、上記のnetworkaddress.cache.ttlに-1を指定して無限キャッシュすることにした。