Java Multi-Threading Flashcards

1
Q

What is a thread?

A

The atomic part of program that can run with other similar atomic parts concurrently.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is the difference between a process and a thread in Java?

A

A process can be referred as program in execution whereas thread is smallest part of process.

A process has its own address space, different from other processes. Multiple threads share the same address space of the process to which they belong.

As a process can have multiple threads, it is heavy. Thread is lightweight.

Context switching and Inter-thread communication is faster in threads than in processes.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is multi-threaded programming/multi-threading?

A

Multi-threading is a programming model that allows multiple threads to exist within the context of one process. These threads can execute concurrently.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What are the benefits of multi-threaded programming?

A

In multi-threading, multiple threads execute concurrently, which improves the performance.

As multiple threads share the same heap space, it is beneficial to create multiple threads rather than multiple processes.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is the difference between user thread and daemon thread?

A

When a user creates a thread in a program, it is called user thread. A daemon thread is a low priority thread that runs in the background to perform tasks such as garbage collection.

JVM will shut down once all the user threads are finished working. Daemon threads do not prevent JVM shutdown. JVM will simply exit even if a daemon thread is working.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Explain daemon thread.

A

A daemon thread is a low priority thread that runs in the background to perform tasks such as

  • garbage collection, created by JVM itself
  • polling remote systems for status changes
  • sending email notifications etc
  • perform scheduled maintenance

JVM will shut down once all the non-deamon threads are finished working. Hence the daemon threads get automatically terminated when all normal threads have been terminated.

If we want to create a daemon thread, we need to call a setDaemon( boolean ) on an existing user thread to make it daemon. Any new thread spawned from a daemon thread will inherit its properties and become daemon thread.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How can we create a thread in Java?

A

We can create a thread object as:

Thread thread = new Thread( );

To start the thread, we call start( ) method on thread object:

thread.start( );

As this does not specify any code for thread to execute, it will stop right away.

There are two ways to specify what code the thread should execute:

  • extending Thread class: and overriding the run( ) method
  • passing an object that implements java.lang.Runnable to Thread constructor.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Explain thread creation with Thread subclass.

A
  1. Create a class that extends the Thread class
  2. Override its run( ) method

public class MyThread extends Thread {

public void run(){
   System.out.println("MyThread running");
}   }
  1. In the main( ) method, create an object of MyThread and call its start( ) method.
 MyThread myThread = new MyThread();
  myTread.start();

In Java 8, this can be condensed to:

