Menu Bar

Drop Down MenusCSS Drop Down MenuPure CSS Dropdown Menu
Showing posts with label Java Thread Tutorial. Show all posts
Showing posts with label Java Thread Tutorial. Show all posts

Saturday, 10 December 2016

What is ExecutorService Interface In Java ?

Previously we have discussed about 
Interface ExecutorService

All Superinterfaces:

All Known Subinterfaces:
ScheduledExecutorService

All Known Implementing Classes:
AbstractExecutorService, ForkJoinPool, ScheduledThreadPoolExecutor, ThreadPoolExecutor

Declaration of ExecutorService:
public interface ExecutorService
extends Executor

The java.util.concurrent.ExecutorService interface represents an asynchronous execution mechanism which is capable of executing tasks in the background. An ExecutorService is thus very similar to a thread pool.

An ExecutorService can be shut down, which will cause it to reject new tasks. Two different methods are provided for shutting down an ExecutorService. The shutdown() method will allow previously submitted tasks to execute before terminating, while the shutdownNow() method prevents waiting tasks from starting and attempts to stop currently executing tasks.

Method submit() extends base method Executor.execute(java.lang.Runnable) by creating and returning a Future that can be used to cancel execution and/or wait for completion.

Methods invokeAny() and invokeAll() perform the most commonly useful forms of bulk execution, executing a collection of tasks and then waiting for at least one, or all, to complete.

The Executors class provides factory methods for the executor services provided in this package.

Method Summary of ExecutorService Interface:


Modifier and Method Name
Description
boolean
awaitTermination(long timeout, TimeUnit unit)
Blocks until all tasks have completed execution after a shutdown request, or the timeout occurs, or the current thread is interrupted, whichever happens first.
<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
Executes the given tasks, returning a list of Futures holding their status and results when all complete.
<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit)
Executes the given tasks, returning a list of Futures holding their status and results when all complete or the timeout expires, whichever happens first.
<T> T invokeAny(Collection<? extends Callable<T>> tasks)
Executes the given tasks, returning the result of one that has completed successfully (i.e., without throwing an exception), if any do.
<T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit)
Executes the given tasks, returning the result of one that has completed successfully (i.e., without throwing an exception), if any do before the given timeout elapses.
boolean isShutdown()
Returns true if this executor has been shut down.
boolean isTerminated()
Returns true if all tasks have completed following shut down.
void shutdown()
Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted.
List<Runnable> shutdownNow()
Attempts to stop all actively executing tasks, halts the processing of waiting tasks, and returns a list of the tasks that were awaiting execution.
<T> Future<T> submit(Callable<T> task)
Submits a value-returning task for execution and returns a Future representing the pending results of the task.
Future<?> submit(Runnable task)
Submits a Runnable task for execution and returns a Future representing that task.
<T> Future<T> submit(Runnable task, T result)
Submits a Runnable task for execution and returns a Future representing that task.


      
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 Executor Interface In Java ?

Interface Executor

All Known Subinterfaces:
ExecutorService, ScheduledExecutorService

All Known Implementing Classes:
AbstractExecutorService, ForkJoinPool, ScheduledThreadPoolExecutor, ThreadPoolExecutor

Declaration of Executor:
public interface Executor

An Executor is normally used instead of explicitly creating threads.For example, rather than invoking new Thread(new(RunnableTask())).start(); for each of a set of tasks, you might use:

Executor executor = anExecutor;
executor.execute(new RunnableTask1());
executor.execute(new RunnableTask2());

Executor executes submitted Runnable tasks. This interface provides a way of decoupling task submission from the mechanics of how each task will be run, including details of thread use, scheduling, etc.

Method Summary of Executor Interface:

Modifier and Method Name
Description
void execute(Runnable command)
Executes the given command at some time in the future.


      
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 »