0

I have the following three variants of Scala code that take as input some method and calls it atomically. The method could have some db/read write operations among other things. I don't know in advance what method it will be except that it terminates in < 100 millis. Pasting Scala code for brevity but imagining a Java version should be straightforward.

val locked = new java.util.concurrent.atomic.AtomicBoolean(false)
def usingAtoimcSleepLock[T](f: => T):T = {
  while (! locked.compareAndSet(false, true)) {Thread.sleep(10)}
  try f
  finally locked.set(false)
} 
def usingAtoimcSpinLock[T](f: => T):T = {
  while (! locked.compareAndSet(false, true)) { /* do nothing */ }
  try f
  finally locked.set(false)
} 
def usingAtoimcTimeoutLock[T](f: => T):T = {
  var ctr = 0
  while (! locked.compareAndSet(false, true)) { 
     if (ctr > 1000) throw new Exception("lock could not be opened")
     ctr = ctr + 1
     // can add Thread.sleep
  }
  try f
  finally locked.set(false)
} 

Which of the above 3 methods is recommended? In particular is usingAtomicSpinLock recommended?

I feel usingAtomicTimeoutLock with a Thread.sleep is the best option. However, I also feel it could waste time due to context switching.

EDIT: I am not asking "what objects should I synchronize?". What I want to know is "how should I synchronize the objects (that I know)"?

Jus12
  • 17,824
  • 28
  • 99
  • 157
  • Possible duplicate of [What object do I synchronize on in Scala?](http://stackoverflow.com/questions/17129963/what-object-do-i-synchronize-on-in-scala) – Kaz Sep 02 '16 at 20:35
  • 1
    Using spinlocks over critical sections that span blocking I/O operations is simply dumb, unless the programming language doesn't provide mutexes or anything of their ilk. – Kaz Sep 02 '16 at 20:39
  • A spinlock is a synchronization primitive. Mutual exclusion is a form of sychronization. As you can see, the referenced question is in fact about locking. – Kaz Sep 02 '16 at 20:42
  • Still I don't see how the linked question answers this. Can you please clarify? – Jus12 Sep 02 '16 at 20:44
  • @Kaz I agree that using mutex better but won't that lead to possibility of deadlock and I need to be extra careful. Here I can simply timeout? – Jus12 Sep 02 '16 at 21:13
  • Spin lock is useful for typically very short operations << 10 microseconds. If this value is only every set once it might make sense but I doubt ti. For operation of above 100 microseconds you should seriously consider using conventional locking/Condition A CAS with a sleep is possibly the worst of both worlds. – Peter Lawrey Sep 03 '16 at 07:42
  • Using your own spin-lcok instead of a `synchronised` lock is probably not worthwhile because [the JVM might automatically use a spin-lock *when that is worthwhile* anyway](https://stackoverflow.com/questions/20689718/what-is-adaptive-spinning-w-r-t-lock-acquisition) – Raedwald Dec 20 '18 at 15:03

0 Answers0