Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a Groovy way of making a method synchronized?

Tags:

groovy

I'm working with Groovy 1.7.2. There are methods which needs to be Synchronized , is there any groovier way of doing this or I have to follow same Java way of putting synchronized keyword before method.

e.g : synchronized static def  Map getMap(def fileName) { }
like image 929
anish Avatar asked Oct 22 '11 05:10

anish


2 Answers

If you can upgrade to Groovy 1.7.3 you can use the Synchronized AST transformation instead. You can use the annotation on instance and static methods. The annotation will create a lock variable in your class (or you can use an existing variable) and the code is synchronized on that lock variable.

The usage of a synchronized block should be preferred over adding the keyword to the method. If you use the synchronized keyword on the method you synchronize on this which means that all other threads that want to access any of the methods in your class have to wait until the lock is free again.

import groovy.transform.Synchronized

class YourClass {
    @Synchronized
    static Map getMap(def fileName) {
        ...
    }
}
like image 169
Benjamin Muschko Avatar answered Oct 17 '22 23:10

Benjamin Muschko


Since Groovy 1.7.3 we have a new AST transformation: @Synchronized

like image 35
Arturo Herrero Avatar answered Oct 18 '22 00:10

Arturo Herrero