![]() |
![]() |
Introduction of Errors | |
Java Exceptions | |
Java Try Block | |
Java Catch Block | |
Java Finally Block | |
Java Throw Keyword | |
Java Throws Keyword | |
Java Builtin Exceptions | |
User Defined Exceptions |
Java Multithreading | |
Creating a Thread | |
Thread Life Cycle | |
Thread Exceptions | |
Thread Synchronization |
Java Programs | |
Java Keywords Dictionary | |
Java Interview Questions |
Synchronization is the process of making sure threads don’t interfere with each other by accessing resources at the same time.
Some resources in programming (such as files, database, etc)cannot be handled very well.
When two or more threads want to access to a shared resource, there is requirnment of the shared resource must be used by only one thread at a time. The Synchronization process is used to achive this task.
Example
One thread is trying to read records form a file while another thread is still writting to the same file. In java, this problem can be overcome by using technique called as Synchronization.
This problem is overcome by using a special type of keyword called as synchronized
synchronized returnType methodName() { // code for synchronized method ..... ..... ..... }
class Synchro { synchronized void show(String msg) { System.out.print("Hey "+msg); try { Thread.sleep(1000); } catch(InterruptedException ie) { System.out.println("Error occured "); } System.out.println(" What's up"); } } class SynTest extends Thread { String mymsg; Synchro sync; Thread t; public SynTest(Synchro s,String ss) { sync = s; mymsg = ss; t = new Thread(this); t.start(); } public void run() { sync.show(mymsg); } } public class Test { public static void main(String[] args) { Synchro mysync = new Synchro(); SynTest st = new SynTest(mysync, "Jack"); SynTest st2 = new SynTest(mysync, "James"); SynTest st3 = new SynTest(mysync, "Keren"); } }
Output
A deadlock is a situation in which two or more competing actions are each waiting for the other to finish, but neither of them ever does.
Example
Suppose the thread A must access method1() before it can release method2(), but thread B cannot release method1() until it gets hold of method2(). These mutually exclusive conditions,a deadlock occurs.
Deadlock is difficult to detect because :