Showing posts with label Java Threading interview Questions. Show all posts
Showing posts with label Java Threading interview Questions. Show all posts

Sunday, August 26, 2012

Thread Programming Interview Questions in Java 2


Q) How to set & get Priority in Threads using java?

public class ThreadExample implements Runnable{

public  void run(){
System.out.println("Thread Starting");

{
for(int i=0;i<9;i++)
System.out.print(i);
}
}

public static void main(String args[]){
Thread t1=new Thread(new ThreadExample());
t1.start();

Thread t2= new Thread(new ThreadExample());
t2.start();

System.out.println("Thread 1 Priority"+t1.getPriority());

t2.setPriority(9);

System.out.println("Thread 2 Priority "+t2.getPriority());

}

}

Output
=============
Thread Starting
Thread Starting
012345678Thread 1 Priority5
Thread 2 Priority 5
012345678

Q) Difference between green thread and native thread in Java?
A) Native threads can switch between threads pre-emptively, switching control from a running thread to a non-running thread at any time. Green threads only switch when control is explicitly given up by a thread (Thread.yield(), Object.wait(), etc.) or a thread performs a blocking operation (read(), etc.).
On multi-CPU machines, native threads can run more than one thread simultaneously by assigning different threads to different CPUs. Green threads run on only one CPU.

Q)  Difference between thread and process?
A) Threads share the address space of the process that created it; processes have their own address space.
Threads have direct access to the data segment of its process; processes have their own copy of the data segment of the parent process.
Threads can directly communicate with other threads of its process; processes must use interprocess communication to communicate with sibling processes.

Q) Thread Life Cycle?



Q) What is context switching in multi-threading?
A) When doing context switching on a single-core processor, the code responsible is executed on the only CPU which takes care of switching the threads.
The kernel is multi-threaded. It can execute on any core. When a core comes to need to swap threads, it invokes the part of the kernel responsible for selecting the next thread it should execute.

5)  What thread-scheduling algorithm is used in Java?
6)  What is thread-scheduler in Java?
7)  How do you handle un-handled exception in thread?
8)  What is thread-group, why its advised not to use thread-group in Java?
9)  Why Executor framework is better than creating and managing thread by application ?
10) Difference between Executor and Executors in Java?
10) How to find which thread is taking maximum cpu in windows and Linux server?


Q) In which class would you find the methods sleep() and yield()?  Thread class

Q) Can you notify a particular thread? :   No

Q) How to make a normal thread as daemon thread?
A) We should call setDaemon(true) method on the thread object to make a thread as daemon thread.

Q) Give one good example of a daemon thread? : Garbage Collector is a low priority daemon thread.

Q) What are the two ways that a code can be synchronised?
A) Method can be declared as synchronised and A block of code be sychronised.


Q)What happens when I make a static method as synchronized?
A) Synchronized static methods have a lock on the class "Class", so when a thread enters a synchronized static method, the class itself gets locked by the thread monitor and no other thread can enter any static synchronized methods on that class. This is unlike instance methods, as multiple threads can access "same synchronized instance methods" at same time for different instances.


Q) Can a thread execute another objects run() method?
A) A thread can execute it's own run() method or another objects run() method.

Q) What are different ways in which a thread can enter the waiting state?
A) A thread can enter the waiting state by the following ways:
1. Invoking its sleep() method,
2. By blocking on I/O
3. By unsuccessfully attempting to acquire an object's lock
4. By invoking an object's wait() method.
5. It can also enter the waiting state by invoking its (deprecated) suspend() method.

Q) What is the difference between yielding and sleeping?
When a task invokes its yield() method, it returns to the ready state, either from waiting, running or after its creation. When a task invokes its sleep() method, it returns to the waiting state from a running state.

Q)What is mutual exclusion? How can you take care of mutual exclusion using Java threads?
A)Mutual exclusion is a phenomenon where no two processes can access critical regions of memory at the same time. Using Java multithreading we can arrive at mutual exclusion. For mutual exclusion, you can simply use the synchronized keyword and explicitly or implicitly provide an Object, any Object, to synchronize on. The synchronized keyword can be applied to a class, to a method, or to a block of code. There are several methods in Java used for communicating mutually exclusive threads such as wait( ), notify( ), or notifyAll( ). For example, the notifyAll( ) method wakes up all threads that are in the wait list of an object.

