Skip to content

Commit

Permalink
Merge pull request #154 from virtualeconomy/bugfix/dynamic_variable
Browse files Browse the repository at this point in the history
fix issue of muti-thread sync
  • Loading branch information
ncying authored Oct 22, 2019
2 parents 75fe43e + 7b3b947 commit 0b5ba8d
Showing 1 changed file with 7 additions and 10 deletions.
17 changes: 7 additions & 10 deletions src/main/scala/vsys/utils/Synchronized.scala
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import java.util.concurrent.locks.ReentrantReadWriteLock

import vsys.utils.Synchronized.{ReadLock, _}

import scala.util.DynamicVariable
// http://vlkan.com/blog/post/2015/09/09/enforce-locking/

object Synchronized {
Expand Down Expand Up @@ -49,26 +48,24 @@ trait Synchronized {

private lazy val instanceReadWriteLock: WriteLock = new WriteLock(synchronizationToken)

protected case class Synchronized[T](private val initialValue: T) {

private val value = new DynamicVariable(initialValue)
protected case class Synchronized[T](private var value: T) {

def apply()(implicit readLock: ReadLock): T = {
value.value
value
}

def mutate[R](f: T => R)(implicit readWriteLock: WriteLock): R = {
f(value.value)
f(value)
}

def transform(newVal: T => T)(implicit readWriteLock: WriteLock): T = {
value.value = newVal(value.value)
value.value
value = newVal(value)
value
}

def set(newVal: => T)(implicit readWriteLock: WriteLock): T = {
val oldVal = value.value
value.value = newVal
val oldVal = value
value = newVal
oldVal
}
}
Expand Down

0 comments on commit 0b5ba8d

Please sign in to comment.