Monday, 28 November 2016

What is the difference between Process and Thread ?

Both processes and threads have independent path of execution. 

Processes are heavy-weight, while threads are light-weight process.

A process can have multiple threads, and thread is a smallest part of the process.

Processes share the different memory spaces, while all threads share the same memory space. In process all threads share system resources like heap memory. while threads has its own stack memory.

Any changes made to process does not affect child process, but any change made to thread can affect the behavior of the other thread .

Processes can easily communicate with child processes, but inter-process communication is difficult. While threads can easily communicate with each other using wait() and notify() methods.



      
Blog Author - Pushkar Khosla,
Software Developer by Profession with 3.0 Yrs of Experience , through this blog i'am sharing my industrial Java Knowledge to entire world. For any question or query any one can comment below or mail me at pushkar.itsitm52@gmail.com.

This blog is all about to learn Core Java ,Interview Programs and Coding tricks to polish your Java Knowledge. If you like the content of this blog please share this with your friends.



Read More »

Sunday, 27 November 2016

What is Daemon Thread In Java ?

Previously we have discussed about
Daemon Thread

When we create a Thread in java, by default its a user defined thread.In order to create a daemon thread ,thread class provide a method named as setDaemon() which is used to set Thread as Daemon thread.

Daemon thread is a low priority based thread that runs in background to perform some tasks such as : garbage collection etc.

Daemon thread life depends upon on the user defined threads.

Thread.setDaemon(true) : This method makes a User Thread to Daemon thread but it can only be called before starting a Thread in java.It will throw IllegalThreadStateException if corresponding Thread is already started and running.

Thread.setDaemon(false) : This method makes Daemon Thread back to normal thread .

public boolean isDaemon() : This method is used to determine weather a thread is Daemon or not.

Difference between Daemon and Non Daemon Thread :
  • JVM does not wait for any daemon thread to finish before exiting.
  • Daemon threads are treated differently than user defined thread when JVM terminates, finally blocks are not called ,and JVM just exits.

Example of Daemon Thread:

