Calling Custom Clojure Functions from Java

Calling Clojure APIs from Java is discussed in my first tutorial. This tutorial explores calling your own Clojure functions from Java. A common use case for this is when you write a JavaFX UI and want to have the controller code written in Clojure.

Our first example explains how to call a simple Clojure function that takes no arguments and returns no values. (Technically, all Clojure fuctions return values, but that doesn’t mean we care about all values Clojure functions return.)

(ns java-clj-interop.core)

(defn hello-world
  "Yeah. You guessed it. This prints 'Hello World!'"
  (println "Hello World!"))

Continue reading “Calling Custom Clojure Functions from Java”

Calling Clojure Functions from Java

Mixing Clojure functions and Java methods usually happens when pure Clojure applications need to interact with Java libraries. However, sometimes you have Clojure functions receiving events from a Java program. This is often the case when you have a Java program with a JavaFX, Java Swing, or Java AWT GUI, but you want all the controller logic written in Clojure. It certainly is  possible to write Clojure code calling Java libraries to create a decent UI, but doing so would be clunky at best.

It is also possible that you have a legacy Java application that you want to write Clojure plugins for. This is easily accomplished by calling Clojure functions from any appropriate place in the Java code. You can call directly into uncompiled Clojure scripts. To call Clojure scripts, you just need to know the right classes for loading your code.

Continue reading “Calling Clojure Functions from Java”

Clojure Threading with Future

Clojure concurrency is easy with future. Speed improvements in Clojure on modern computers come from multi-threading. Besides tapping into Java’s thread system, Clojure has it’s own easy-to-use thread system, and Clojure threads don’t get easier to use than with future.

In its simplest form, use def with a future and then then dereference the value obtained. When the future is no longer needed, make a call to shutdown-agents for the program to exit properly.

For example:

(ns clj-future.core)

(defn do-something
  "Doing something noticable."
  "Life. Don't tell me about life.")

(defn -main
  "I don't do a whole lot."
  ;; create a var named some-string
  ;; and make it reference our future
  (def some-string (future 
  ;; dereference the future value
  ;; and print it
  (println @some-string)
  ;; remember to shut down agents
  ;; so the program exits normally

Continue reading “Clojure Threading with Future”