Menu Bar

Drop Down MenusCSS Drop Down MenuPure CSS Dropdown Menu
Showing posts with label Thread Interview Question. Show all posts
Showing posts with label Thread Interview Question. Show all posts

Tuesday, 7 February 2017

How many threads does a Java program have at least ?

Each java program have atleast one thread i.e. main thread in which each program is executed.

      
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, 10 December 2016

What is the difference between the ExecutorService .submit() and Executor.execute() method in Java ?


Here we will discuss all the difference between submit() and execute() method.


execute()
submit()
This method belongs to Executor interface.
This method is belongs to ExecutorService interface.
This method can only execute Runnable interface task.
This method can take either Runnable or Callable task to execute.
Its return type is void.
It returns a Future 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 »

Thursday, 8 December 2016

What is Semaphore in Java ?


Class Semaphore

All Implemented Interfaces:

Declaration of Semaphore:
public class Semaphore
extends Object
implements Serializable

Java 5 comes with semaphore implementations in the java.util.concurrent package. Semaphores are used to restrict the number of threads than can access some resource. Semaphores  are also used to send signals between two threads
Semaphore class is a counting semaphore and it has two main methods:
  1. acquire()
  2. release()

The counting Semaphore  are initialized with a given number of permits. Each acquire() blocks if necessary until a permit is available. For each call to acquire() a permit is taken by the calling thread. And For each call to release() a permit is returned to the semaphore. Thus at most N threads can pass the acquire() method without any release() calls, where N is number of permits the semaphore was initialized with. Here permits are just simple counter and nothing else.

The constructor for this class optionally accepts a fairness parameter. When set false, this class makes no guarantees about the order in which threads acquire permits. When fairness is set true, the semaphore guarantees that threads invoking any of the acquire methods are selected to obtain permits in the order in which their invocation of those methods was processed (first-in-first-out; FIFO). 

Note that FIFO ordering necessarily applies to specific internal points of execution within these methods. So, it is possible for one thread to invoke acquire before another, but reach the ordering point after the other, and similarly upon return from the method. Also note that the untimed tryAcquire methods do not honor the fairness setting, but will take any permits that are available.

Constructor Summary of Semaphore:

Constructor
Description
Semaphore(int permits)
Creates a Semaphore with the given number of permits and nonfair fairness setting.
Semaphore(int permits, boolean fair)
Creates a Semaphore with the given number of permits and the given fairness setting.

Method Summary of Semaphore:

Modifier and Method Name
Description
void acquire()
Acquires a permit from this semaphore, blocking until one is available, or the thread is interrupted.
void acquire(int permits)
Acquires the given number of permits from this semaphore, blocking until all are available, or the thread is interrupted.
void acquireUninterruptibly()
Acquires a permit from this semaphore, blocking until one is available.
void
acquireUninterruptibly(int permits)
Acquires the given number of permits from this semaphore, blocking until all are available.
int availablePermits()
Returns the current number of permits available in this semaphore.
int drainPermits()
Acquires and returns all permits that are immediately available.
protected Collection<Thread> getQueuedThreads()
Returns a collection containing threads that may be waiting to acquire.
int getQueueLength()
Returns an estimate of the number of threads waiting to acquire.
boolean hasQueuedThreads()
Queries whether any threads are waiting to acquire.
boolean isFair()
Returns true if this semaphore has fairness set true.
protected void
reducePermits(int reduction)
Shrinks the number of available permits by the indicated reduction.
void release()
Releases a permit, returning it to the semaphore.
void release(int permits)
Releases the given number of permits, returning them to the semaphore.
String toString()
Returns a string identifying this semaphore, as well as its state.
boolean tryAcquire()
Acquires a permit from this semaphore, only if one is available at the time of invocation.
boolean tryAcquire(int permits)
Acquires the given number of permits from this semaphore, only if all are available at the time of invocation.
boolean
tryAcquire(int permits, long timeout, TimeUnit unit)
Acquires the given number of permits from this semaphore, if all become available within the given waiting time and the current thread has not been interrupted.
boolean
tryAcquire(long timeout, TimeUnit unit)
Acquires a permit from this semaphore, if one becomes available within the given waiting time and the current thread has not been interrupted.

Example of Semaphore:

import java.util.concurrent.Semaphore;

public class SemaphoreClassExample {
    private static final int CONCURRENT_THREADS = 2;
    private final Semaphore semaphore = new Semaphore(CONCURRENT_THREADS, true);
    
    public void starts() {
        for (int i = 1; i <= 5; i++) {
            Person person = new Person();
            person.start();
        }
    }
    
