Page 1 of 1

Java Question!

Posted: Fri Oct 09, 2009 12:25 pm
by Ninja
I do not know if this is the right forum for Java Questions. If not I apologise.

In TvT Event we have this code:

Code: Select all

synchronized (_participatedPlayers)		{			_participatedPlayers.put(playerInstance.getObjectId(), playerInstance);		}
Is it possible to explain to me what exactly is the job of "synchonized"? I search the internet and other pages and I read something about locks, synchronization methods, synchronization statements e.t.c but still I do not get it. Anyone please explain me this in "English" not "Programming English".
Thanks.

Re: Java Question!

Posted: Sat Oct 10, 2009 10:42 am
by Ninja
It seems my question is not simple to explain :(.

Re: Java Question!

Posted: Sat Oct 10, 2009 10:53 am
by Ashitaka
Hi Ninja,

In one simple sentence taken from java tutorials:
"Synchronized Methods describes a simple idiom that can effectively prevent thread interference and memory consistency errors."

Imagine that you are buying a ticket for the cinema, the person who is selling you the ticket can do 3 actions (functions):
- Decrement the number of tickets remaining (when someone buy a ticket)
- Increment the number of tickets remaining (when someone cancel a ticket)
- Inform to the clients how many tickets remain.

Assuming that the person who is selling the tickets have to do the following to accomplish each task:
Decrement:
1.- Retrieve the number of tickets.
2.- Decrease in one.
3.- Store the value in the system.

Increment: Same as decrement but step 2 increasing instead of decreasing.

Now let's imagine that two clients are being served at the same time: Client A buy a ticket and Client B cancel a ticket.

This is what the seller does:

Retrieve the value for the client A (Answer: 4)
Retrieve the value for the client B (Answer: 4)
Decrease in 1 for the client A (now for the client A is 4-1=3)
Increase in 1 for the cancelation of client B (Now for the client B is (4+1=5)
Store the value for the client A (the seller stores 3)
Store the value for the client B (the seller stores 5)

Final result: Remaining tickets 5 instead of 4.

That is what is called Thread interference and synchronized methods makes the seller to serve only one client at the same time.

Try to read java sun tutorials for more information HERE

Re: Java Question!

Posted: Sat Oct 10, 2009 1:53 pm
by Ninja
Thanks for the excellent explanation.

So synchronized is just to avoid deadlocks?

Re: Java Question!

Posted: Sat Oct 10, 2009 3:00 pm
by Ashitaka
Ninja wrote:Thanks for the excellent explanation.

So synchronized is just to avoid deadlocks?
Ninja, please read again the description and documentation. Synchronization prevent thread interference and memory consistency errors, and those are not just deadlocks.

Re: Java Question!

Posted: Sun Oct 11, 2009 6:52 am
by denser
it means just cue of tasks. just work with func step by step, 1 by 1 :)