• Post Reply Bookmark Topic Watch Topic
  • New Topic

Newbie question about synchronization across instances

 
Wilson Mui
Ranch Hand
Posts: 140
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am very new at Threads so I was hoping to get some information here.
I was wondering when I synchronize a method, and then lets say I create multiple threads (just 2), that each has objects that call this synchronized method. That means that method is only called, by one of those objects at any given moment right?
So, in a way, it is almost like the method is like a static method. But lets say I have a method that is synchronized and it alters the information contained in the Object that contains it ONLY. Why would I ever really need to synchronize that method, when I really have no fear of the method altering data that can be accessed by another Object.
 
Greg Charles
Sheriff
Posts: 3010
12
Firefox Browser IntelliJ IDE Java Mac Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, a synchronized method is really nothing like a static method.
Two threads can access the same object, right? To put it into more tangible terms, let's imagine the object is a chalkboard, and the threads are two people building widgets. When a person finishes a widget, she goes to the chalkboard, reads the number printed there, adds one, erases the old number, and writes the new one. Now let's say both people finish widgets at about the same time. They both go to the chalkboard and read the number 3 there, and start the addition step. First one erases the 3, and writes 4, then the other one, having already done the addition, erases the 4, and writes 4 again. One widget has been miscounted!
OK, back into computer terms. The chalkboard is an object with an increment method. It looks something like this:
synchronized void increment()
{
int count = readCounter();
count = count + 1;
updateCounter(count);
}
We have to synchronize the method to make sure the read / compute / update process completes for one thread before another begins. Synchronizing the method make sure it happens that way.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!