[#179] Break hostname util into smaller components

This commit is contained in:
Peter Taoussanis 2016-07-07 12:57:37 +07:00
parent 6d3fc57dbb
commit f2f42ca39f
1 changed files with 15 additions and 14 deletions

View File

@ -685,21 +685,22 @@
`(binding [*out* default-out, *err* default-err] ~@body)) `(binding [*out* default-out, *err* default-err] ~@body))
#+clj #+clj
(def get-hostname (do ; Hostname stuff
(enc/memoize* (enc/ms :mins 1) (defn get-?hostname "Returns live local hostname, or nil." []
(fn [] (try (.getHostName (java.net.InetAddress/getLocalHost))
;; Android doesn't like this on the main thread. Would use a `future` but (catch java.net.UnknownHostException _ nil)))
;; that starts the Clojure agent threadpool which can slow application
;; shutdown w/o a `(shutdown-agents)` call
(let [executor (java.util.concurrent.Executors/newSingleThreadExecutor)
^java.util.concurrent.Callable f
(fn []
(try
(.. java.net.InetAddress getLocalHost getHostName)
(catch java.net.UnknownHostException _ "UnknownHost")
(finally (.shutdown executor))))]
(deref (.submit executor f) 5000 "UnknownHost"))))) (defn get-?hostname_ "Returns a new `(get-?hostname)` promise." []
;; Android doesn't like hostname calls on the main thread. Using `future`
;; would start the Clojure agent threadpool though, which can slow down
;; application shutdown w/o a `(shutdown-agents)` call.
(let [p (promise)]
(.start (Thread. (fn [] (deliver p (get-?hostname)))))
p))
(def get-hostname "Returns cached hostname string."
(enc/memoize* (enc/ms :mins 1)
(fn [] (or (deref (get-?hostname_) 5000 nil) "UnknownHost")))))
(comment (get-hostname)) (comment (get-hostname))