• Post Reply Bookmark Topic Watch Topic
  • New Topic

Syncronizing method

 
Jay Shukla
Ranch Hand
Posts: 214
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm reffereing SCJP K & B book for SCJP and following code is given that:


Above code is given in SCJP K & B book to explain don't rely on the "thread-safe" class.
It says that

"Nothing prevents another thread from doing something else to the list in between
calls those two calls to methods add() and remove()."


Can anyone explain how another thread can do something else as quoted above.

Thanks in Advance.
 
sudipto shekhar
Ranch Hand
Posts: 826
Chrome Eclipse IDE Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As far as I think what it means to say is that any other thread can definitely modify the list.
As in say some other thread calls the remove method on the list while a thread is adding to the list.
Think your code runs till this:


And then t1.start() is called and t1 is in runnable state.
But t1 does not run and then t2.start() is called and is scheduled by the scheduler to running state.
It's run() method is called and the element is removed from the List.

So we see that any other thread may change the List between the calls to the method add and removeFirst().

Hope this helps.
 
Jay Shukla
Ranch Hand
Posts: 214
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Sudipto for good explanation!!!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!