Tuesday, 23 June 2015

Synchronization

Only methods and blocks can be synchronized, not variables or classes.
A class can have both Synchronized and non-synchronized methods.
Once a thread acquires the lock on an object, no other thread can enter any of the synchronized methods in that class (for that object).
If two threads are using the same instance of the class to invoke the method, only one thread at a time will be able to execute the method.
A thread can acquire more than one lock.
If a thread goes to sleep, it holds any locks it has-it doesn't release them.
Static methods can be synchronized.
Ex: While creating Singleton object, static and synchronized method has to create.

What is volatile keyword?

The volatile modifier tells the compiler that the variable modified by volatile can be changed unexpectedly by other parts of your program. One of these situations involves multithreaded programs.  In a multithreaded program, sometimes, two or more threads share the same instance variable. For efficiency considerations, each thread can keep its own, private copy of such a shared variable. The real (or master) copy of the variable is updated at various times, such as when a synchronized method is entered. While this approach works fine, it may be inefficient at times. In some cases, all that really matters is that the master copy of a variable always reflects its current state. To ensure this, simply specify the variable as volatile, which tells the compiler that it must always use the master copy of a volatile variable (or, at least, always keep any private copies up to date with the master copy, and vice versa). Also, accesses to the master variable must be executed in the precise order in which they are executed on any private copy.

No comments:

Post a Comment