Part 2
Interview questions on multithreading in java for experienced covered in this post:
What is deadlock? How to avoid a
situation of dead lock?
- Deadlocks are a set of blocked processes, each holding a resource and waiting to acquire a resource held by another process.
-
We can avoid the deadlock: Do not grant a resource request if
this allocation has the potential to lead to deadlock.
What happen if you don't override run()
method on Thread class?
-
If you don’t override the run() method it will execute the
run method of the Thread class that has empty implementation. The compiler
won’t throw any exception.
-
It is recommended to override the run() method and provide
your implementation.
What is the difference between sleep()
and wait() in java?
|
Sleep() |
Wait() |
1. |
The sleep () method can be used to pause the process for some time
or the time we want to. |
Wait() is a method that can be used to put the thread in a waiting
state. |
2. |
Sleep() method never release the lock while sleeping the
thread. |
Wait() method can release the lock while a thread is waiting. |
3. |
Syntax:
synchronized(LOCK) {
Thread.sleep(1000);
} |
Syntax:
synchronized(LOCK) {
LOCK.wait();
} |
There are 3 Thread Thread1, Thread2 and
Thread3 how would you ensure the thread execution for Thread1, Thread2
and then Thread3?
-
If a thread wants to wait until completing some other thread
then we should go for the join(); method.
-
In above example, Thread1.join(Thread2) and
Thread2.join(Thread3) in the above case Thread3 will execute first and then
thread2 and then thread1.
What is the difference between Runnable
and Callable?
|
Runnable |
Callable |
1. |
The runnable interface has the run() method which needs to override
an implemented class. |
The callable interface has a call() method which needs to override
an implemented class. |
2. |
Run() method cannot return a value. |
Call() method can return a value. |
3. |
Runnable cannot throw checked Exception. |
Callable can throw checked exception. |
4. |
Runnable cannot be used in Executor Framework. |
Callable can use in Executor Framework. |
5. |
public interface Runnable {
void run();
} |
public interface
Callable<V> {
V
call() throws Exception;
} |
What is static synchronization?
-
Static synchronized method will acquire a lock of the class
instead of an object.
-
Static belongs to the class, not the object so Thread
acquires a lock from class.
-
Suppose there are multiple static synchronized methods (m1,
m2, m3, m4) in a class, and suppose one thread is accessing m1, then no
other thread at the same time can access any other static synchronized
methods.
What is the difference between
Synchronous and Asynchronous programming?
-
Implies that tasks will be executed one by one. The next task
is started only after the current task is finished. Task3 is not started
until task2 is finished.
-
Implies that task returns control immediately with a promise
to execute a code and notify about the result later(e.g. callback, feature).
Task 3 is executed even if Task 2 is not finished.
-
Please refer to the Real-Time Example.
-
Synchronous: You
are in a queue to get a movie ticket. You cannot get one until everybody in
front of you gets one, and the same applies to the people queued behind
you.
-
Asynchronous:
You are in a restaurant with many other people. You order your food. Other
people can also order their food, they don't have to wait for your food to
be cooked and served to you before they can order. In the kitchen,
restaurant workers are continuously cooking, serving, and taking orders.
People will get their food served as soon as it is cooked.
What is the difference between submit()
and execute() in thread pool?
|
Execute() |
Submit() |
1. |
Return type of execute() method is void. |
Return type of submit() is Future. |
2. |
execute() method is declared in Executor Interface. |
submit() method is declared in ExecutorService interface. |
3. |
This method accepts only Runnable Task. |
This method accepts Runnable as well as Callable tasks. |
-
Please refer below examples of each interface.
package
simplifiedjava.crackedInterview;
import
java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class ThreadExecutorServiceUsingRunnableDemo { public static void main(String[] args) {
ExecutorService executorService
= xecutors.newSingleThreadExecutor(); executorService.execute(new Runnable() {
@Override
public
void
run() {
System.out.println("Executor Service Executed with Runnable...");
for(int
i=0; i<10; i++) {
System.out.println("Child Thread...");
}
}
});
executorService.shutdown();
}
} Using Callable Interface. package simplifiedjava.crackedInterview;
import
java.util.concurrent.Callable;
import
java.util.concurrent.ExecutionException;
import
java.util.concurrent.ExecutorService;
import
java.util.concurrent.Executors; import java.util.concurrent.Future; public class ThreadExecutorServiceUsingCallableDemo { public static void main(String[] args) {
ExecutorService executorService
= Executors.newFixedThreadPool(1); Future obj = executorService.submit(new Callable() {
@Override
public
Object call() throws
Exception {
//System.out.println("Executor Service Executed with
Callable...");
return
"Executor Service Executed with Callable...";
}
});
try
{
System.out.println(obj.get());
} catch
(InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
} |
What is the difference between
CyclicBarrier and CountDownLatch?
-
CyclicBarrier and Countdown latch techniques can be used in a
multi-threaded environment to manage resources for multiple threads.
-
The difference is explained below.
|
CountDownLatch |
CyclicBarrier |
1. |
You cannot reuse the instance of CountDownLatch once the count
reaches zero and the latch is open. CountDownLatch works like a
count-down timer. |
CyclicBarrier can be reused by resetting the barrier once the
barrier is broken. |
2. |
CountDownLatch doesn’t have any kind of Constructor. |
CyclicBarrier has a constructor where Runnable instance can be
provided. |
3. |
CountDownLatch maintains the count of Tasks. |
CyclicBarrier maintains the count of Threads. |
4. |
The only current thread will throw InterruptedException. It will
not impact other threads. |
If one thread is interrupted while waiting then other threads will
throw BrokenBarrierException. |
What is race condition?
-
In a multithreaded environment when more than one thread
tries to access shared resources at the same time.
-
Please refer to the below real-life example to understand
race conditions.
- You are planning to go to a movie at 5 pm. You inquire about the availability of the tickets at 4 pm. The representative says that they are available. You relax and reach the ticket window 5 minutes before the show. I'm sure you can guess what happens: it's a full house. The problem here was in the duration between the check and the action. You inquired at 4 and acted at 5. In the meantime, someone else grabbed the tickets.
- Java interview questions and answers all MNC - Click here
- Basic core java interview questions and answers for freshers - Click here
- Core java interview questions for 3 years experience - Click here
- Core java interview questions and answers for 3-5 years exp - Click here
- Core java interview questions and Answers for 5 - 7 Years exp - Click here
- Basic Java Interview Questions and Answers - Click here
- Java interview questions and answers on oops - Click here
- Java interview questions and answers on Strings - Click here
- Java interview questions on exception handling - Click here
- Interview questions on multithreading in java for experienced - Click here
- Interview questions on serialization in java for experienced - Click here
- Interview questions on inner class in java for experienced - Click here
- Interview questions on Collections in java for experienced - Click here
Thank you techies for visiting this blog. I hope you enjoyed this blog and got more technical knowledge. I have tried to cover all types of questions and provided examples tested on eclipse as much as I can. Guys, please don’t just mug up the questions and answers. Try to clear your concepts with examples. Try to write a code on eclipse once you read the concepts. It will help you to memorize the concepts for a very long time. Simultaneously you will be prepared for interview programs as well. It will help you to survive in the IT sector for a long time. It may be easy to crack an interview but it's really tough to survive in the IT industry with inadequate knowledge and skills. I have collected all the questions from actual interviews attended by my friends, colleagues, college mate and classmate. I have covered frequently asked questions as well as challenging questions. I have included many programs to understand the concept thoroughly. I will try to explain the concept with the help of a real-time program in eclipse. You can share more questions which are not covered in this blog or post. Always welcome your suggestions and queries. I will definitely try to resolve it. Please comment your queries and new set of questions under the comment sections. I will create a new post for those questions.
My total experience is 10. Initially I had worked on some support
projects and then I moved to java projects. I had worked with many
multi-national companies like R-Systems, Tata Consultancy
Services, Cybage Softwares. Fortunately, TCS and Cybage
has given me an opportunity to take interviews for experienced
candidates. I have conducted more than 1000 interviews by now. Mock sessions will be conducted for minimal charges. I will guide you personally on how to crack interviews. All sessions will be online sessions only. My interview book will be provided free of cost if you enroll for personal training. Once you have done practice then I assured you will definitely crack almost all java interviews. I have published my book named with "All MNC Java Interview" which is available on amazon. You can go through it or you can directly contact to me if you are interested to read the book. I will give you special discount. I have covered near about 550 questions and answers with program tested on eclipse and necessary diagram. I have covered interview questions asked in all reputed MNC like TCS, Infosys, Capgemini, Tech Mahindra, Cognizant, City Bank, Barclays, Amdocs, Mindtree etc. My purpose behind this book is, help you to get a job in your dream company. I can understand this is a struggling period for job seekers and freshers. Everybody must have gone from this phase. so never give up. Keep upgrading yourself. I am sure you will get a job in your dream company. All the best!!! Please reach out to me for personal training for interview preparation.
You can reach out to me at mncjavainterview@gmail.com.
|
0 Comments