English 中文(简体)
如何在scala做一个安全代码线?
原标题:How to make a code thread safe in scala?
  • 时间:2012-05-23 10:37:55
  •  标签:
  • scala

我有一个在scala的代码, 出于各种原因, 有几个线的代码线 无法同时通过更多的线索访问。

我知道我可以使用演员模型, 但我发现它有点太过分了 几行代码。

我会使用某种锁, 但我无法找到任何具体的例子,无论是谷歌还是斯塔克流。

最佳回答

我认为最简单的解决方案是使用 同步 用于关键部分(与爪哇一样)。

someObj.synchronized {
    // tread-safe part
}

它很容易使用,但会阻碍和容易造成僵局,因此我鼓励你查看Akka ,可能更复杂,但更好/不阻碍的解决办法。

问题回答

你可以使用任何爪哇货币结构,例如>Semaphores ,但是我建议反对它,因为血压容易出错,而且难以使用。在这里,演员确实是最好的方法。

创建行为体并不一定是困难的。在 scala- lang. org 上对行为体有一个简短但有用的指导: < a href="http://www.scala-lang.org/node/242" rel=“no follown noreferrer" >http://www.scala-lang.org/node/242

如果确实非常简单,你可以同时使用:http://www.ibm.com/developerworks/java/library/j-scala02049/index.html

或者您可以在jdk中的同时包中使用某些类:http://docs.oracle.com/javase/6/docs/api/java/util/control/package-summary.html

如果您想要使用演员, 您应该使用 akka 演员( 他们将来会取代 scala 演员), 请看 : < a href=" http://doc.akka. io/docs/ akka/2. 0.1/" rel= “ nofollow” > http://doc.akka. io/docs/akka/2. 0.1/ < /a > 。 它们也支持诸如 密克罗尼西亚( 邦机) 和 STM ( 软软件交易记忆) 等东西 。

一般来说,试图使用纯粹的功能或方法,其固定的数据结构应有助于线条安全。





相关问题
How to flatten a List of different types in Scala?

I have 4 elements:List[List[Object]] (Objects are different in each element) that I want to zip so that I can have a List[List[obj1],List[obj2],List[obj3],List[obj4]] I tried to zip them and I ...

To use or not to use Scala for new Java projects? [closed]

I m impressed with Twitter and investigating to use Scala for a new large scale web project with Hibernate and Wicket. What do you think about Scala, and should I use it instead of Java? EDIT: And, ...

Why does Scala create a ~/tmp directory when I run a script?

When I execute a Scala script from the command line, a directory named "tmp" is created in my home directory. It is always empty, so I simply deleted it without any apparent problem. Of course, when I ...

Include jar file in Scala interpreter

Is it possible to include a jar file run running the Scala interpreter? My code is working when I compile from scalac: scalac script.scala -classpath *.jar But I would like to be able to include a ...

Scala and tail recursion

There are various answers on Stack Overflow which explain the conditions under which tail recursion is possible in Scala. I understand the limitations and how and where I can take advantage of tail ...