Q) What is the difference between preemptive scheduling and time slicing?
A) Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then re-enters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.

Q) run(): After a thread is started, via its start() method of the Thread class, the JVM invokes the thread's run() method when the thread is initially executed.

Q) wait(), notify(), and notifyAll() methods : Methods are used to provide an efficient way for thread inter-communication.

Q) Thread & States ?
A) A thread is an independent path of execution in a system. The high-level thread states are ready, running, waiting and dead.

Q) What are synchronized methods and synchronized statements?

Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method's object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement.

Q) What happens when a thread cannot acquire a lock on an object?
A) Yes. You can lock an object by putting it in a "synchronized" block. The locked object is inaccessible to any thread other than the one that explicitly claimed it. If a thread attempts to execute a synchronized method or synchronized statement and is unable to acquire an object's lock, it enters the waiting state until the lock becomes available.

Q) What is the difference between process and thread?
A) A thread is a separate path of execution in a program. A Process is a program in execution.

Q) Why would you use a synchronized block vs. synchronized method?
A) Synchronized blocks place locks for shorter periods than synchronized methods.

Q) What is an object's lock and which objects have locks?
A) An object's lock is a mechanism that is used by multiple threads to obtain synchronized access to the object. A thread may execute a synchronized method of an object only after it has acquired the object's lock. All objects and classes have locks. A class's lock is acquired on the class's Class object.

