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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With