我使用grails 2.3.x和async获得了一些奇怪的行为。我正在用这段代码做一些测试:
def test1() {
def list = new PromiseList()
list << {
Thread.sleep(1000)
println "1"
return "1"
}
list << {
Thread.sleep(2000)
println "2"
return "2"
}
list << {
Thread.sleep(3000)
println "3"
return "3"
}
list.onComplete { List results ->
println 'finished: '+results
}
list.onError { error ->
error.printStackTrace()
}
render 'finish'
}
但在我的日志中我得到了:
1
| Error java.lang.NullPointerException
| Error at org.apache.catalina.connector.Request.notifyAttributeAssigned(Request.java:1565)
| Error at org.apache.catalina.connector.Request.setAttribute(Request.java:1556)
| Error at org.apache.catalina.connector.RequestFacade.setAttribute(RequestFacade.java:543)
| Error at org.apache.catalina.core.ApplicationHttpRequest.setAttribute(ApplicationHttpRequest.java:281)
| Error at org.codehaus.groovy.grails.web.util.WebUtils.storeGrailsWebRequest(WebUtils.java:682)
| Error at org.codehaus.groovy.grails.plugins.web.async.WebRequestPromsiseDecorator$_decorate_closure1.doCall(WebRequestPromiseDecoratorLookupStrategy.groovy:61)
| Error at sun.reflect.GeneratedMethodAccessor283.invoke(Unknown Source)
| Error at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
| Error at java.lang.reflect.Method.invoke(Method.java:606)
| Error at org.springsource.loaded.ri.ReflectiveInterceptor.jlrMethodInvoke(ReflectiveInterceptor.java:1260)
| Error at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:90)
| Error at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:233)
| Error at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1086)
| Error at groovy.lang.ExpandoMetaClass.invokeMethod(ExpandoMetaClass.java:1110)
| Error at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:910)
| Error at groovy.lang.Closure.call(Closure.java:411)
| Error at groovy.lang.Closure.call(Closure.java:405)
| Error at groovyx.gpars.group.PGroup$3.call(PGroup.java:287)
| Error at groovyx.gpars.group.PGroup$4.run(PGroup.java:311)
| Error at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
| Error at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
| Error at java.lang.Thread.run(Thread.java:724)
2
3
实际上执行了task(和onError closure),但是onComplete不是(当然)!!
我在做错了什么?除了Thread.sleep()是从doc:http://grails.org/doc/latest/guide/async.html获取的实际代码
由于某种原因,Thread.sleep()与GPars不兼容吗?
答案 0 :(得分:0)
问题是onComplete
没有阻止。请求/操作在您的任务和list
超出范围之前完成。
在操作返回之前,您需要使用waitAll()
等待所有任务完成。最简单的方法是将onComplete
替换为
def result = list.get ()
println 'finished: ' + result
通过调用list.get()
来实现 waitAll()
。