Multithreading interview questions

 Multithreading interview questions

 

What is multiprocessing? 

Executing multiple task simultaneously for that  operating system will create separate process
for each task.
What is a multithreading?
A multi threaded program utilizes the power of one single processor to appear to be doing more than one thing at a time,
multithreading means creating multiple thread in same process.

What is the main purpose of multithreading? 

Multithreading is the  best of utlizing cpu resources.

in multiprocessing comnication between two procees are difficult why because they

shared memory aloso different.in case of multithreading they share common memory location 

only so communication very easy.

A JVM runs in a single process and threads in a JVM share the heap belonging to that process. That is why several threads may access the same object. Threads share the heap and have their own stack space. This is how one thread’s invocation of a method and its local variables are kept thread safe from other threads.

Example:Servlets are better in performance than CGI because Servlet support multi-threading but CGI doesn’t.

What is daemon thread?
Daemon thread also like normal thread it also run in separate stack difference is
which will run background

Daemon threads will be terminated by the JVM when there are none of the other threads running, it includes main thread of execution as well.
example:grabage collector

we can convert normal thread to deamon thread using calling setDeamonThread(ture) on current thread;

How many ways we can create a thread?

we can create in two ways one is extending a Thread class another one is implementing Runnable interface.
best ways implementing runnable interface why because class can extends only one class if extend thread class
then that particular no chance for extends any other if you implement Runnbale interface we can extend any other class.

What is the use of threadscheduler? 

The main job of threadscheduler is it will push thread from Runnable to running state.

What is time slicing?
dividing CPU time to avillable threads.

How can we achieve thread safety in Java?


We can achive three ways
1.Using Synchronization
2.Using immutable
3.Wrapper classes
Synchronizing critical sections

Marking your code's critical sections as synchronized is the "normal" approach to making classes synchronized. It is also the only way to use wait() and notify() to get threads to cooperate towards achieving some common goal. So the guideline concerning Approach 1 is simply:

Unless special circumstances make it appropriate to use an immutable or wrapper object, use Approach 1 to make your class thread-safe: Make sure the appropriate instance variables are private and mark the critical sections as synchronized.
Using immutable objects

Achieving thread safety by making objects immutable (Approach 2) works well when objects are small and represent values of a simple abstract data type. The Java API includes several examples of immutable objects, including String and the primitive type wrappers such as Integer, Long, Float, Boolean, Character, and so on.

It's worth noting that instances of the AWT's Color class are immutable. Likewise, the immutable approach may make sense for this article's RGBColor class, which is similar in functionality to the AWT's Color class, because RGBColor objects are small (they contain only 3 ints) and conceptually represent values of a simple abstract data type.

MORE LIKE THIS
HOW-TO
Using threads with collections, Part 2
HOW-TO
Object finalization and cleanup
HOW-TO
My ENIGMAtic Java Ring
Another benefit of immutable objects is that you can pass references to them to methods without worrying that the method will change the object's state. In addition, if the overhead of immutability (excessive creation of short-lived objects) may at times be too inefficient, you can also define a mutable companion class that can be used when the immutable version isn't appropriate. An example of this design approach in the Java API is the StringBuffer class, which serves as a mutable companion to the immutable String class. Note that the StringBuffer class is also thread-safe, but it uses the "normal" approach: its instance variables are private and its critical sections are synchronized.

Using wrapper objects

The wrapper object approach to thread safety (Approach 3) makes the most sense when you want to give clients a choice between a version of a class that is thread-safe and one that isn't. This approach also makes sense when you're a client of someone else's class that isn't thread-safe, but you need to use the class in a multithreaded environment. Once you define your own thread-safe wrapper for the class, you can safely use the class in a multithreaded environment by going through your wrapper.

A good example of this approach from the Java API comes from the 1.2 collections library. The 1.2 collections library defines a hierarchy that includes classes that represent many kinds of collections -- none of which are thread-safe. But class Collection includes several class methods that will enclose a regular collection object in a thread-safe wrapper, so you can safely use the object in a multithreaded context. This design gives users of the collections library a choice of using a collections object that is thread-safe and one that isn't.





What is ThreadLocal?

