Synchronization
Multithreading
introduced asynchronous behavior.
If a
thread is writing some data another thread may be reading the same data at that
time.
This may
lead to data inconsistent problem.
To
overcome this problem, we should go for synchronized keyword.
If a method or block declared as synchronized, then at a time only one
thread is allowed to execute that method or block on the given object so that
data inconsistency problem will be resolved.
Hence
there is no specific requirement then it is not recommended to use synchronized
keyword.
While a
thread executing synchronized method on the given object the remaining thread
not allowed to execute any synchronized method simultaneously
But
remaining threads are allowed to execute non synchronized methods
simultaneously.
class Bank{
Synchronized area(){
//whenever we are performing update operation (add/remove/delete/replace)
i.e., where state of obj changing
}
Non -Synchronized area(){
//like read operation
i.e., where state of obj wont changed
}}
Problem with traditional synchronized keyword
Every object in Java has a unique lock whenever we are
using synchronization keyword then only lock concept will come into the
picture.
If a thread wants to execute synchronized method on the
given object.
first it must get lock of that object.
Once thread got locked then it is allowed to execute any
synchronization method on that object.
Once method execution completed automatically thread
releases lock.
Acquiring and releasing lock internally takes care by JVM
and programmer not responsible for this activity.
If a thread releases the lock, then which waiting thread
will get that lock we are not having any control over this.
We can’t specify the maximum waiting time for a thread to
get a lock so that it will wait until getting a lock, which may affect performance of the system and causes a deadlock.
We are not having any flexibility to Try for a lock
without waiting.
There is no API to list all waiting threads for a lock.
The synchronized keyword compulsory we must define within
a method and if is not possible to declare over multiple threads.
The above listed are the common problems that are faced
by the programmer or before the java.util.concurrent.locks package is
introduced.
To overcome all these problems java.util.concurrent.locks
package is introduced in Java 1.5 version. Also, it provides several
enhancements to the programmer to provide more control of Concurrency.
No comments:
Post a Comment