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

+17 votes
in Clojure by
edited by

From JDK19+ onwards, the following becomes reflective without adding a type hint:

(def x 10)
(Thread/sleep x)

The tricky bit is that in earlier JDKs the above did not reflect, but when you upgrade your JDK, the reflection starts.

If using native-image, your program may start to fail due to missing reflection configuration.

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.

E.g.:

(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?

by
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.
by
(~/clojure)-(!2001)-> clj
    Clojure 1.12.0-alpha4
    user=> (System/getProperty "java.version")
    "20.0.1"
    user=> (set! *warn-on-reflection* true)
    true
    user=> (def x 1000)
    #'user/x
    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).
    nil
    user=>

1 Answer

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