GPars:等待演员完成

时间:2013-02-21 22:51:11

标签: groovy gpars

我认为我从文档中弄错了。

我有两个演员,XMLActor和HttpActor。 XMLActor读取xmlFiles,然后向HTTPActor发送消息进行处理。 XMLActor将比HttpActor更快地完成。

我的主要类调用两个actor的连接。我期待主线程只会在两个演员完成后终止。但是,实际发生的是,只要XMLActor处理了所有消息,系统就会终止,并且HttpActor不处理大量消息。

我可以使用一些闩锁甚至是AtomicInteger等待消耗所有消息,但我想知道是否有更优雅的方式。

final HttpActor httpActor = new HttpActor().start()
final XMLActor xmlActor = new XMLActor(httpActor:httpActor).start()
Actors.actor {
        file.eachLine { line ->
            def chunks = line.split(",")
            def id = chunks[0].replaceAll("\\\"","").trim()
            def name = chunks[1].replaceAll("\\\"","").trim()
            xmlActor << new FileToRead(basePath:args[1],id:id,name:name, fileCounter:counter)
        }
    }
[httpActor, xmlActor]*.join()

//inside xmlActor
countries.each {  country ->
            httpActor << new AlbumPriceMessage(id:message.id, country:country)
        }

1 个答案:

答案 0 :(得分:3)

join()方法肯定会等待两个actor完成。我不知道你是怎么阻止这两个演员的,所以无法对此发表评论。你发送了这样的毒药信息吗?或者在演员身上调用stop()?

例如,您的案例的以下模拟正确停止:

import groovyx.gpars.actor.*;

def httpActor = Actors.staticMessageHandler {
    println "Http actor processing " + it
}

def xmlActor = Actors.staticMessageHandler {
    println "XML Actor processing " + it
    httpActor << it
}

xmlActor.metaClass.afterStop = {
    httpActor.stop()
}

100.times {
    xmlActor << "File$it"
}
xmlActor.stop()

[xmlActor, httpActor]*.join()
println "done"