Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Thread

 
cyril vidal
Ranch Hand
Posts: 247
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear all,
Question n�19 from Dan's (third part) devoted to threads:

Answer for possible outputs:

Prints: [T1,A][T2,B].
c. Prints: [T1,B][T2,B].
d. Prints: [T2,B][T1,A].
e. Prints: [T2,A][T1,A].
Since method m1 is not synchronized

As far as I understand, here the modifier static for object b in class A is very important: it means that the same object B is shared between the two threads a and b.
But if we delete this keyword in the code, now each thread has its own object b, and there is no more reason that we obtain a different result than
[T1,A][T2,B]

I've tested it, and on my computer, that's indeed the case.
But may we generalize?
Thanks in advance for your answer,
Cyril.
 
Miki Muzsi
Ranch Hand
Posts: 120
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you remove the static keyword, indeed there are two diffeerent instances of B created. This garantees that you can not get output like:
[T1,B]
or [T2,A]
However you will not have garantee that the output is always: [T1,A][T2,B]. It can be [T2,B] [T1,A] as well, since no control (garantee) how thread scheduler will do things.
Miki
 
cyril vidal
Ranch Hand
Posts: 247
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's right!
Thanks Miki for your answer.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic