Part 5
Interview questions on multithreading in java for experienced covered in this post:
Which JVM Parameter is used to control stack size of thread?
-
Parameter: -Xssn
represents Stack Size;
- Every thread that is spawned during the execution of the program passed to
java has n as its C stack size.
What is the purpose of join() method?
-
Thread class provides the join() method which allows one
thread to wait until another thread completes its execution.
-
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 Synchronized and ReentrantLock?
|
Synchronized |
ReentrantLock |
1. |
Synchronized does not support fairness.
Synchronized never offer chance longest waiting thread. |
ReentrantLock support fairness. ReentrantLock has fairness property
which provides a lock to the longest waiting thread. |
2. |
Synchronized doesn’t provide any method like tryLock(). |
ReentrantLock provides the tryLock() method which acquires a lock
only if it's available or not held by any other thread. |
3. |
In a Synchronized mechanism, a thread can be blocked for an
infinite period. |
In ReentrantLock thread cannot be blocked for infinite time because
ReentrantLock provides a lockInterruptibly()method which can be used
to interrupt the thread.
|
Explain the busy spin technique?
-
Busy-waiting or spinning is a technique in which a process
repeatedly checks to see if a condition is true instead of calling the wait
or sleep method and releasing the CPU.
-
It is mainly useful in the multicore processor where the
condition is going to be true quite quickly i.e. in a millisecond or
microsecond.
-
The advantage of not releasing CPU is that all cached data
and instruction remain unaffected, which may be lost, had this thread is
suspended on one core and brought back to another thread.
What is Semaphore in Java? What are the types of Semaphore?
-
A Semaphore is a variable that can be used in the
Synchronization process.
-
A Semaphore controls access to shared resources through the
use of the Counter.
-
If the counter is zero then access will be denied.
-
If the counter is greater than zero then access will be
allowed.
-
A semaphore maintains the set of permits.
-
Types of Semaphores
are below.
1.
Binary semaphore:
A binary semaphore only takes only 0 and 1 as values and is used to
implement mutual exclusion as well as synchronize concurrent processes.
2.
Counting semaphore:
The value of a counting semaphore at any point indicates the maximum number
of processes that can enter the critical section at the same time.
3.
Bounded Semaphores:
Bounded semaphores can be used to set the upper bound limit. The Upper bound
value denotes how many signals it can store. Counting semaphores do not
contain any upper bound value so bounded semaphores can be used in a place
of counting semaphores.
4.
Timed Semaphores:
The timed semaphores allow a thread to run for a specified period of time.
After a particular time, the timer resets and releases all other
permits.
What is the difference between Deadlock and Starvation.
|
Deadlock |
Starvation |
1. |
Deadlock is a situation that occurs when one of the processes got
blocked. |
When all the low priority processes got blocked, while the high
priority processes execute then this situation is termed as
Starvation. |
2. |
There is starvation in every deadlock. |
Not every starvation needs to be a deadlock. |
3. |
Deadlock is an infinite process. |
Starvation is a long waiting but it is not an infinite
process. |
What is Thread Starvation?
-
Starvation is a situation where the thread is in a waiting
state for a very long time because it is not getting access to shared
resources because higher priority threads are coming.
-
When all the low priority processes got blocked, while the
high priority processes execute then this situation is termed
Starvation.
-
This happens when shared resources are made unavailable for
long periods by "greedy" threads.
What is the use of ExecutorService interface?
-
The Java ExecutorService is the interface that allows us to
execute tasks on threads asynchronously.
-
The Java ExecutorService interface is present in the
java.util.Concurrent package.
-
Executors execute() method takes a runnable object and
performs the task asynchronously.
-
After making the call of execute() method we call the
shutdown() method.
-
Please refer to the below example.
package simplifiedjava.crackedInterview;
import
java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class ExecutorServiceDemo {
public
static
void
main(String[] args) {
ExecutorService executorService
= Executors.newFixedThreadPool(10);
executorService.execute(new Runnable() {
@Override
public
void
run() {
System.out.println("ExecutorService");
}
});
executorService.shutdown();
}
}
Ouput: ExecutorService |
-
Executors submit() method takes a runnable object and returns a Future
object. Later on, this object can be used to check the status of Runnable
whether it has completed execution or not.
-
Please refer to the below example.
package simplifiedjava.crackedInterview;
import
java.util.concurrent.ExecutorService;
import
java.util.concurrent.Executors; import java.util.concurrent.Future; public class ExecutorServiceDemo {
public
static
void
main(String[] args) {
ExecutorService executorService
= Executors.newSingleThreadExecutor();
Future future = executorService.submit(new Runnable() {
@Override
public
void
run() { //System.out.println("ExecutorService"); }
});
System.out.println(future.isDone());
}
}
Output: false |
-
Executors invokeAny() method takes a collection of callable
objects. This method returns the future object of the callable objects which
are executed first successfully.
-
Please refer to the below example.
package simplifiedjava.crackedInterview;
import
java.util.HashSet;
import
java.util.Set;
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 ExecutorServiceDemo { public static void main(String[] args) throws InterruptedException, Exception {
// invoke method demo
ExecutorService executorService
= Executors.newSingleThreadExecutor();
Set<Callable<String>> callableSet
= new
HashSet<Callable<String>>();
callableSet.add(new
Callable<String>() {
public
String call() throws
Exception{
return
"Job 1";
} });
callableSet.add(new
Callable<String>() {
public
String call()throws
Exception{
return
"Job 2";
} });
callableSet.add(new
Callable<String>() {
public
String call()throws
Exception{
return
"Job 3";
} });
String executedJob
= executorService.invokeAny(callableSet);
System.out.println(executedJob);
executorService.shutdown();
}
}
Output: Job 2 |
-
The invokeAll() method takes in a Collection of Callable
objects having tasks and returns a list of Future objects containing the
result of all the tasks.
package simplifiedjava.crackedInterview;
import
java.util.HashSet;
import
java.util.List;
import
java.util.Set;
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 ExecutorServiceDemo { public static void main(String[] args) throws InterruptedException, Exception {
// invoke method demo
ExecutorService executorService
= Executors.newSingleThreadExecutor();
Set<Callable<String>> callableSet
= new
HashSet<Callable<String>>();
callableSet.add(new
Callable<String>() {
public
String call() throws
Exception{
return
"Job 1";
} });
callableSet.add(new
Callable<String>() {
public
String call()throws
Exception{
return
"Job 2";
} });
callableSet.add(new
Callable<String>() {
public
String call()throws
Exception{
return
"Job 3";
} }); List<Future<String>> executedJob = executorService.invokeAll(callableSet);
for(Future future: executedJob) {
System.out.println(future.get());
}
executorService.shutdown();
}
}
Output:
Job 2
Job 3 Job 1
|
What is the role of Future interface in Multithreading?
-
A Future represents the result of an asynchronous
computation.
-
Methods are provided to check if the computation is complete,
to wait for its completion, and to retrieve the result of the computation.
-
The result can only be retrieved using method get when the
computation has completed, blocking if necessary until it is ready.
-
Cancellation is performed by the cancel method.
-
Additional methods are provided to determine if the task was
completed normally or was cancelled.
-
Once a computation has been completed, the computation cannot
be cancelled.
- If you would like to use a Future for the sake of cancellability but not provide a usable result, you can declare types of the form Future<?> and return null as a result of the underlying task.
- 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