Hi,
I'm trying to do the following in Clojure, and I'm wondering if
there's a better way...
This creates a little window, with a button that prints "my env"
whenever it is clicked.

(ns main
  (:import
    (javax.swing JFrame JButton)
    (java.awt.event ActionListener)))

(def env)
(defn main [args]
  (binding [env "my env"]
    (println env)                                    ;<---- prints
fine. Because we're still in correct thread.
    (let [frame (new JFrame)
          button (new JButton)]
      (. button addActionListener (proxy [ActionListener] []
                                    (actionPerformed [evt] (println
env))))   ;<--- IllegalStateException: env is unbound
      (doto frame
        (add button)
        (setVisible true))))

This can be resolved by doing the following:

(def env)
(defn main [args]
  (binding [env "my env"]
    (println env)                                    ;<---- prints
fine. Because we're still in correct thread.
    (let [frame (new JFrame)
          button (new JButton)
          env env]                      ;<----- Must include this line
      (. button addActionListener (proxy [ActionListener] []
                                    (actionPerformed [evt] (println
env))))   ;<--- Works properly now.
      (doto frame
        (add button)
        (setVisible true))))

IllegalStateException is being thrown because the ActionListener code
is actually called from the Swing event loop which runs in a different
thread, where env is not bound. This is easily fixed by introducing a
variable inside a let, that is captured by the ActionListener
closure).

So this requires that the coder be aware of the circumstances in which
his closures are called (ie. in the same thread, in a different
thread, etc...). Is this a detail that the coder should be responsible
for?

Is it possible for closures to automatically capture the bindings for
the thread in which the closure was declared? Or does this have some
terrible consequences that I'm not yet seeing?

Anyway, it's something to think about.
  Thanks for your help.
     -Patrick
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Clojure" group.
To post to this group, send email to clojure@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/clojure?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to