Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to translate a java runnable example to clojure

Tags:

java

clojure

I'm a little bit confused as to how the Runnable block can be translated from this example:

http://www.codejava.net/coding/capture-and-record-sound-into-wav-file-with-java-sound-api

    Thread stopper = new Thread(new Runnable() {
        public void run() {
            try {
                Thread.sleep(RECORD_TIME);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
            recorder.finish();
        }
    });

The bit of code I am confused with is this:

   Runnable(){... public void run() {... }}
like image 245
zcaudate Avatar asked Dec 06 '22 02:12

zcaudate


2 Answers

Of note, clojure functions implement Runnable.

user=> (ancestors clojure.lang.AFn)
#{clojure.lang.IFn
  java.lang.Object
  java.lang.Runnable
  java.util.concurrent.Callable}

So you could pass a fn directly to Thread's constructor.

(def stopper 
  (Thread.
    (fn []
      (try
        (Thread/sleep RECORD_TIME)
        (catch InterruptedException e
          (.printStackTrace e))))))
like image 151
overthink Avatar answered Dec 11 '22 10:12

overthink


Probably via future:

(def recorder ( /*...*/) )
(def recorded (future (Thread/sleep RECORD_TIME)  (.finish recorder) recorder))

Then dereference it:

@recorded 
like image 20
robermann Avatar answered Dec 11 '22 10:12

robermann