-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWorker.scala
42 lines (32 loc) · 901 Bytes
/
Worker.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package TwoPhaseCommit
import org.apache.zookeeper._
import java.util.concurrent.TimeUnit
import scala.util.Random
case class Worker(id:Integer, hostPort:String, root:String) extends Watcher {
val zk = new ZooKeeper(hostPort, 3000, this)
val workerPath = root + "/worker_" + id.toString
val mutex = new Object()
var data: String = ""
override def process(event: WatchedEvent): Unit = {
mutex.synchronized {
val value = if (Random.nextDouble() > 0.5) "commit" else "abort"
while (zk.exists(root, false) == null) {
TimeUnit.SECONDS.sleep(5)
}
println(s"Node $id vote $value")
zk.create(workerPath,
value.getBytes,
ZooDefs.Ids.OPEN_ACL_UNSAFE,
CreateMode.EPHEMERAL
)
TimeUnit.SECONDS.sleep(10)
zk.getData(workerPath, this, null)
zk.delete(workerPath, -1)
zk.close()
}
}
def run(): Unit = {
while (true) {
}
}
}