Synchronization
The process of restricting only one thread can access the resource at a given point of time is know as
Synchronization.
➔ We can achieve Synchronization using synchronized keyword.
• Synchronisation internally uses say lock concept
• In Java Each and every object contains a unique lock
• Each and every object comes with only one lock whenever we are executing a
synchronised method or a block on a particular object then the lock of object is required.
• Whenever we are executing non synchronised methods or block then the lock is not
required.
• If the thread is trying to execute synchronised method or a block then first it occupies
the lock of that object once the execution completes then automatically it releases the
lock.
• Acquiring and release in the lock is taken care by JVM.
• While a threat executing synchronised method on a given object then the remaining
thread are not allowed to execute any synchronised method or a block simultaneously
on the same object, but remaining threads can execute non synchronised methods or a
block simultaneously.
Advantages of synchronization
It is used to resolve data inconsistency problem
Drawback :
o It increases the waiting time of a thread
o It decreases the performance of an application
Example :
Synchronized Block
package [Link];
public class Table {
void printTable(int n) {
[Link]("heloo");
synchronized (this) {
for (int i = 1; i <= 10; i++) {
[Link](n + " x " + i + " = " + (n * i));
}
}
}
}
Or
Synchronized method
public class Table {
synchronized void printTable(int n) {
for (int i = 1; i <= 10; i++) {
[Link](n+" x "+i+ " = "+(n*i));
}
}
}
package [Link];
public class User1 extends Thread {
Table tab;
User1(Table ref) {
tab = ref;
}
@Override
public void run() {
[Link](5);
}
}
class User2 extends Thread {
Table tab;
public User2(Table ref) {
tab = ref;
}
@Override
public void run() {
[Link](10);
}
}
package [Link];
public class Main {
public static void main(String[] args) {
Table t=new Table();
User1 u1=new User1(t);
User2 u2=new User2(t);
[Link]();
[Link]();
}
}