Multithreading scala并行集合:为工作线程提供线程局部变量的惯用方法
下面的进度函数是我的工作函数。我需要让它访问一些创建/获取成本高昂的类。库中是否有用于线程局部变量的标准机制?还是我必须自己编写一个对象池管理器Multithreading scala并行集合:为工作线程提供线程局部变量的惯用方法,multithreading,scala,thread-local,parallel-collections,Multithreading,Scala,Thread Local,Parallel Collections,下面的进度函数是我的工作函数。我需要让它访问一些创建/获取成本高昂的类。库中是否有用于线程局部变量的标准机制?还是我必须自己编写一个对象池管理器 object Start extends App { def progress { val current = counter.getAndIncrement if(current % 100 == 0) { val perc = current.toFloat * 100 / total
object Start extends App {
def progress {
val current = counter.getAndIncrement
if(current % 100 == 0) {
val perc = current.toFloat * 100 / totalPosts
print(f"\r$perc%4.2f%%")
}
}
val lexicon = new Global()
def processTopic(forumId: Int, topicId: Int) {
val(topic, posts) = ProcessingQueries.getTopicAndPosts(forumId,topicId)
progress
}
val (fid, tl) = ProcessingQueries.getAllTopics("hon")
val totalPosts = tl.size
val counter = new AtomicInteger(0)
val par = tl.par
par.foreach { topic_id =>
processTopic(fid,topic_id)
}
}
替换了先前的答案。这把把戏做得又好又整洁
object MyAnnotator extends ThreadLocal[StanfordCoreNLP] {
val props = new Properties()
props.put("annotators", "tokenize,ssplit,pos,lemma,parse")
props.put("ssplit.newlineIsSentenceBreak", "two")
props.put("parse.maxlen", "40")
override def initialValue = new StanfordCoreNLP(props)
}
通过覆盖ThreadLocal上的initialValue,可以更整洁地完成此操作。这样,您就不需要执行get/set逻辑。