    class Person extends Thread {
        @Override
        public void run() {
            try {
                // Acquire Lock
            semaphore.acquire();
            } catch (InterruptedException e) {
                System.out.println("received InterruptedException");
                return;
            }
            System.out.println("Thread : " + this.getName() + " starts Acquire()");
            try {
                sleep(1000);
            } catch (Exception e) {
                
            } finally {
                // Release Lock
            semaphore.release();
            }
            System.out.println("Thread " + this.getName() + " stops Release()\n");
        }
    }
    
    public static void main(String[] args) {
        SemaphoreClassExample test = new SemaphoreClassExample();
        test.starts();
        
    }
}
Program Output:

Thread : Thread-1 starts Acquire()
Thread : Thread-3 starts Acquire()
Thread Thread-3 stops Release()

Thread Thread-1 stops Release()

Thread : Thread-0 starts Acquire()
Thread : Thread-2 starts Acquire()
Thread Thread-2 stops Release()

Thread Thread-0 stops Release()

Thread : Thread-4 starts Acquire()
Thread Thread-4 stops Release()


     
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 »

Wednesday, 7 December 2016

What is Producer Consumer Problem In Java ?


Producer Consumer Problem

The producer–consumer problem also known as the bounded-buffer problem ,it has two processes the producer and the consumer who share the common fixed size buffer. The producer job is to produce and put into the buffer, at the same time the consumer job is to consume what producer has produced ,one at a time.

The problem is to make sure the producer can not produce if the buffer is full and consumer can not consume if buffer is empty.

The solution to the problem is that, put producer to sleep is buffer is full, now the consumer will consume from buffer and it notify the producer to produce again. In the same way consumer will go for sleep if the buffer is empty, now the producer will produce ,and notify the consumer .

In multi-threading programming environment we use wait() and notify() methods to solve this problem. These methods are also used for inter-thread communication.

Example of Producer-Consumer:

class Que {
int n;
boolean status false;
synchronized int get(){
while(!status){
try {
wait();
catch (Exception e) {
e.printStackTrace();
}
}
System.out.println("OBJECT CONSUMED : "+n);
status false;
notify();
return n;
}
synchronized void put(int n){
while(status){
try {
wait();
catch (Exception e) {
e.printStackTrace();
}
}
this.n = n;
status true;
System.out.println("OBJECT PRODUCED : "+n);
notify();
}
}
class Producerr implements Runnable {

Que que;
public Producerr(Que que) {
this.que = que;
new Thread(this,"Producer").start();
}
@Override
public void run() {
int i = 0;
while(i <= 7){  //Here 7 means producer & consumer will go upto 7.
que.put(i++);
}
}
}
class Consumerr implements Runnable{
Que que;
public Consumerr(Que que) {
this.que = que;
new Thread(this,"Consumer").start();
}
@Override
public void run() {
while(true){
que.get();
}
}
}
public class ProducerConsumerExample {

public static void main(String[] args) {
Que q = new Que();
new Producerr(q);
new Consumerr(q);
}

}
Program Output:
OBJECT PRODUCED : 0
OBJECT CONSUMED : 0
OBJECT PRODUCED : 1
OBJECT CONSUMED : 1
OBJECT PRODUCED : 2
OBJECT CONSUMED : 2
OBJECT PRODUCED : 3
OBJECT CONSUMED : 3
OBJECT PRODUCED : 4
OBJECT CONSUMED : 4
OBJECT PRODUCED : 5
OBJECT CONSUMED : 5
OBJECT PRODUCED : 6
OBJECT CONSUMED : 6
OBJECT PRODUCED : 7
OBJECT CONSUMED : 7


     
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 »

Tuesday, 6 December 2016

What is thread pool ?


A thread pool is a collection of worker threads that efficiently execute asynchronous callbacks on behalf of the application. The thread pool is primarily used to reduce the number of application threads and provide management of the worker threads. Applications can queue work items, associate work with waitable handles, automatically queue based on a timer, and bind with I/O.

In thread pool ,group of threads are created, and when a service provider assign a task to thread, a thread is pulled from pool and do a task, after completion of task thread is again put into the pool. 

Using worker threads minimizes the overhead due to thread creation. Thread objects use a significant amount of memory, and in a large-scale application, allocating and deallocating many thread objects creates a significant memory management overhead.

Thread pools are often used in multi threaded servers. Each connection arriving at the server via the network is wrapped as a task and passed on to a thread pool. The threads in the thread pool will process the requests on the connections concurrently.

Java 5 comes with built in thread pools in the java.util.concurrent package, so you don't have to implement your own thread pool.

The thread pool architecture consists of the following:
  • Worker threads that execute the callback functions
  • Waiter threads that wait on multiple wait handles
  • A work queue
  • A default thread pool for each process
  • A worker factory that manages the worker threads


Example of ThreadPool :

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

class WorkerThread implements Runnable {

String msg = "";
public WorkerThread(String msg) {
this.msg = msg;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+" : Thread Started, "+"Message : "+msg);
try {
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+" : Thread Ended");
}
}
public class ThreadPoolExample {

public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(7); //Thread Pool with 7 threads
for(int i=1;i<=10;i++){
Runnable wo = new WorkerThread(""+i);
executorService.execute(wo);
}
executorService.shutdown();
while(!executorService.isTerminated()){
}
System.out.println(" : All THREADS ARE EXECUTED : ");
}

}
Program Output:
pool-1-thread-2 : Thread Started, Message : 2
pool-1-thread-5 : Thread Started, Message : 5
pool-1-thread-3 : Thread Started, Message : 3
pool-1-thread-4 : Thread Started, Message : 4
pool-1-thread-1 : Thread Started, Message : 1
pool-1-thread-6 : Thread Started, Message : 6
pool-1-thread-7 : Thread Started, Message : 7
pool-1-thread-4 : Thread Ended
pool-1-thread-4 : Thread Started, Message : 8
pool-1-thread-6 : Thread Ended
pool-1-thread-6 : Thread Started, Message : 9
pool-1-thread-3 : Thread Ended
pool-1-thread-3 : Thread Started, Message : 10
pool-1-thread-2 : Thread Ended
pool-1-thread-5 : Thread Ended
pool-1-thread-7 : Thread Ended
pool-1-thread-1 : Thread Ended
pool-1-thread-4 : Thread Ended
pool-1-thread-3 : Thread Ended
pool-1-thread-6 : Thread Ended
 : All THREADS ARE EXECUTED : 


      
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 »