public class DeamonThreadExample extends Thread {
public void run(){
try {
if(Thread.currentThread().isDaemon()){
System.out.println("Daemon Thread Executing.");
}
else{
System.out.println("Normal Thread is Executing.");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println("Daemon Thread Exiting.");
}
}
public static void main(String[] args) {
DeamonThreadExample t1 = new DeamonThreadExample();
DeamonThreadExample t2 = new DeamonThreadExample();
t1.setDaemon(true);
t1.start();
t2.start();
}

}
Program Output:
Daemon Thread Executing.
Normal Thread is Executing.
Daemon Thread Exiting.
Daemon Thread Exiting.

Example of Daemon Thread throwing Exception:

public class DeamonThreadExample extends Thread {
public void run(){
try {
if(Thread.currentThread().isDaemon()){
System.out.println("Daemon Thread Executing.");
}
else{
System.out.println("Normal Thread is Executing.");
}
catch (Exception e) {
e.printStackTrace();
finally {
System.out.println("Daemon Thread Exiting.");
}
}
public static void main(String[] args) {
DeamonThreadExample t1 = new DeamonThreadExample();
DeamonThreadExample t2 = new DeamonThreadExample();
t1.setDaemon(true);
t1.start();
t2.start();
}

}
Program Output:
Normal Thread is Executing.Exception in thread "main" 
Daemon Thread Exiting.
java.lang.IllegalThreadStateException
at java.lang.Thread.setDaemon(Unknown Source)
at thread.DeamonThreadExample.main(DeamonThreadExample.java:23)



      
Blog Author - Pushkar Khosla,
Software Developer by Profession with 3.0 Yrs of Experience , through this blog i'am sharing my industrial Java Knowledge to entire world. For any question or query any one can comment below or mail me at pushkar.itsitm52@gmail.com.

This blog is all about to learn Core Java ,Interview Programs and Coding tricks to polish your Java Knowledge. If you like the content of this blog please share this with your friends.



Read More »

What is Deadlock In Java. And How to Avoid It ?

Previously we have discussed about


DeadLock

Deadlock describes a situation where two or more threads are blocked forever, waiting for each other.
Means when a thread is waiting for an object lock that is acquired by another thread and second thread is waiting for an object lock that is acquired by the first thread. So both the threads are waiting for each other to release a lock ,this situation or condition is called a Deadlock.

Example Showing Deadlock:
if thread1  and thread1 both will be called by two or many threads ,there is a good chance of deadlock because if thread 1 acquires lock on Sting object  while executing thread1 and thread 2 acquires lock on Integer object while executing thread2 both will be waiting for each other to release lock on Integer and String to proceed further which will never happen.

public class DeadLockDemo {
public static void main(String[] args) {
Thread thread1 = new Thread(){
public void run(){
synchronized(String.class){
System.out.println("Thread 1 : Aquired lock on String.class object");
try {
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
synchronized(Integer.class){
System.out.println("Thread 1 : Aquired lock on Integer.class object");
}
}
}
};
Thread thread2 = new Thread(){
public void run(){
synchronized (Integer.class) {
System.out.println("Thread 2 : Aquired lock on Integer.class object");
try {
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
synchronized (String.class) {
System.out.println("Thread 2 : Aquired lock on String.class object");
}
}
}
};
thread1.start();
thread2.start();
}
}
Program Output:
Thread 1 : Aquired lock on String.class object
Thread 2 : Aquired lock on Integer.class object



How to avoid deadlocks:

The best way to prevent deadlock is to avoid acquiring more than one lock at a time. However If it is not possible then you need to ensure that resources must be defined in some order.

Example Avoiding Deadlock:
Now there would not be any deadlock because both Threads are accessing lock on  Integer and String class literal in same order. So, if thread1 acquires lock on Integer object , thread2 will not proceed until thread1 releases Integer lock, same way thread1 will not be  blocked even if thread2 holds String lock because now thread2 will not expect thread1 to release Integer lock to proceed further.

public class DeadLockAvoid {
public static void main(String[] args) {
Thread thread1 = new Thread(){
public void run(){
synchronized(String.class){
System.out.println("Thread 1 : Aquired lock on String.class object");
try {
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
synchronized(Integer.class){
System.out.println("Thread 1 : Aquired lock on Integer.class object");
}
}
}
};
Thread thread2 = new Thread(){
public void run(){
synchronized(String.class){
System.out.println("Thread 2 : Aquired lock on String.class object");
try {
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
synchronized(Integer.class){
System.out.println("Thread 2 : Aquired lock on Integer.class object");
}
}
}
};
thread1.start();
thread2.start();
}
}
Program Output:
Thread 1 : Aquired lock on String.class object
Thread 1 : Aquired lock on Integer.class object
Thread 2 : Aquired lock on String.class object
Thread 2 : Aquired lock on Integer.class object



      
Blog Author - Pushkar Khosla,
Software Developer by Profession with 3.0 Yrs of Experience , through this blog i'am sharing my industrial Java Knowledge to entire world. For any question or query any one can comment below or mail me at pushkar.itsitm52@gmail.com.

This blog is all about to learn Core Java ,Interview Programs and Coding tricks to polish your Java Knowledge. If you like the content of this blog please share this with your friends.



Read More »

Saturday, 26 November 2016

Suspending, Resuming, and Stopping Thread with Example.

Previously we have discussed about

Note : In Java 1.1 the suspend(), resume() and stop() methods were used to perform some operations like suspending, resuming and stopping a Thread. These three methods have been deprecated since the release of Java 2 and not used in modern Java programming. The main reason for deprecating these methods was to prevent the occurrence of deadlock situations and system failures in a multi-threaded environment.

The functions of suspending, resuming and stopping a thread are performed using Boolean type flags in a multi-threading environment.
These flags store the current status of the Threads. The run() method works according to the current boolean value of these three flags.

If the suspend flag is set to true then run() method will suspend the execution of the currently running thread. Similarly ,if the resume flag is set true then run() method will resume the execution of the suspended thread. Apart from the suspend and resume a thread will get terminated once the stop flag of the thread is set to true.

Example of Suspend,resume and stop Operations:

class MyThread implements Runnable {
Thread th;
boolean suspend_Flag;
boolean resume_Flag;
boolean stop_Flag;
public MyThread(String st) {
th = new Thread(this,st);
suspend_Flag = false;
stop_Flag = false;
th.start();
}
@Override
public void run() {
try {
int j = 1;
while(++j<20){
synchronized (this) {
while(suspend_Flag){
wait();
}
if(stop_Flag){
break;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
synchronized void suspend(){
suspend_Flag = true;
}
synchronized void resume(){
suspend_Flag = false;
notify();
}
synchronized void stop(){
suspend_Flag = false;
stop_Flag = true;
notify();
}
}
public class SysResAndStopExample {

public static void main(String[] args) {
try {
MyThread t = new MyThread("INDIA");
System.out.println("Thread MyThread is Created & Started :");
Thread.sleep(1000);
t.suspend();
System.out.println("Thread MyThread is Suspended");
Thread.sleep(1000);
t.resume();
System.out.println("Thread MyThread is Resume");
Thread.sleep(1000);
t.suspend();
System.out.println("Thread MyThread is Suspended.");
Thread.sleep(1000);
t.resume();
System.out.println("Thread MyThread is Resume.");
Thread.sleep(1000);
t.stop();
System.out.println("Thread MyThread is Stop.");
} catch (Exception e) {
e.printStackTrace();
}
}

}
Program Output:
Thread MyThread is Created & Started :
Thread MyThread is Suspended
Thread MyThread is Resume
Thread MyThread is Suspended.
Thread MyThread is Resume.
Thread MyThread is Stop.

      
Blog Author - Pushkar Khosla,
Software Developer by Profession with 3.0 Yrs of Experience , through this blog i'am sharing my industrial Java Knowledge to entire world. For any question or query any one can comment below or mail me at pushkar.itsitm52@gmail.com.

This blog is all about to learn Core Java ,Interview Programs and Coding tricks to polish your Java Knowledge. If you like the content of this blog please share this with your friends.



Read More »

Java Thread Exception.

Previously we have discussed about
Java Thread Exception

The call to sleep() method throws InterruptedException, so we enclosed in a try block and followed by a catch block ,because exception should be caught.If we fail to catch the exception ,program will not compile.

Java run system will throw IllegalThreadStateException whenever we attempt to invoke a method that a thread can not handle in the given state.

For Example : a sleeping thread can not deal with the resume() method because a sleeping thread can not recieve any instructions. The same is true with the suspend() method when it is used on a blocked (Non Runnable) thread.

Whenever we call a thread method that is likely to throw an exception, we have to supply an appropriate exception handler to catch it.The catch statement may take one of the following forms:

catch(ThreadDeath e){
----------
}
catch(InterruptedException e){
----------
}
catch(IllegalArgumentException e){
----------
}
catch(Exception e){
-----------
}

      
Blog Author - Pushkar Khosla,
Software Developer by Profession with 3.0 Yrs of Experience , through this blog i'am sharing my industrial Java Knowledge to entire world. For any question or query any one can comment below or mail me at pushkar.itsitm52@gmail.com.

This blog is all about to learn Core Java ,Interview Programs and Coding tricks to polish your Java Knowledge. If you like the content of this blog please share this with your friends.



Read More »

Inter Thread Communication In Java.

Previously we have discussed about
Inter-Thread Communication Methods

Inter Thread Communication

Inter Thread Communication means exchange of messages between two or more threads.The Transfer of messages takes place before or after the change of state of Thread.
For Example an active thread may notify to another suspended thread just before switching to the suspend state. Java Implements inter thread communication with the help of the following three methods: wait(), notify() and notifyall().
These methods are implemented as final methods in object class , so all classes have these methods.

wait() : This method tells calling thread to give up and go to sleep untill some other thread enters the same state and calls notify() or notifyall(). The Object class declaration of notifyall() method is shown below :
final void wait()

notify() : It Resume the thread that went into the sleep state.The Object class declaration of notifyall() method is shown below :
final void notify()

notifyall() : It Resume all threads that went into the sleep state.The execution of these threads happens as per per priority.The Object class declaration of notifyall() method is shown below :
final void notifyall()

Example of Inter Thread Communication:

class User{
int rs = 500;
synchronized void get(int rs){
System.out.println("Getting Rs ");
if(this.rs < rs){
System.out.println("Less Rupees ");
try {
wait();
} catch (Exception e) {
e.printStackTrace();
}
}
this.rs = rs;
System.out.println("Getting Rs Completed ..");
}
synchronized void put(int rs){
System.out.println("Depositing Rs..");
this.rs += rs;
System.out.println("Depositing Completed.");
notify();
}
}
public class InterThreadCommunicationExample1 {

public static void main(String[] args) {
User u = new User();
new Thread(){
public void run(){
u.get(1000);
}
}.start();
new Thread(){
public void run(){
u.put(200);
}
}.start();
}

}
Program Output:
Getting Rs 
Less Rupees 
Depositing Rs..
Depositing Completed.
Getting Rs Completed ..


      
Blog Author - Pushkar Khosla,
Software Developer by Profession with 3.0 Yrs of Experience , through this blog i'am sharing my industrial Java Knowledge to entire world. For any question or query any one can comment below or mail me at pushkar.itsitm52@gmail.com.

This blog is all about to learn Core Java ,Interview Programs and Coding tricks to polish your Java Knowledge. If you like the content of this blog please share this with your friends.



Read More »

Using isAlive() and join() Methods In Java ?

Previously we have discussed about

There are two ways to determine whether a thread has finished its execution or not. First method is isAlive() and second is join() method.

isAlive() : 
The general form is isAlive() method is : public final boolean isAlive()
This method returns true if the thread upon which it is called is still running.Otherwise it returns false.

Example of isAlive():

public class IsAliveExample extends Thread {

public void run(){
System.out.println("IN run method : ");
try {
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("OUT run method : ");
}
public static void main(String[] args) {
IsAliveExample t1 = new IsAliveExample();
IsAliveExample t2 = new IsAliveExample();
t1.start();
t2.start();
System.out.println("T1 Status : "+t1.isAlive());
System.out.println("T2 Status : "+t2.isAlive());
}

}
Program Output:
IN run
IN run
T1 Status : true
T2 Status : true
OUT Run
OUT Run

join() :
The general form of join() method is : 
public final void join() throws InterruptedException

The join() method is used more commonly than isAlive(), This method waits until the thread on which it is called terminates.
Using join() method, we tell our thread to wait until the specified thread completes its execution. 
In join() method we can also specify a maximum amount of time that you want to wait for specified thread to terminate.

Its Declaration form is :
final void join(long milliseconds) throws InterruptedException

Example of join():
In this program join() method ensure that Thread t1 finishes its processing before Thread t2 starts. 

public class JoinMethodExample extends Thread{
public void run(){
System.out.println("In Run");
try {
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Out Run");
}
public static void main(String[] args) {
JoinMethodExample t1 = new JoinMethodExample();
JoinMethodExample t2 = new JoinMethodExample();
t1.start();
try {
t1.join();
} catch (Exception e) {
e.printStackTrace();
}
t2.start();
}
}
Program Output:
In Run
Out Run
In Run
Out Run


      
Blog Author - Pushkar Khosla,
Software Developer by Profession with 3.0 Yrs of Experience , through this blog i'am sharing my industrial Java Knowledge to entire world. For any question or query any one can comment below or mail me at pushkar.itsitm52@gmail.com.

This blog is all about to learn Core Java ,Interview Programs and Coding tricks to polish your Java Knowledge. If you like the content of this blog please share this with your friends.



Read More »