Part 1
Interview questions on multithreading in java for experienced covered in this post:
What is a Thread and what is the
process?
- Thread: Thread is a single independent path of execution of the
program.
- Process: Process is a program in execution.
What are the advantages of
Multithreading?
- Multithreading in java is a process of executing multiple threads
simultaneously.
- Advantages of multithreading.
1. Perform multiple operations at a time.
2. The Performance will be improved if multiple threads are executing the
shared resources.
3. It saves time if multiple threads are executing at a
time.
What are the multiple ways to create
a thread? Which one is recommendable?
- There are two ways to create a thread.
1. Thread Class: You can extend the Thread class and create a
thread.
2. Runnable Interface: You can implement a Runnable interface and
create a thread.
- Second one is recommendable which is implementing a Runnable interface
because if you implement a runnable interface then you will have an option
to extends one more class.
- Please refer to the below example.
1. Extending Thread Class.
package
simplifiedjava.crackedInterview; public class CreatingThreadUsingThreadClassDemo extends Thread{ Thread t = new Thread();
public static void
main(String[] args) {
// TODO
Auto-generated method stub
} } 2. Implementing Runnable Interface.
package
simplifiedjava.crackedInterview; public class CreatingThreadUsingThreadClassDemo implements Runnable{ Thread t = new Thread();
public static void
main(String[] args) {
// TODO
Auto-generated method stub }
@Override
public void
run() { // TODO Auto-generated method stub
}
} |
Explain the thread life cycle?
- There are five states of the thread life cycle.
1. New: When a thread gets newly created.
2. Runnable: When you invoke the start() method then the thread
enters into a runnable state.
3. Running: When the scheduler allocates time slots in CPU then that
thread enters into a running state.
4. Blocked: When you invoke the wait() method then that thread enters
into a waiting state.
5. Terminate: after execution of the thread enters into a dead
state.
What is the daemon thread?
- Daemon thread is a very lightweight thread that is running in the
background.
- You may invoke the setDaemon() method to convert normal thread to daemon
thread.
- isDaemon() method can be used to check whether the particular thread is
daemon or not.
- When all non-daemon thread completes then the daemon thread terminates
automatically.
- For example, the Garbage Collector thread is a daemon thread.
What do you mean by thread
priority?
- Thread priorities are nothing but a number between 1 to
10.
- Each thread has some priority.
- Default priority is 5.
- Scheduler schedules the thread according to their
priority.
- There are 3 constants defined in thread priorities.
1. MIN_PRIORITY
2. NORM_PRIORITY
3. MAX_PRIORITY
Why wait(), notify() and notifyAll()
methods are in Object class even these methods are used in
multithreading?
- Basically, wait(), notify(), notifyAll() methods are using
by threads to communicate with each other. But these methods belong to
java.lang.Object class.
- Every Object has its lock or Monitor.
- One thread can hold only one lock or monitor at a time
while executing a synchronized block or method.
- If wait(), notify() and notifyAll() methods are put in
Thread class instead of Object class then we would have faced Thread
communication problem, Synchronization on object won’t be possible. If
each thread will have a monitor we won’t have any way of achieving
synchronization.
What is the reason to override the
run method in multithreading? What will happen if I don't override the
run method?
- Thread class has run() which doesn’t have any
implementation so you need to override the run() method and implement your
logic into it.
- Compiler won’t flash any error but nothing will be printed
or executed.
How to achieve Thread safety in
java?
- Thread safety means multiple threads sharing the same
resource without producing an unpredictable result.
- We can achieve thread-safety in multiple ways. Please refer
to the below 8 options.
1. Synchronized Methods.
2. Synchronized Blocks.
3. Synchronized Collection. (Using Collections Utility
Class).
4. Concurrent Collection.
5. Immutable Implementation.
6. Thread-Local Field.
7. Volatile Field.
8. Stateless Implementation.
Explanation in details.
1.
Synchronized Methods:
Ø The method can be declared with a
synchronized
keyword.
Ø Once you declared the method with a
synchronized
keyword then only one thread can execute shared resources at a time. Other
threads will be blocked until the first thread finishes its execution.
Ø synchronized
method depends on either “Intrinsic Lock” or “Monitor Lock”.
Ø When the thread calls the
synchronized
method, it acquires the intrinsic lock.
Ø The Monitor is just a reference to the role that the lock
performs on the associated objects.
Ø Please refer to the below example.
package simplifiedjava.crackedInterview; public class SynchronizedMethodDemo {
int counter
= 0;
public synchronized void
getCounter() {
counter
=+ 1; // Similar to counter = counter +1;
System.out.println("Counter is "+ counter); }
public static void
main(String[] args) {
new
SynchronizedMethodDemo().getCounter();
}
} |
2.
Synchronized Block:
Ø A
synchronized
block can be called a statement block.
Ø Method synchronization is highly expensive so to avoid this
situation we can perform synchronization at the statement level which is
less expensive from a performance perspective.
Ø A
synchronized
block generally declares inside a method.
Ø Please refer to the below example.
package simplifiedjava.crackedInterview;
import
java.util.ArrayList;
import
java.util.Arrays;
import
java.util.Collection; import java.util.Collections; public class SynchronizedBlockDemo {
int counter
= 0;
public void
getCounter() {
synchronized(this) {
counter
=+ 1; // Similar to counter = counter +1;
}
System.out.println("Counter is "+ counter); }
public static void
main(String[] args) {
new
SynchronizedMethodDemo().getCounter();
}
} |
3.
Synchronized Collection:
Ø We can create a thread-safe collection by using utility
methods of the Collections utility class.
Ø Once you create the thread-safe collection object then only
one thread can execute at a time. While other threads will be blocked
until the collection object is unblocked by the first thread.
Ø Please refer to the below example.
package simplifiedjava.crackedInterview;
import
java.util.Arrays;
import
java.util.Collections; import java.util.List; public class SynchronizedCollectionDemo {
public static void
main(String[] args) {
Thread t1
= new
Thread(new
MyClass1());
Thread t2
= new
Thread(new
MyClass2());
t1.start();
t2.start();
} } class MyClass1 implements Runnable{
@Override
public void
run()
{
List<Integer> list1
= Arrays.asList(10,20,30,40,50);
List<Integer> synchronizedList1
= Collections.synchronizedList(list1);
for(Integer i
: list1) {
System.out.println(i);
}
} } class MyClass2 implements Runnable{
@Override
public void
run() {
List<Integer> list2
= Arrays.asList(60,70,80,90,100);
List<Integer> synchronizedList2
= Collections.synchronizedList(list2);
for(Integer i
: list2) {
System.out.println(i);
}
}
} |
4.
Concurrent Collection:
Ø Java provides java.util.concurrent package for thread
safety.
Ø Java.util.concurrent package has some thread safe classes
like ConcurrentHashMap, CopyOnWriteArrayList, CopyOnWriteArraySet.
Ø Please refer to the below example.
package simplifiedjava.crackedInterview;
import
java.util.Map; import java.util.concurrent.ConcurrentHashMap; public class ConcurrentCollectionDemo {
public static void
main(String[] args) {
Map<String,Integer> concurrentMap
= new
ConcurrentHashMap<>();
concurrentMap.put("one", 1);
concurrentMap.put("two", 2);
concurrentMap.put("three", 3);
}
} |
5.
Immutable Implementation:
Ø Immutable means its internal states can’t be changed once
it is created.
Ø If we need to share the state between different threads, we
can create thread-safe classes by making them immutable classes.
Ø If the state will be fixed forever then immutable objects
can be used thread-safely.
Ø Please refer to the below example.
package simplifiedjava.crackedInterview; public final class ImmutableClassDemo { private final String empCode="E001";
public
String getEmpCode() {
return empCode;
}
} |
6.
Thread-Local Field:
Ø We can easily create classes whose fields are thread-local
by simply defining private fields in the Thread class.
Ø We can create thread-safe classes that don’t share states
between threads by making their fields thread-local.
Ø Please refer to the below example.
package simplifiedjava.crackedInterview;
import
java.util.Arrays; import java.util.List; public class ThreadLocalDemo1 extends Thread { private final List<Integer> numList = Arrays.asList(10,20,30,40,50);
@Override
public void
run() {
for(int n
: numList) {
System.out.println(n);
}
} } package simplifiedjava.crackedInterview;
import
java.util.Arrays; import java.util.List; public class ThreadLocalDemo2 extends Thread{ private final List<String> wordList = Arrays.asList("Hi","Hello","GM","GA","GN");
@Override
public void
run() {
for(String str
: wordList) {
System.out.println(str);
}
}
} |
7.
Volatile Field:
Ø If you declare a variable as volatile, JVM will store those
variables on main memory.
Ø We can make sure every time JVM reads the value from the
main memory.
Ø Every time JVM writes the value it will write on the main
memory.
Ø Volatile keyword ensures that variable will be visible to
all thread and thread can read the value from main memory.
Ø Please refer to the below example.
package simplifiedjava.crackedInterview; public class ThreadLocalVariableDemo {
private volatile int empId; private String name; public static void main(String[] args) {
}
} |
8.
Stateless Implementation:
Ø Stateless implementation is the simplest way to achieve
thread safety.
Ø Stateless implementation is nothing but function
implementation which produces the same result every time. There is no
change to change the state by any thread.
Ø Please refer to the below example.
package simplifiedjava.crackedInterview; public class StateLessImplementationDemo { public static void main(String[] args) {
int i
= 10;
int square
= i
* i ;
System.out.println(square);
}
} |
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.
- 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