Java Multi-threading Interview Questions.

Notes on Multithreading
  • Thread is a lightweight subprocess.
  • It can be created by extending the Thread class or implementing the runnable interface, and then overriding run method.
  •  A thread can be started by using start() method.
  • Using start() method without overriding the run() method will not create any thread.
Q.What are some important methods in Thread?
Thread.sleep()
  Sleep() is a static method.
  It takes an argument long millisecond, which makes the thread to sleep.
   Sleep() throws Interrupted exception .
Here CPU will be in idle state.
Thread.yield()
Yield() method is also a static method that causes the thread to temporarily suspend and it allows other same or higher priority threads to execute.
CPU will never be in idle state.
Thread.join()
If any executing thread t1 calls join t2, then it will wait for execution till t1 finishes.
Wait()
Causes the current thread to wait until another thread invokes the notify() or notifyAll() method.
Wait(), notify() and notifyAll() belongs to object class.
getName() method return name of a thread.
setName() method helps in setting the name of a thread.
setPriority() method helps in setting the priority of a thread, which can be from 1 to 10;
The default priority is 5.

States of a Thread
Q.Locks in java:
Whenever a static method is synchronized then, it acquires a class level lock.
When a non-static method is synchronized then, it acquires object level lock.
When we want a few lines of a class to be locked inside, a method we can use synchronized block.
In java8 concurrency API supports various explicit locks(e.g. Reentrant lock, ReadWrite Lock, Stamped Lock, Semaphore) provided by lock interface.
Q. What is race condition?
A race condition is when more than one thread tries to acquire a shared resource. It is okay if they are trying to read the resource, but ambiguity occurs when then try to write or make any change to it.
Q.Difference between fixed thread pool and cached Thread pool?
The java.util.concurrent package provides an interface Executor and a sub-interface ExecutorService, which is implemented by a class Executors.
There is a total of 5 Thread pools:
Single thread executor: This has only 1 thread and executes tasks one by one. The method used for this is Executors.newSingleThreadExecutor().
   e.g ExecutorService single = Executors.newSingleThreadExecutor();
Cached thread pool: This is a pool with several threads, which executes tasks simultaneously. Thread is reused here and destroyed if not reused within 60 seconds. The method used for this is newCachedThreadPool().
  e.g ExecutorService cached = Executors.newCachedThreadPool();
Fixed thread pool: This takes an argument of the number of threads to be created and executes the threads one by one. The method used for this is newFixedThreadPool(int No of threads)
 e.g ExecutorService fixed = Executors.newFixedThreadPool(10);
Scheduled thread pool: Here group of thread executes the task in the future after a time delay. The method used for this is newScheduledThreadPool().
 e.g ExecutorService scheduled = Executors.newScheduledThreadPool(5);
Single thread scheduled thread pool: This takes only one thread to run in the future. The method used for this is newSingleThreadScheduledExecutor().
e.g ExecutorService singleScheduled = Executors.newSingleThreadScheduledExecutor();
Q.What is  use of semaphore?
Semaphores are used to lock access to an object. Each thread must call acquire() before accessing to acquire lock and it must call release() to release lock.
Semaphore has 2 overloaded constructors i.e Semaphore(int number) && Semaphore(int number , boolean how), they are also called as counting semaphore and binary semaphore.
Q.What is BlockingQueue? Write a sample code for Blocking Queue?
A Blocking queue is a queue, that does not allow to remove while the queue is empty and does not allow to add while  queue is full.It is added in java concurrency package from java 5 .
Blocking queue can be called as below.
private final BlockingQueue<Integer> sharedQueue;

Q.How do you return something from a thread?

We use java callable instead of runnable. The call() method of callable can return value as well as throws exception.

Q)How do you communicate between 2 Threads.

Q) What is the Volatile keyword in java?

Q.Difference between volatile and atomic in java?

Difference between Lock and Synchronized in java?

  • A synchronized block makes no guarantee about the sequence of threads waiting to get access.
  • Synchronized block does not accept any argument, whereas in the lock we can pass how much time we should wait for a lock to be release else get timed out.
  •  Synchronized should be in a thread, lock and unlock can be called from separate thread.

How to stop a thread in java?

The stop() method has been deprecated now. So thread can be stopped using Thread.interrupt() method.

Also, we use the shutdown method if you are using the Executor Service method as below.


  • shutdown: No new tasks are accepted, all previous tasks are executed.
  • shutdownNow: Shut down immediately, also returns list of running tasks.
  • awaitTermination: This is used with shutdown and shudownNow and block until tasks are completed after shutdown.

What is the difference between Concurrency vs Parallelism?

Concurrency means an application making progress on more than one task simultaneously or concurrently. If an application has more than one task then it may not make more progress.

Parallelism means the application divides the task into multiple subtasks which can be processed parallel.

In Concurrency, it is how the application handles multiple tasks vs in parallelism it handles each individual task through the thread.

Previous
Next Post »

Pages