Interview Preparation: Concurrency
12 BRILLIANT ANSWERS TO SOFTWARE ENGINEERING INTERVIEW QUESTIONS!
Q 1. What is the difference between process and thread?
Any program is under process. Process control block
regulates any function.
Process control block contains information about processes
like a priority, process ID, state, CPU usage, register usage, and other
information.
The thread is part of a process.
This can refer to several threads inside the process as well
as multiple processes with duplicate threads.
Q 3. How do you create a thread in Java and run it?
Steps for Creating a Thread
·
Create a class that extends a thread class or
implements runnable to the interface. (both are found in Java.lang package).
·
Write or provide the body of the Run () method.
·
Create an object of that class that contains the
run () method.
·
Create a thread and attach it to the object of a
class containing a Run () method.
·
Run the thread (for this purpose) use the Start
() method of the Thread class.
·
Example to show (how to run and create a
thread).
Thread t= new Thread(); //here Thread is the
class and t is the object of thread class.
or
Thread t=new (object,”thread_name”); //here we pass
object and thread name.
Program to show the creation of a thread
public class sample
{
public static void main(String[]args)
{
System.out.println(“current thread”);
Thread t= Thread.currentThread();
System.out.println(“current Thread=”+t);
System.out.println(“name of the current
Thread=”+t.getName());
}
}
Q 4. What are the different states of a
thread and when do the state transitions
occur?
A thread state. A thread can
be in one of the following states:
- NEW
A thread that has not yet started is in this state. - RUNNABLE
A thread executing in the Java virtual machine is in this state. - BLOCKED
A thread that is blocked waiting for a monitor lock is in this state. - WAITING
A thread that is waiting indefinitely for another thread to perform a particular action is in this state. - TIMED_WAITING
A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state. - TERMINATED
A thread that has existed is in this state.
Q 5. What is a daemon thread and what are
its use cases?
Daemon threads are low priority threads the main work of
this thread to provide services to the user thread it use to serve user threads
and are only needed while user threads are running daemon threads are useful for
background supporting task such as garbage collection , releasing memory of
unused objects and remove unwanted entries from the cache
Methods
Void set Daemon(Boolean status) – this method is use to mark
a current thread as daemon thread or user thread
Boolean is Daemon() _ this is used to check that current is
daemon it return true if thread is daemon otherwise return false
Q 5. How do you create a daemon thread?
Create Daemon Thread in Java Example
In the following example, we will create a daemon thread in Java that demonstrates the behavior of daemon
threads. The main thread creates a daemon thread that displays a message every
half second. The main thread then sleeps for five seconds. While the daemon
thread is still executing, the program ends because the only currently executing
threads are daemon threads.
// JavaDaemonTest.java
2
3
public class JavaDaemonTest {
4
5
public static void main(String args[]) {
6
// Create runnable action for daemon
7
Runnable daemonRunner
= new
Runnable() {
8
public void run() {
9
// Repeat forever
10
while (true) {
11
System.out.println("I'm a Daemon.");
12
// Sleep
for half a second
13
try {
14
Thread.sleep(500);
15
16
} catch (InterruptedException ignored)
{
17
18
}
19
}
20
}
21
};
22
// Create and start daemon thread
23
Thread daemonThread
= new
Thread(daemonRunner);
24
daemonThread.setDaemon(true);
25
daemonThread.start();
26
// Sleep for five seconds
27
try {
28
Thread.sleep(5000);
29
30
} catch (InterruptedException ignored) {
31
}
32
System.out.println("Done.");
33
}
34
}
Q
7. What is Java Memory
Model (JMM)?
A memory (consistency) model that defines
legal behaviors in a multi-threaded Java code with respect to the
shared memory. The JMM serves as a contract between programmers
and the JVM. The Java memory model describes how threads in the Java
programming language interact through memory. Together with the description of
single-threaded execution of code, the memory model provides the semantics of
the Java programming language.
Q 8. What are deadlock, livelock, and
starvation? What causes these
conditions?
8.1 What Is a Deadlock?
A deadlock is a situation in which processes block each other
due to resource acquisition and none of the processes makes any progress as
they wait for the resource held by the other process.
Conditions for Deadlock
·
Mutual Exclusion: At least one
resource needs to be held by a process in a non-sharable mode. Any other
process requesting that resource needs to wait.
·
Hold and Wait: A process must hold one resource and requests
additional resources that are currently held by other processes.
·
No Preemption: A resource can’t be forcefully released from
a process. A process can only release a resource voluntarily once it is deemed
to be released.
8.2 What Is Livelock?
In the
case of a livelock, the states of the processes involved in a live lock
scenario constantly change. On the other hand, the processes still depend
on each other and can never finish their tasks.
8.3 What Is Starvation?
Starvation is an outcome of a process that is unable to gain
regular access to the shared resources it requires to complete a task and thus,
unable to make any progress.
What Causes Starvation?
Starvation can occur due to deadlock, livelock, or caused by
another process.
As we have seen in the event of a deadlock or a live lock a
process competes with another process to acquire the desired resource to
complete its task. However, due to the deadlock or livelock scenario, it failed
to acquire the resource and generally starved for the resource.
REFERENCE FOR THE ABOVE: https://www.baeldung.com/cs/deadlock-livelock-starvation#:~:text=If%20a%20process%20requests%20for,deadlock%2C%20livelock%2C%20and%20starvation. FOR BETTER UNDRSTADING PLEASE VISIT THE
WEBSSITE
Q 9. What happens if you don’t override the thread class
run() method?
If we don’t override run() method, compiler will not flash
any error and it will execute run() method of Thread class that has empty
implemented, So, there will be no output for this thread.
Below example will not provide any output
Q 10. What is atomic operation and what
are atomic classes in the Java
Concurrency API?
Atomic operation in java is an operation during which a
processor can concurrently or simultaneously read and write in the same
location in the same bus operation. This operation is used to prevent any
other processes to read or write in the middle until the operation is completed.
Java provides atomic
classes such as AtomicInteger, AtomicLong, Atomic
Boolean and Atomic Reference. Objects of these classes
represent the atomic variable of int, long, Boolean, and object
reference respectively.
REFRENCE FOR THE ABOVE: https://www.geeksforgeeks.org/atomic-variables-in-java-with-examples/
Q 11. What are Executor and
ExecutorService and what are the differences
between them?
Executor vs ExecutorService vs Executors
in Java
a) One of the key differences
between Executor and ExecutorService interface is that the
former is a parent interface
while ExecutorService extends Executor I mean, it's a
sub-interface of Executor.
b) Another important difference
between ExecutorService and Executor is that Executor
defines execute() method which accepts an object of
the Runnable interface, while submit() method can
accept objects of both Runnable and Callable interfaces.
c) The third difference
between Executor and ExecutorService interface is that
the execute() method doesn't return any result, its return type is
void but the submit() method returns the result
of computation via a Future object. This is also the key difference
between submit() and execute() method, which is one of the
frequently asked Java concurrency interview questions.
d) The fourth difference
between ExecutorService and Executor interface is that
apart from allowing a client to submit a task, ExecutorService also provides
methods to control the thread pool e.g. terminate the thread pool by calling the shutDown() method.
You should also read "Java Concurrency in Practice" to
learn more about the graceful shutdown of a thread-pool and how to handle
pending tasks.
e) Executors class provides factory methods to
create different kinds of thread pools
e.g. newSingleThreadExecutor() creates a thread pool of just one
thread, newFixedThreadPool(int numOfThreads) creates a thread pool of
a fixed number of threads, and newCachedThreadPool() creates new
threads when needed but reuse the existing threads if they are available.
Q 12. What are Concurrent Collection Classes?
Java Concurrent Collection Classes
- BlockingQueue – an interface
that is at the base of all Queue based concurrent collections.
While adding an element to a BlockingQueue, if there is no space it
can wait till it becomes available and when retrieving, it will wait till
an element is available if it is empty.
- ArrayBlockingQueue – a blocking
queue class based on bounded Java Array. Once instantiated, cannot be
resized.
·
SynchronousQueue – a blocking queue class with
capacity of zero always.
·
PriorityBlockingQueue – a priority queue-based blocking
queue. It is an unbounded concurrent collection.
·
LinkedBlockingQueue – an optionally bounded Java
concurrent collection. Orders elements based on FIFO order.
·
DelayQueue –
a queue where only delay expired elements can be taken out. Its an unbounded
concurrent collection.
·
BlockingDeque – an interface that extends BlockingQueue and adds the operations of Deque.
·
LinkedBlockingDeque – an implementation class
of BlockingDequeue.
·
TransferQueue – a Java concurrent collection
interface that



Comments
Post a Comment