Q)Let`s say you have thread T1, T2 and T3, how will you ensure that thread T2 run after T1 and thread T3 run after T2?
(A) It can be achieved using join method of Thread class.

Q)How to know the thread priority?
A) isAlive() —it returns true when Thread is running
A) join() these two methods are used to know thread priority.

Q) What is a deadlock?
Deadlock is a situation where two or more threads are blocked forever, waiting for each other. This may occur when two threads, each having a lock on one resource, attempt to acquire a lock on the other's resource. Each thread would wait indefinitely for the other to release the lock, unless one of the user processes is terminated. Deadlock ocurred on Two threads call Thread.join() on each other and Two threads use nested synchronized blocks to lock two objects and the blocks lock the same objects in different order.

Java Threading Programming Interview Questions 1


Q) Explain different way of using thread?
A) A Java thread could be implemented by using Runnable interface or by extending the Thread class. The Runnable is can be used for Thread because we can inherit one more class.

Q) What are the two types of multitasking?
A) process-based and Thread-based

Q) Thread Example by extending Thread Class
A) public class ThreadExample extends Thread{

public void run(){
System.out.println("Thread Starting");
for(int i=0;i<9;i++)
System.out.println(i);
}

public static void main(String args[]){
new ThreadExample().start();

}

}

Q) Thread Example by Implmenting runnable interface?
public class ThreadExample implements Runnable{

public void run(){
System.out.println("Thread Starting");
for(int i=0;i<9;i++)
System.out.println(i);
}

public static void main(String args[]){
Thread t1=new Thread(new ThreadExample());
t1.start();
}

}

Q) What is synchronization in respect to multi-threading in Java?
A) Synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one Java thread to modify a shared variable while another thread is in the process of using or updating same shared variable. This usually leads to significant errors.
Example
=======
public class ThreadExample implements Runnable{

public  synchronized void run(){
System.out.println("Thread Starting");

{
for(int i=0;i<9;i++)
System.out.print(i);
}
}

public static void main(String args[]){
Thread t1=new Thread(new ThreadExample());
t1.start();

Thread t2= new Thread(new ThreadExample());
t2.start();

Thread t3= new Thread(new ThreadExample());
t3.start();

}

}

Q)Difference  Thread.start() & Thread.run() method?
A) Thread.start() method (native method) of Thread class actually does the job of running the Thread.run() method in a thread. If we directly call Thread.run() method it will executed in same thread, so does not solve the purpose of creating a new thread.

Q) Why do we need run() & start() method both. Can we achieve it with only run method?
A) We need run() & start() method both because JVM needs to create a separate thread which can not be differentiated from a normal method call. So this job is done by start method native implementation which has to be explicitly called. Another advantage of having these two methods is we can have any object run as a thread if it implements Runnable interface. This is to avoid Java’s multiple inheritance problems which will make it difficult to inherit another class with Thread.


Q) Can you declare a static method as synchronized?
A) Yes, we can declare static method as synchronized. But the calling thread should acquire lock on the class that owns the method.


Q) & A) Constrcutor in Thread Class : Thread(Runnable threadob,String threadName)

Q) & A) Metods available in the Runnable Interface? run()

Q) & A) What is the data type for the method isAlive() and this method is available in which class? : boolean, Thread

Q) What are all the methods available in the Thread class?
A)isAlive()
join()
resume()
suspend()
stop()
start()
sleep()
destroy()

Q) What are all the methods used for Inter Thread communication and what is the class in which these methods are defined?
A)wait(),notify() & notifyall() and Object class

Q) What is the mechanisam defind by java for the Resources to be used by only one Thread at a time? : Synchronisation

Q) Thread Priority values
A) MAX-10, MIN-1 NORMAL-5 and Method is setPriority()

Q)Default thread at the time of starting the program?: Main Method

Q) Thread States: new,runnable,blocked & dead

Q) The suspend()method is used to teriminate a thread? : False

Q) The run() method should necessary exists in clases created as subclass of thread? : True

Q) Which method waits for the thread to die ? : join() method

--wait(),notify(),notifyall() are defined as final & can be called only from with in a synchronized method
  wait(),notify(),notifyall() the wait() method only throws IOException

Q)Garbage collector thread belongs to which priority? : low-priority

Q) What is meant by daemon thread? In java runtime, what is it's role?
A) Daemon thread is a low priority thread which runs intermittently in the background doing the garbage collection operation for the java runtime system.

Wednesday, August 22, 2012

Thread Example in Java


public class ThreadExample extends Thread{

public synchronized  void run(){
for(int i=0;i<11;i++)
System.out.print(i);
System.out.println(" ");
}
public static void main(String args[]){
Thread t1=new ThreadExample();
Thread t2=new ThreadExample();
Thread t3=new ThreadExample();

t1.start();
t2.start();
t3.start();

t1.setPriority(MAX_PRIORITY);
System.out.println("Thread 1 Priority"+t1.getPriority());

System.out.println("Thread 1 Group"+t1.getThreadGroup());

System.out.println("State of Thread2"+t2.getState());

}
}

Monday, August 20, 2012

Thread Interview Questions in Java


1) What is the difference between checked and unchecked exception handling in Java? What are the disadvantages of checked exception handling?
Ans: Checked exceptions are the one for which there is a check by the compiler that these exceptions have to be caught or specified with throws keyword. These kind of exceptions occur because of conditions which are out of control of the application like Network error, File Access Denied etc.
Unchecked exceptions are the one which arise because of logic written by the developer. e.g. Trying to access an array element which doesn’t exist.

Multiple exceptions in single catch block
catch(FileNotFoundExcpetion fne | Exception e){}

What are the differences between NoClassDefFoundError and ClassNotFoundException?
Ans: NoClassDefFoundError occurs when a class was found during compilation but could not be located in the classpath while executing the program.
For example: class A invokes method from class B and both compile fine but before executing the program, an ANT script deleted B.class by mistake. Now on executing the program NoClassDefFoundError is thrown.
ClassNotFoundException occurs when a class is not found while dynamically loading a class using the class loaders.
For example: The database driver is not found when trying to load the driver using Class.forName() method.

What is the purpose of throw keyword? What happens if we write “throw null;” statement in a Java program?
Ans: ”throw” keyword is used to re-throw an exception which has been caught in a catch block. The syntax is “throw e;” where e is the reference to the exception being caught. The exception is re-thrown to the client.
This keyword is useful when some part of the exception is to be handled by the caller of the method in which throw keyword is used.
The use of “throw null;” statement causes NullPointerException to be thrown.
The answers are brief. Do post your comments if you think I have missed anything or discuss any other exception handling question.