2015年11月6日 星期五

[ 常見問題 ] Is there a Groovy way of making a method synchronized?

Source From Here 
Question 
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. For example: 
  1. synchronized static def  Map getMap(def fileName) { }  
How-To 
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
  1. import groovy.transform.Synchronized  
  2.   
  3. class YourClass {  
  4.     @Synchronized  
  5.     static Map getMap(def fileName) {  
  6.         ...  
  7.     }  
  8. }  
Supplement 
[ GroovyGN ] Synchronized Annotation for Synchronizing Methods

沒有留言:

張貼留言

[JS 文章收集] 用 Node.js 學 JavaScript 語言(1)簡介與安裝

Source From  Here   簡介   Node.js  是 Ryan Dahl 基於 Google 的 V8 引擎於 2009 年釋出的一個 JavaScript 開發平台,主要聚焦於 Web 程式的開發,通常用被來寫網站。但是,要開發網站就勢必要把「 HTML,...