Monday, 5 December 2016

What is the difference between the interrupted() and isInterrupted() method in Java ?


interrupted

Declaration of interrupted:
public static boolean interrupted()

Tests whether the current thread has been interrupted. The interrupted status of the thread is cleared by this method. In other words, if this method were to be called twice in succession, the second call would return false (unless the current thread were interrupted again, after the first call had cleared its interrupted status and before the second call had examined it).

A thread interruption ignored because a thread was not alive at the time of the interrupt will be reflected by this method returning false.

It Returns true if the current thread has been interrupted, false otherwise.

isInterrupted

Declaration of isInterrupted:
public boolean isInterrupted()

Tests whether this thread has been interrupted. The interrupted status of the thread is unaffected by this method.

A thread interruption ignored because a thread was not alive at the time of the interrupt will be reflected by this method returning false.

It Returns true if this thread has been interrupted, false otherwise.



      
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 »

Why wait, notify and notifyAll are not inside thread class ?

These methods works on the locks and locks are associated at Object level not at Thread level.So, that's why these methods belongs to Object class.The methods wait(), notify() and notifyAll() are also used for inter-thread communication in Threads.

In Java, Synchronization make sure that only one thread will access the object or resources at one time.

In Java, any object can act as a monitor, An object's method without qualifed by the keyword synchronized  can be invoked by any number of  threads at any time, the lock is ignored. 
The synchronized method of an object, who owns the lock of that object, can be permitted to run that method at any time i.e. a synchronized method is mutually exclusive .If, at the time of invocation, another thread owns the lock, then the calling thread will be put in the Blocked state and is added to the entry queue.

When a thread running in a synchronized method of an object is calling the wait() method of the same object, that thread releases the lock of the object and is added to that object's waiting queue. As long as it's there, it sits idle.
Note also that wait() forces the thread to release its lock. This means that it must own the lock of an object before calling the wait() method of that (same) object. Hence the thread must be in one of the object's synchronized methods or synchronized block before calling wait().



      
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 happens when an Exception occurs in a thread ?

The most important question usually asked in interview about what happen if thread throws Exception.

If Exception is not caught then thread will die.It will prints the Exception to the console.The Thread itself will exit at this point, it couldn't continue anyway, because its run() method has finished.

So if you want the exception to be re-raised in your main thread, you can define an UncaughtExceptionHandler. And then call Thread.setUncaughtExceptionHandler on that thread after its created ,passing in your custom Exception handler.

Any uncaught exception from a thread is propagated to the thread's UncaughtExceptionHandler. If there's none defined, it goes to the thread group's handler, if that isn't set either, it goes to the default handler.



      
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 »