Welcome! Please see the About page for a little more info on how this works.

+17 votes
in Clojure by
retagged by

From JDK19+ onwards, the following won't work without adding a type hint:

(def x 10)
(Thread/sleep x)

The tricky bit is that in earlier JDKs the above would work without adding type hints, but as soon as you upgrade your programs start to fail.

It would be nice to have a built-in sleep function that accepted a number so we don't forget to add type hints and it would work consistently across JDKs.


(ns clojure.java.misc)
(defn sleep [x]
  (if (number? x)
    (Thread/sleep (long x))

A better name for clojure.java.misc is welcome. Maybe just clojure.java or put this function into clojure.core?

Weirdly enough, now I can't reproduce it on 1.11.1 with JDK 20, at all - in REPL, by executing a script, by executing a `-main` function, with extra wrappers around both the var and the function.
(~/clojure)-(!2001)-> clj
    Clojure 1.12.0-alpha4
    user=> (System/getProperty "java.version")
    user=> (set! *warn-on-reflection* true)
    user=> (def x 1000)
    user=> (Thread/sleep x)
     Reflection warning, NO_SOURCE_PATH:1:1 - call to static method sleep on java.lang.Thread can't be resolved (argument types: unknown).

1 Answer

+1 vote
There is a portable analog to Thread/sleep in core.async.
Seems overkill to pull in the whole of core.async if all you need is sleep, though.