public static void main( String[ ] args) {

Thread t= new Thread( ) {

@Override
public void run( ) {
System.out.println("My thread is running");
}
};

t.start();
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Explain thread creation with Runnable implementation.

A
  1. Create a class that implements java.lang.Runnable interface
  2. Override its run( ) method

public class MyRunnable implements Runnable {

public void run(){
   System.out.println("MyRunnable running");
}   }
  1. Pass an instance of the MyRunnable class to a Thread constructor and call the start( ) method on thread object.

Runnable runnable = new MyRunnable( );

Thread thread = new Thread ( runnable );
thread.start( );

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What happens if we call run( ) method on a thread object instead of start( )?

A

The thread will execute the given code but the execution will not be performed by a new thread. Rather it will be done by the original thread which created the thread.

Generally, the run( ) method is executed by new thread when start( ) is called.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

How can we give a name to a thread?

A

We can pass the name string to the thread constructor.

With Thread subclassing:
Thread thread = new Thread("Thread #1");
With Runnable implementation:
MyRunnable runnable = new MyRunnable( );
Thread thread = new Thread(runnable, "New Thread");

And then retrieve it with
thread.getName( );

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

How can we pause a thread?

A

A thread can pause itself by calling the static method Thread.sleep() which takes number of milliseconds as parameter.

The sleep() method will attempt to sleep that number of milliseconds before resuming execution.

try {
    Thread.sleep(10L * 1000L);
} catch (InterruptedException e) {
    e.printStackTrace();
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Explain a thread’s lifecycle.

A

java. lang.Thread contains an enum State, which defines its 6 potential states. During any given point of time, the thread can be in only one state.
1. NEW: a newly created thread that has not yet started the execution.
2. RUNNABLE: either running or ready for execution but it’s waiting for resource allocation
3. BLOCKED: waiting to acquire monitor lock to enter/reenter a synchronized block/method
4. WAITING: waiting for some other thread to perform a particular action without any time limit
5. TIMED_WAITING: waiting for some other thread to perform a specific action for a specified period
6. TERMINATED: has completed its execution

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Explain the NEW state of thread.

A

A NEW Thread is a thread that’s been created but not yet started. It remains in this state until we start it using the start( ) method.

Main m= new Main( );
Thread t = new Thread (m);
System.out.println( t.getState( ) );

will print NEW.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Explain the RUNNABLE state of thread.

A

When we create a new thread and call the start() method on that, it moves from NEW to RUNNABLE state. Threads in this state are either running or ready to run, but they’re waiting for resource allocation from the system.

Main m= new Main( );
Thread t = new Thread (m);
t.start( );
System.out.println( t.getState( ) );

will print RUNNABLE.

In a multi-threaded environment, the Thread Scheduler allocates a fixed amount of time to each thread. After it has run for a particular amount of time for a thread, it will relinquish the control to other RUNNABLE threads.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Explain the BLOCKED state of thread.

A

A thread is in the BLOCKED state when it’s currently not eligible to run. It enters this state when it is waiting to acquire the monitor lock on a synchronized code block that is locked by some other thread.

To reproduce it, we can create two different threads t1 and t2. Then we can start both t1 and t2, put t2 to sleep for 3 seconds.

Let t1 enter a static synchronized method containing an infinite loop via its run( ) method so that while t1 is inside, t2 will be blocked. Calling getState( ) on t2 will then print BLOCKED.

17
Q

Explain the WAITING state of thread.

A

A thread is in WAITING state when it’s waiting for some other thread to perform a particular action. It can do so by calling any of below methods:

  • wait( )
  • Thread.join( )

To reproduce it, we create and start a thread t1. Inside t1’s run( ) method, we create another thread t2, start it and call join( ) on it.

This will put t1 in WAITING state until t2 is finished. Since t1 is waiting for t2 to complete, calling getState( ) on t1 will print WAITING.

18
Q

Explain the TIMED_WAITING state of thread.

A

A thread is in TIMED_WAITING state when it’s waiting for another thread to perform a particular action within a stipulated amount of time. It can do so by calling any of the below methods:

  • Thread.sleep ( long millis )
  • Thread.join ( long millis )
  • wait ( int timeout ) or wait ( int timeout, int nanos )

We can reproduce it by creating it, starting it, putting a thread to sleep right away for 1s and inside run( ) method for 5s so that it sleeps for longer time.

Thread t= new Thread(new Main ( ) );
t.start( );
Thread.sleep( 1000 );
System.out.println( t.getState ( ) );

Inside run( ) method:
Thread.sleep( 5000 );
19
Q

Explain the TERMINTED state of thread.

A

This is the state of a dead thread. It’s in the TERMINATED state when it has either finished execution or was terminated abnormally.

20
Q

Explain thread priority.

A

In a Multi-Threading environment, Thread Scheduler assigns CPU resources to a thread based on thread’s priority. Whenever a thread is created, it always has some priority assigned to it either by JVM or by user explicitly.

Accepted value of priority for a thread is in range of 1 to 10, 1 being lowest and 10 being highest priority. Along with these, Thread class also defines three static int variables- MIN_PRIORITY(1), NORM_PRIORITY(5) and MAX_PRIORITY(10).

Usually higher priority thread gets precedence in execution but it doesn’t guarantee its prioritized execution.

We can invoke getPriority( ) method to retrieve the current priority and setPriority (int val) to set the new priority. Setting the priority anything other than [1, 10] will throw IllegalArgumentException.

21
Q

What is Thread Scheduler and time slicing?

A

Thread Scheduler is the OS service that allocates the CPU time and resources to the available runnable threads. Once we create and start a thread, it’s execution depends on the implementation of Thread Scheduler.

Time Slicing is the process to divide the available CPU time to the available runnable threads. Allocation of CPU time to threads can be based on thread priority or the thread waiting for longer time will get more priority in getting CPU time.

Thread scheduling can’t be controlled by java, so it’s always better to control it from application itself.

22
Q

What is context switching wrt multi-threading?

A

Context Switching is the process of storing and restoring CPU state so that Thread execution can be resumed from the same point later.

With this, one process switches out of CPU so another process can run. This context switch can be triggered by the process making itself unrunnable (by waiting for user input).

23
Q

Explain the join( ) method.

A

join( ) method is one of the mechanisms of inter-thread synchronization. When we invoke the join() method on a thread, the calling thread goes into a waiting state. It remains in a waiting state until the referenced thread terminates.

24
Q

How to make sure main( ) is the last thread to finish?

A

We can use join( ) method to make sure all threads created by main( ) are finished first.

25
Q

How does inter-thread communication happen?

A

With wait( ), notify( ) and notifyAll( ) methods.