zcaudate
zcaudate

Reputation: 14258

how to translate a java runnable example to 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() {... }}

Upvotes: 4

Views: 1204

Answers (3)

overthink
overthink

Reputation: 24463

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))))))

Upvotes: 9

naga
naga

Reputation: 86

In the original message I understood that the question was that how to implement an interface (java.lang.Runnable in this case). That can be done with reify.

(reify java.lang.Runnable
  (run [this]
       (try
         (Thread/sleep RECORD_TIME))
         (catch InterruptedException e
           (.printStackTrace e))))))

Of course if you just wanted to execute a set of expressions in a separate thread you'd want to use eg. (future) as robermann mentioned above.

Upvotes: 3

robermann
robermann

Reputation: 1722

Probably via future:

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

Then dereference it:

@recorded 

Upvotes: 4

Related Questions