scala_object

scala object 线程安全

这篇Scala thread-safety question回复

提到如下代码:

1
2
3
object Class {
val students = new mutable.List()
}

“object” initialization is thread safe. “mutable.List” is not thread
safe and needs to be synchronized.

然后我们自己定义一个object用于测试:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
  object  TestObject {

val prop1 = "sad"

lazy val prop2 = "testLazy"
println("propinitialize")
private val props: java.util.Map[String, Object] = new java.util.HashMap[String, Object]

props.put("prop2",prop2)//访问prop2的时候会给prop2赋值

def initialize() = {
println("initialize")
}

def apply() ={

println(props.get("prop2").toString)
println("initializing")
}
}

用以下代码测试:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
object  TestObjectInitializer extends  App {

val exce = Executors.newFixedThreadPool(6)

for (i <- 0.to(100)){
val runner = new Runnable {
def run(): Unit = {

TestObject()
}}
exce.submit(runner)
}

println("initialized")
}

打印如下代码:

1
2
3
4
5
6
7
8
9
10
11
12
propinitialize
initialized
testLazy
testLazy
initializing
testLazy
testLazy
initializing
testLazy
testLazy
initializing
initializing

propinitialize只执行一次。

参考资料:
Scala Singleton Object with Multi-threading
How to make object (a mutable stack) thread-safe

欢迎关注我的公众号:沉迷Spring
显示 Gitment 评论
0%