Saturday, November 30, 2013

Synchronization Concept

What is synchronization ?
-----------------------------

I will explain with bad example....
But easy to understand

I will compare... java object having several methods
as
House with various rooms(Bathroom is one of the room)

Generally.. if one person enters bathroom no other person
will enter right ?

The other person waits... until the person in the bathroom
comes out.

I will compare persons in the house with threads..

Bathroom and synchronized methods behave same...

When one person entered bathroom,no other person in
the house can enter bathroom right ?
(synchronized methods)

But still the person waiting for bathroom can enter
other rooms like dining room,kitchen room etc..
(non synchronized methods)

Now if we compare with threads

When one thread enters synchronized method no other
thread can enter any synchronized method...(there may
be multiple methods with keyword synchronized right)
So,if one thread enters synchronized no other thread
should enter any other synchronized method..

But... the other threads can still... enter non synchronized
methods....

Finally...

If one thread enters synchronized method in object A ,other
threads cannot enter.. other synchronized methods in object A
but..... synchronized method in object B can be accessed
as it is completely different object(room in another house)

Very very imp:
-----------------
If there are 3 synchronized methods...
You have to compare

3 synchronized methods(A,B,C) collectively as a bathroom
2 non synchronized methods E,F.
What I want to say is

When one person enters bathroom.. no one can enter
right

Similarly

When thread A enters any one synchronized method out of 3 say A,
Thread B can't enter A or B or C.

But Thread B can still enter E,F...

If you don't understand this... you will implement coding
badly.........

But Thread A can enter all the methods....synchronzied (A,B,C) and non synchronized (E,F)

Thread concept looks simple..... But in realtime... it will be tough
to identify.. where there can be potential.. thread related issues....
unless u r really really good in this theory....

No comments:

Post a Comment