Thread Local can be considered as a scope of access, like a request scope or session scope. It's a thread scope.
What is Thread Pool? How can we create Thread Pool in Java?

A thread pool manages the pool of worker threads, it contains a queue that keeps tasks waiting to get executed.

A thread pool manages the collection of Runnable threads and worker threads execute Runnable from the queue.

java.util.concurrent.Executors provide implementation of java.util.concurrent.Executor interface to create the thread pool in java.


Example:

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

 public class ThreadPoolExample {

    public static void main(String args[]) {
       ExecutorService service = Executors.newFixedThreadPool(10);
       for (int i =0; i<100; i++){
           service.submit(new Task(i));
       }
    }
 
}

final class Task implements Runnable{
    private int taskId;
 
    public Task(int id){
        this.taskId = id;
    }
 
    @Override
    public void run() {
        System.out.println("Task ID : " + this.taskId +" performed by "
                           + Thread.currentThread().getName());
    }
 
}

Output:

Task ID : 1 performed by pool-1-thread-2
Task ID : 0 performed by pool-1-thread-1
Task ID : 11 performed by pool-1-thread-1
Task ID : 2 performed by pool-1-thread-3
Task ID : 13 performed by pool-1-thread-3
Task ID : 3 performed by pool-1-thread-4
Task ID : 15 performed by pool-1-thread-4
Task ID : 16 performed by pool-1-thread-4
Task ID : 17 performed by pool-1-thread-4
Task ID : 18 performed by pool-1-thread-4


What is use of synchronized keyword?

using synchronized  key word we can provide code thread safety (if its thread security is required then only use synchronization other wise it decreases the performance)
we can use synchronized keyword either method or constructor.


What is a volatile keyword?

In general each thread has its own copy of variable, such that one thread is not concerned with the value of same variable in the other thread.
But sometime this may not be the case. Consider a scenario in which the count variable is holding the number of times a method is called for a
given class irrespective of any thread calling, in this case irrespective of thread access the count has to be increased so the count variable
is declared as volatile. The copy of volatile variable is stored in the main memory, so every time a thread access the variable even for
 reading purpose the local copy is updated each time from the main memory. The volatile variable also have performance issues.


Difference between green thread and native thread in Java?


Green threads" refers to a model in which the Java virtual machine itself creates, manages, and context switches all Java threads within one operating system process. No operating system threads library is used.

Native threads" refers to a in which the Java virtual machine creates and manages Java threads using the operating system threads library - named libthread on UnixWare - and each Java thread is mapped to one threads library thread.




What is context switching in multi-threading?


 
Difference between deadlock and livelock, deadlock and starvation?

live locks occurs when all threads are blocked.

starvation occurs when thread unable to access shared resource.

A deadlock occurs when thread A holds lock L and tries to acquire lock M, while thread B holds lock M and tries to acquire lock L. Thus both threads are waiting for a lock held by the other, and can not progress to release their own lock. This causes both threads to wait forever. The situation may be involving more than 2 threads as well.

 
What thread-scheduling algorithm is used in Java?

  
 
Why Executor framework is better than creating and managing thread by application ?

Using Executor framework we can create pool of threads so that we can ruse the threads.

wit out recreating.

How many ways we can stop current thread execution?

using sleep(),wait(),joing we can push thread from running to ruunable state.
and yield() aloso but its not sure first i will check based on priority.so theres is no gureenty using yield.

Why wait() and notify() methods are defined in the Object class, and not in the Thread class?


The wait (), notify () and notify all () methods are object-specific. The wait() method suspends the current thread of execution, The notify()method tells the object to wake up the suspended threads that it is currently keeping track of. Since wait(), notify() and notifyAll() are object specific, they must be used within code that is synchronized on the object. The another reason to define these method in Object class is that, locks are made available on per Object basis.

Author

Written by Admin

Aliquam molestie ligula vitae nunc lobortis dictum varius tellus porttitor. Suspendisse vehicula diam a ligula malesuada a pellentesque turpis facilisis. Vestibulum a urna elit. Nulla bibendum dolor suscipit tortor euismod eu laoreet odio facilisis.

0 comments: