Grails Service 并发处理(笔记)
grails Service是单例的,所以容易出并发问题,当出现并发时怎么处理?在调用的方法名称上面增加@Synchronized。 这个是groovy多线程的处理,非常简单就能解决异步问题。 groovy的异步用法有很多种,以下是groovy帮助文档里面的原文。 ------------------------------------------------------------- Method annotation to make a method call synchronized for concurrency handling with some useful baked-in conventions. class SynchronizedExample { private final myLock = new Object() @Synchronized static void greet() { println "world" } @Synchronized int answerToEverything() { return 42 } @Synchronized("myLock") void foo() { println "bar" } } ? which becomes: ? class SynchronizedExample { private static final $LOCK = new Object[0] private final $lock = new Object[0] private final myLock = new Object() static void greet() { synchronized($LOCK) { println "world" } } int answerToEverything() { synchronized($lock) { return 42 } } void foo() { synchronized(myLock) { println "bar" } } }? Credits: this annotation is inspired by the Project Lombok annotation of the same name. The functionality has been kept similar to ease the learning curve when swapping between these two tools. Details: If $lock and/or $LOCK are auto-generated,the fields are initialized with an empty Object[] array,and not just a new Object() as many snippets using this pattern tend to use. This is because a new Object is NOT serializable,but a 0-size array is. Therefore,using @Synchronized will not prevent your object from being serialized. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |