Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use locking macro or monitor-enter and monitor-exit in Java from Clojure

I have a piece of Clojure code need to optimize for better performance. My thought is to rewrite it using java. There is one object I used locking macro in the code that I need to rewrite and this object may also be locked else where which is written in Clojure code.

I don't want to define new ReentrantLock object because this application is memory sensitive.

My question is what in java is equal to locking macro, or monitor-enter and monitor-exit under the hood from Clojure?

like image 778
Shisoft Avatar asked Apr 07 '16 19:04

Shisoft


1 Answers

For the following Clojure code:

(def someObject ...)

(locking someObject
  ;; critical section)

where locking is a macro translating to:

(let [lock someObject]
  (try
    (monitor-enter lock)
    ;; critical section
    (finally
      (monitor-exit lock))))

Java's equivalent is synchronized keyword:

Object someObject = ...;
synchronized (someObject) {
    // critical section
}

Or another form synchronizing on this reference:

public synchronized void someMethod() {
    // critical section
}

which is equivalent to:

public void someMethod() {
    synchronized (this) {
        // critical section
    }
}

You can also synchronize on class object:

public class SomeClass {
    public static synchronized void someMethod() {
        // critical section
    }
}

which is equivalent to:

public class SomeClass {
    public static void someMethod() {
        synchronized (SomeClass.class) {
            // critical section
        }
    }
}

Java's synchronized keyword is compiled into JVM's monitorenter and monitorexit bytecode instructions. Clojure's monitor-enter and monitor-exit special forms use the same bytecode instructions.

like image 181
Piotrek Bzdyl Avatar answered Oct 15 '22 20:10

Piotrek Bzdyl