2

What is the difference between using synchronized println and just println in Groovy for a threaded script?

synchronized out(message) {
println(message)
}

def thread1 = Thread.start {
out "TEST"
}
def thread2 = Thread.start {
out "TEST"
}
def thread3 = Thread.start {
out "TEST"
}
Android Developer
  • 987
  • 1
  • 8
  • 22
mze3e
  • 438
  • 2
  • 5
  • 14

1 Answers1

0

There is no difference, until you call single println command. One println is internally synchronized. But if your out contains multiple print statements, there may be such situation, illistrated below

out(int threadId){ 
   println("line 1 T$threadId")
   println("line 2 T$threadId")
}

Execution may flow like
//output by 2 threads
line 1 T1 // thread 1 entered out
// thread 1 was interrupted
// thread 2 entered out
line 1 T2
line 2 T2 //end of thread 2 out
// Thread 1 resumed
line 2 T1 

As we see, output is messed. synchronized fixes that problem

See also SO answer about println inner synchronisation https://stackoverflow.com/a/9459886/1601606

Community
  • 1
  • 1
Seagull
  • 13,484
  • 2
  • 33
  • 45
  • I doubt `println` is atomic. `+=` isn't atomic. Did you mean `synchronized`? – tim_yates Nov 22 '13 at 06:56
  • @tim Yes, I meant atomic, as monolite construction, that will be executed as one. Thanks for comment! I know about 'atomic' term, but little confused with it usage here. I corrected the answer. – Seagull Nov 22 '13 at 07:31