Multithreading interview questions in java for experienced – Multithreading Interview Questions in Java

Multithreading interview questions in java for experienced: List of topic-wise frequently asked java interview questions with the best possible answers for job interviews.

Multithreading Interview Questions in Java

Question 1.
What is a thread?
Answer: A thread is a set of instructions executing apart from other threads (with its own stack) but sharing the same memory space (with the same heap).

Question 2.
What is the difference between Process and Thread?
Answer:
The process is a program in execution whereas thread is a separate path of execution in a program.

A process can contain multiple threads. In most multithreading operating systems, a process gets its own memory address space; a thread doesn’t. Threads typically share the heap belonging to their parent process.
For instance, a JVM runs in a single process in the host O/S. Threads in the JVM share the heap belonging to that process; that’s why several threads may access the same object.

Typically, even though they share a common heap, threads have their own stack space. This is how one thread’s invocation of a method is kept separate from another’s. This is all a gross oversimplification, but it’s accurate enough at a high level. Lots of details differ between operating systems.

Java runtime environment runs as a single process that contains different classes and programs as processes. Thread can be called a lightweight process. Thread requires fewer resources to create and exists in the process, thread shares the process resources.
Table

Question 3.
What are the benefits of multi-threaded programming?
Answer:
In Multi-Threaded programming, multiple threads are executing concurrently which improves the performance because the CPU is not idle in case some thread is waiting to get some resources. Multiple threads share the heap memory, so it’s good to create multiple threads to execute some task rather than creating multiple processes. For example, Servlets are better in performance than CGI because Servlets support multi-threading but CGI doesn’t.

Question 4.
Difference between multithreading and multitasking?
Answer:
A Web Server understands and supports only HTTP protocol whereas an Application Server supports HTTP, TCP/IP, and many more protocols. Also, many more features such as Caches, Clusters, Load Balancing are there in Application Servers which are not available in Web Servers. We can also Configure Application Servers to work as Web Server. In short, Application Server is a superset of which the Web Server is a subset.

Question 5.
How does multithreading take place on a computer with a single CPU?
Answer:
The operating system’s task scheduler allocates execution time to multiple tasks. By quickly switching between executing tasks, it creates the impression that tasks execute sequentially.

Question 6.
What is the difference between a lightweight and a heavyweight process?
Answer:
[Short answer: threads are lightweight, programs (aka processes or tasks) are heavyweight.] Lightweight and heavyweight processes refer to the mechanics of a multi-processing system.

In a lightweight process, threads are used to divvy up the workload. Here you would see one process executing in the OS (for this application or service.) This process would possess 1 or more threads. Each of the threads in this process shares the same address space. Because threads share their address space, communication between the threads is simple and efficient. Each thread could be compared to a process in a heavyweight scenario.

In a heavyweight process, new processes are created to perform the work in parallel. Here (for the same application or service), you would see multiple processes running.
Each heavyweight process contains its own address space. Communication between these processes would involve additional communications mechanisms such as sockets or pipes.

The benefits of a lightweight process come from the conservation of resources. Since threads use the same code section, data section, and OS resources, fewer overall resources are used. The drawback is now you have to ensure your system is thread-safe. You have to make sure the threads don’t step on each other. Fortunately, Java provides the necessary tools to allow you to do this.

Question 7.
What is the difference between user Thread and daemon Thread?
Answer:
When we create a Thread in a java program, it’s known as a user thread. A daemon thread runs in the background and doesn’t prevent JVM from terminating. When there are no user threads running, JVM shutdown the program and quits. A child thread created from a daemon thread is also a daemon thread.

Question 8.
How can we create a Thread in Java?
Answer:
There are two ways to create Thread in Java – first by implementing Runnable interface and then creating a Thread object from it and second is to extend the Thread class. Read this post to learn more about creating threads in java.

Question 9.
What are the different stages in the lifecycle of Thread?
Answer:
When we create a Thread in a java program, its state is New. Then we start the thread that changes its state to Runnable. Thread Scheduler is responsible to allocate CPU to threads in the Runnable thread pool and change their state to Running. Other Thread states are Waiting, Blocked, and Dead. Read this post to learn more about the life cycle of the thread.

Question 10.
What is the atomic operation? What are atomic classes in Java Concurrency API?
Answer:
Atomic operations are performed in a single unit of task without interference from other operations. Atomic operations are necessary for a multi-threaded environment to avoid data inconsistency.
int++ is not an atomic operation. So by the time one thread reads its value and increment it by one, another thread has read the older value leading to the wrong result. To solve this issue, we will have to make sure that increment operation on count is atomic, we can do that using Synchronization but Java 5 java.util.concurrent. atomic provides wrapper classes for int and long that can be used to achieve this atomically without the usage of Synchronization. Go to this article to learn more about atomic concurrent classes.

Question 11.
What is the Lock interface in Java Concurrency API? What are its benefits over synchronization?
Answer:
The lock interface provides more extensive locking operations than can be obtained using synchronized methods and statements. They allow more flexible structuring, may have quite different properties and may support multiple associated Condition objects.
The advantages of a lock are

  • It’s possible to make them fair
  • It’s possible to make a thread responsive to interruption while waiting on a Lock object.
  • It’s possible to try to acquire the lock, but return immediately or after a timeout, if the lock can’t be acquired
  • It’s possible to acquire and release locks in different scopes, and in different orders

Question 12.
What is Executors Framework?
Answer:
In Java 5, the Executor framework was introduced with the java.util.concurrent. Executor interface. The Executor framework is a framework for standardizing invocation, scheduling, execution, and control of asynchronous tasks according to a set of execution policies. Creating a lot many threads with no bounds to the maximum threshold can cause the application to run out of heap memory. So, creating a ThreadPool is a better solution as a finite number of threads can be pooled and reused. Executors framework facilitate the process of creating Thread pools in java. Check out this post to learn with example code to create thread pool using Executors framework.

Question 13.
What is BlockingQueue? How can we implement the Producer-Consumer problem using Blocking Queue?
Answer:
java.util.concurrent.BlockingQueue is a Queue that supports operations that wait for the queue to become non-empty when retrieving and removing an element, and wait for space to become available in the queue when adding an element. BlockingQueue doesn’t accept null values and throw NullPointerException if you try to store null value in the queue.
BlockingQueue implementations are thread-safe. All queuing methods are atomic in nature and use internal locks or other forms of concurrency control. BlockingQueue interface is part of the java collections framework and it’s primarily used for implementing producer-consumer problems.

Question 14.
What is Callable and Future?
Answer:
Java 5 introduced java.util.concurrent.Callable interface in concurrency package that is similar to Runnable interface but it can return any Object and able to throw Exception.

The callable interface uses Generic to define the return type of Object. Executors class provides useful methods to execute Callable in a thread pool. Since callable tasks run in parallel, we have to wait for the returned Object. Callable tasks return java.util. concurrent.Future object. Using Future we can find out the status of the Callable task and get the returned Object. It provides get( ) method that can wait for the Callable to finish and then return the result.

Question 15.
What is FutureTask Class?
Answer:
Futuremark is the base implementation class of the Future interface and we can use it with Executors for asynchronous processing. Most of the time we don’t need to use FutureTask class but it comes really handy if we want to override some of the methods of the Future interface and want to keep most of the base implementation. We can just extend this class and override the methods according to fb our requirements. Check out the Java FutureTask Example post to learn how to use it and what are different methods it has.

Question 16.
What are Concurrent Collection Classes?
Answer:
Java Collection classes are fail-fast which means that if the Collection will be changed while some thread is traversing over it using iterator, the iterator.next( ) will throw ConcurrentModificationException.
Concurrent Collection classes support full concurrency of retrievals and adjustable expected concurrency for updates.
Major classes are ConcurrentHashMap, CopyOnWriteArrayList and CopyOnWriteArraySet, check this post to learn how to avoid ConcurrentModificationException when using iterator.

Question 17.
what is Executors Class?
Answer:
Executors class provide utility methods for Executor, ExecutorService, ScheduledExecutorService, ThreadFactory, and Callable classes. Executors class can be used to easily create Thread Pool in java, also this is the only class supporting the execution of Callable implementations.

Question 18.
W^hat are some of the improvements in Concurrency API in Java 8?
Answer:
Some important concurrent API enhancements are:

  • ConcurrentHashMap compute( ), forEach( ), forEachEntry( ), forEachKey( ), forEachValue( ), merge( ), reduce( ) and search( ) methods.
  • CompletableFuture that may be explicitly completed (setting its value and status).
  • Executors newWorkStealingPoolO method to create a work-stealing thread pool using all available processors as its target parallelism level.

Question 19.
Explain Java Thread Life cycle.
Answer:
The life cycle of threads in Java is very similar to the life cycle of processes
running in an operating system. During its life cycle, the thread moves from one
state to another depending on the operation performed by it or performed on it. A
Java thread can be in one of the following states:

• NEW: A thread that is just instantiated is in the new state. When a start 0 method is invoked, the thread moves to the ready state from which it is automatically moved to a runnable state by the thread scheduler.
• RUNNABLE (ready_running) A thread executing in the JVM is in a running state.
• BLOCKED A thread that is blocked waiting for a monitor lock is in this state. This can also occur when a thread performs an I/O operation and moves to the next (runnable) state.
• WAITING for A thread that is waiting indefinitely for another thread to perform a particular action is in this state.
• TIMED_WAITING (sleeping) A thread that is waiting for another thread to perform an action up to a specified waiting time is in this state.
• TERMINATED (dead) A thread that has exited is in this state.

Question 20.
What are the states associated with the thread?
Answer:
The thread contains ready, running, waiting, and dead states.

Question 21.
What state is a thread in when it is executing?
Answer:
An executing thread is in the running state.

Question 22.
How can a dead thread be restarted?
Answer:
A dead thread cannot be restarted.

Question 23.
What are the different ways of creating a thread?
Answer:
There are two ways of creating a thread.
• Implementing Runnable: The Runnable interface defines a single method, run, meant to contain the code executed in the thread. The Runnable object is passed to the Thread constructor, as in the HelloRunnable example

public class HelloRunnable implements Runnable {
public void run( ) {
system. out.println(“Hello from a thread!”);
}
public static void main(string args[]) {
(new Thread(new HelloRunnable( ))).start();
}
}

• Subclass Thread: The Thread class itself implements Runnable interface, though it runs method does nothing. An application can subclass Thread, and provides its own implementation of the run, as in the HelloThread example:

public class HelloThread extends Thread {
public void run( ) {
System. out.println(“Hello from a thread!”);
}
public static void main(string args[ ])
{
(new HelloThread( )).start( );
}
}

Question 24.
What are the differences between extending the Thread class and implementing the Runnable interface?
Answer:
Extending the Thread class will make your class unable to extend other classes, because of the single inheritance feature in JAVA. However, this will give you a simpler code, structure. If you implement runnable, you can gain better object-oriented design and consistency and also avoid the single inheritance problems.

Question 25.
When is a thread created?
Answer:
A thread is created by the VM behind the scenes during a call to the start( ) method. It begins its life inside the run( ) method of the thread subclass instance whose start( ) method was called.

Question 26.
Hem do I create a new thread and have it start running?
Answer:
Creating a thread involves creating a new Thread and invoking its start( ) method. Calling start( ) causes the run( ) method of the Thread subclass or the Runnable object passed to the Thread constructor to execute.

Thread t1 = new Thread( ) {
      public void run( ) {
             for (int i=0; i<100; i++) {
                   System.out.println(“Tastes Great”);
             }
       }
};
Runnable r = new Runnable( ) {
      public void run( ) {
             for (int i=0; i<100; i++) {

                   system.out.println(“Less Filling”);
             }
      }
};
Thread t2 = new Thread(r);
t1.start( );
t2.start( );

Question 27.
What is the use of the start( ) function in starting a thread? Why we don’t use the run( ) functions directly to run the thread?
Answer:
The start( ) method tells the Java Virtual Machine that it needs to create a system-specific thread. After creating the system resource, it passes the Runnable object to it to execute its run( ) method. Calling the run( ) method directly has the “Thread” execute in the same thread as the calling object, not in a separate thread of execution, as intended.

In other words, calling run( ) is just like a normal method call. Whereas, calling start( ) tells the thread to create the necessary system resources and then execute the run( ) method asynchronously.

Question 28.
Can each Java object keep track of all the threads that want to exclusively access it?
Answer:
Yes.

Question 29.
What is the use of the start( ) function in starting a thread? Why we do not use the run( ) function directly to run the thread?
Answer:
The start( ) method tells the Java Virtual Machine that it needs to create a system specific thread. After creating the system resource, it passes the Runnable object to it to execute its run( ) method. Calling the run( ) method directly has the “Thread” execute in the same thread as the calling object, not in a separate thread of execution, as intended.
In other words, calling run( ) is just like a normal method call. Whereas, calling start( ) tells the thread to create the necessary system resources and then execute the run( ) method asynchronously.
Question 30.
What method must be implemented by all threads?
Answer:
All tasks must implement the run( ) method, whether they are a subclass of Thread or implement the Runnable interface.
Question 31.
Where can I find a set of data structures to deal with many of the concurrent programming concepts?
Answer:
Doug Lea has produced a utility library in conjunction with his Concurrent Programming in Java that includes many common classes needed to help you synchronize your data access, like mutex and semaphore.
Question 32.
Which way a developer should use for creating a thread, i.e. Subclassing Thread or implementing Runnable.
Answer:
There are two ways of creating Thread in java (i.e. subclassing or implementing Runnable). It is very important to understand the implication of using these two approaches.
There are two different points about using these two approaches.
• By extending the thread class, the derived class itself is a thread object and it gains full control over the thread life cycle. Implementing the Runnable interface does not give developers any control over the thread itself, as it simply defines the unit of work that will be executed in a thread.
• Another important point is that when extending the Thread class, the derived class cannot extend any other base classes because Java only allows single inheritance. By implementing the Runnable interface, the class can still extend other base classes if necessary.
To summarize, if a developer needs full control over the Thread life cycle, subclassing Thread class is a good choice, and if programs need more flexibility by extending other class developer, should go with implementing Runnable interface.
Question 33.
How to create multithreaded program? Explain different ways of using thread? When a thread is created and started, what is its initial state?
Or
Extending Thread class or implementing Runnable Interface. Which is better?
Answer:
You have two ways to do so. First, making your class “extends” Thread class. The other way is making your class implement the “Runnable” interface. The latter is more advantageous, ’cause when you are going for multiple inheritance, then only interface can help. If you are already inheriting a different class, then you have to go for Runnable Interface. Otherwise you can extend the Thread class.
Also, if you are implementing an interface, it means you have to implement all methods in the interface. Both Thread class and Runnable interface are provided for convenience and use them as per the requirement. But if you are not extending any class, better extend Thread class as it will save few lines of coding. Otherwise performance-wise, there is no distinguishable difference. A thread is in the ready state after it has been created and started.
Question 34.
What are three ways in which a thread can enter the waiting state?
Answer:
A thread can enter the waiting state by invoking its sleep( ) method, by blocking on I/O, by unsuccessfully attempting to acquire an object’s lock, or by invoking an object’s wait( ) method. It can also enter the waiting state by invoking its (deprecated) suspend( ) method.
Question 35.
What’s new with the stop( ), suspend( ) and resume( ) methods in JDK 1.2?
Answer:
The stop( ), suspend( ) and resume( ) methods have been deprecated in JDK
Question 36.
How would you implement a thread pool?
Answer:
public class ThreadPool extends java.lang.Object implements ThreadPoolInt This class is a generic implementation of a thread pool, which takes the following input
a) Size of the pool to be constructed
b) Name of the class which implements Runnable (which has a visible default constructor) and constructs a thread pool with active threads that are waiting for activation. Once the threads have finished processing they come back and wait once again in the pool.
This thread pool engine can be locked i.e. if some internal operation is performed on the pool then it is preferable that the thread engine be locked. Locking ensures that no new threads are issued by the engine. However, the currently executing threads are allowed to continue till they come back to the passivePool
Question 37.
What is the class and interface in java to create thread and which is the most advantageous method?
Answer:
Thread class and Runnable interface can be used to create threads and using Runnable interface is the most advantageous method to create threads because we need not extend thread class here.
Question 38.
what is the use of Join method?
Answer:
The join method allows one thread to wait for the completion of another. If
“ t “ is a Thread object whose thread is currently executing,
t.join( );
Causes the current thread to pause execution until t’s thread terminates. Overloads of join allow the programmer to specify a waiting period. However, as with sleep, join is dependent on the OS for timing, so you should not assume that join will wait exactly as long as you specify.
Like sleep, join responds to an interrupt by exiting with an InterruptedException.
Question 39.
What is the difference between sleep( ), wait( ), and suspend( )?
Answer:
Thread. sleep( ) sends the current thread into the “Not Runnable” state for some amount of time. The thread keeps the monitors it has acquired – i.e. if the thread is currently in a synchronized block or method no other thread can enter this block or method. If another thread calls t.interrupt( ) it will wake up the sleeping thread.
Note that sleep is a static method, which means that it always affects the current thread (the one that is executing the sleep method). A common mistake is to call t.sleepO where t is a different thread; even then, it is the current thread that will sleep, not the t thread.
t.suspend( ) is deprecated. Using it is possible to halt a thread other than the current thread. A suspended thread keeps all its monitors and since this state is not interruptable it is deadlock prone.
object. wait( ) sends the current thread into the “Not Runnable” state, like sleep( ), but with a twist. Wait is called on a object, not a thread; we call this object the “lock. object.” Before lock.wait( ) is called, the current thread must synchronize on the lock object; wait( ) then releases this lock, and adds the thread to the “waitlist” associated with the lock. Later, another thread can synchronize on the same lock object and call the lock.notify( )- This wakes up the original, waiting thread. Basically, wait( )/notify( ) is like sleep( )/interrupt( ), only the active thread does not need a direct pointer to the sleeping thread, but only to the shared lock object.
Question 40.
What is the difference between yielding and sleeping?
Answer:
When a task invokes its yield( ) method, it returns to the ready state. When a task invokes its sleep( ) method, it returns to the waiting state.
Question 41.
What happens when you invoke a thread’s interrupt method while it is sleeping or waiting?
Answer:
When a task’s interrupt( ) method is executed, the task enters the ready state. The next time the task enters the running state, an InterruptedException is thrown.
Question 42.
What are three ways in which a thread can enter the waiting state?
Or
What are different ways in which a thread can enter the waiting state?
Answer:
A thread can enter the waiting state in the following ways:
  1. Invoking its sleep ( ) methods,
  2. By blocking on I/O
  3. By unsuccessfully attempting to acquire an object’s lock
  4. By invoking an object’s wait( ) method.
  5. It can also enter the waiting state by invoking its (deprecated) suspend( ) method.
Question 43.
How can one thread wait for another thread to die before it continues execution?
Answer:
The thread’s join( ) method allows you to wait for another thread to finish execution.
Thread t1 = new Thread(runnable); 
t1.start( );
// do stuff
. . .
// wait for tl to finish 
t1. join( )
Question 44.
How do I get a thread to pause?
Answer:
The static sleep( ) method of the Thread class will let your thread sleep for a set number of milliseconds (or nanoseconds). When the thread wakes up, it will be scheduled to execute in the future. It may not start executing immediately after the timeout.
try {
Thread.sleep(3000); // 3 seconds 
} catch (interruptedException e) {
                   System.err.prinlnt(“You interrupted me”);
}
[You can have another thread wake up the sleeping thread prematurely by calling t.interruptO (where “t” is a pointer to the thread object).
Note that since Thread.sleep( ) is a static method, the following code will not do what you expect it to:
Thread t = new MyThread( ); 
t.start( ); 
try {
          t.sleep(3000);
} catch (interruptedException e) {
         System.err.prinlnt(“You interrupted me”);
}

It will pause the current thread, meaning the thread executing the shown code, not the child thread (t/MyThread).

Question 45.
What are daemon threads and which method is used to create the daemon thread?
Answer:
Daemon thread is a low priority thread that runs intermittently in the background doing the garbage collection operation for the java runtime system. setDaemon method is used to create a daemon thread.
Question 46.
How can a daemon thread be implemented?
Answer:
After creating an object of a Thread class and before starting the thread, call the setDeamon ( ) function of the Thread class with parameter as true. This will mark the thread as a daemon thread.
Question 47.
Is there any limitation on the number of daemon threads in an application?
Answer:
No, there is no limitation on the number of daemon threads in an application.
Question 48.
What is a daemon thread? What is the use of daemon thread?
Answer:
Daemon term is mainly used in UNIX. In Java, this is used to indicate a special type of thread. Normally when a thread is created in Java, by default it is a non-daemon thread. Whenever a Java Program is executed, the Java Virtual Machine (JVM) will not exit until any non-daemon threads are still running. This means if the main thread of an application ends and the remaining threads left are Daemon threads, then the JVM will exit killing all the daemon threads without warning.
A daemon thread should be used for some background task that might provide a service to the applications. E.g. a Server threads listening on a port for the clients’ requests. A thread for which an exit method is not provided or which does not have an exit mechanism can be marked as a daemon thread.
Question 49.
How do I have one thread wait for another thread to finish before continuing?
Answer:
You can wait for a thread to finish by calling its join( ) method. For instance, in the following code, the current thread will wait until thread2 finishes before printing “Done”.
thread2.start( );
// do more stuff here 
thread2.join( );
System.out.print!n(“Done”);
Question 50.
How can I catch exceptions thrown in secondary threads I create?
Answer:
You need to create the secondary threads in a custom ThreadGroup. Subclass ThreadGroup and override public void uncaughtException (Thread source, Throwable throwable). This method would then be notified when an uncaught exception is thrown.
Question 51.
How do I create a variable local to a Thread?
Answer:
The Java 1.2 release introduced the concept of thread local variables as a standard class. Previously, they existed in the sun. server.util package of the Java
Webserver product. Now, you get them in java. lang.ThreadLocal and java. lang. *”%. InheritableThreadLocal classes. These classes permit individual threads to have ‘ independent copies of variables. With ThreadLocal, only a particular thread sees the variable, with InheritableThreadLocal a thread and all its descendants can see it.
Here’s an example,
public class LocalThreadvars implements Runnable {
static private class MyThreadLocal extends ThreadLocal {
            protected object initialvalue( ) {
                        return new Double (Math.random( ) * 1000.0);
            }
   }
static ThreadLocal threadLocal = new MyThreadLocal( );
static int counter = 0;
private LocalThreadvars( ) {
counter++;
}
public void run( ) {
       LocalThreadvars myLTV = new LocalThreadvars( );
       displayvalues( );
       try {
                Thread.currentThread( ).sleep (((Double)
threadLocal .get( )) .longvalue( ));
                myLTV. displayvalues( );
} catch (interruptedException e) {
               e.printStackTrace( );
      }
}
private void displayvalues( ) {
         System.out.println (threadLocal.get( ) + “\t” + counter + 
“\t” + Thread. currentThread( ) .getName( ));
  }
public static void main (String args[ ]) {
        LocalThreadvars 1 tv = new LocalThreadvars( );
        1 tv. displayvalues( );
        for (int i=0;i<5;i++) {
                 Thread t = new Thread (Itv);
                 t.start( );
          }
     }
}

Question 52.
Is there a separate stack for each thread in Java?
Answer:
No

Question 53.
What is the main difference between a preemptive scheduler and a non-preemptive scheduler?
Answer:
A preemptive scheduler interrupts a thread of execution when its time slice rims out. A non-preemptive (or “cooperative”) scheduler waits for the thread to yield control.
[Java native thread implementations are usually preemptive; the green-threads implementation is cooperative but priority-preemptive, which means that when a high-priority thread becomes runnable, it immediately becomes active.]
Question 54.
How does a preemptive scheduler manage a thread’s time slice?
Answer:
The lowest level preemptive scheduler (kernel layer) uses the system timer interrupt and context switching to manage time slices. When any CPU interrupt occurs, the CPU makes a note of where it was, and what it was doing (pushes all registers onto the stack). The CPU then processes the interrupt and returns to what it was previously doing (pops all registers from the stack). The thread context in this sense, is the information the CPU needs to start or resume execution in any section of code. The scheduler is invoked by the timer interrupt routine (it can also be part of the timer interrupt).
The scheduler checks to see if the current time slice has expired; if so, the current thread context is stored and the next valid thread context is restored. The most basic implementation is a stack swap, as each thread has its own stack. When a thread is created, it gets a new context with an empty stack. The new context directs the CPU to the thread’s run( ) member at the beginning of its time slice. A thread’s context is destroyed when the thread returns from the run( ) member or its stop( ) member is successfully invoked.
Question 55.
Why are resources tied to ThreadGroups?
Answer:
Every thread of execution on any given platform has its own context, which contains an execution state, and a set of access rights (among other things). A thread’s access rights are equal to that of the parent thread, minus rights denied by the parent. In Java, all threads of execution, and thread groups within an applet (or application) belong to a parent ThreadGroup object. A thread’s access to Java resources is therefore determined by its parent ThreadGroup object (including the thread of execution that passes through init( ), start( ), stop( ), processEvent(…),
Question 56.
How can I create ThreadGroups in applets running in Netscape 4.7 without generating security exceptions?
Answer:
Sign your code and enable UniversalThreadGroupAccess PrivilegeManager.enablePrivilege(“UniversalThreadGroupAccess”);
Question 57.
How can multiple threads be controlled simultaneously?
Answer:
If you create threads in a ThreadGroup object, they may be controlled simultaneously with the member functions of said object.
Question 58.
What is synchronization?
Answer:
Synchronization is the mechanism that ensures that only one thread is accessed the resources at a time.
Question 59.
When you will synchronize a piece of your code?
Answer:
When you expect your code will be accessed by different threads and these threads may change a particular data causing data corruption.
Question 60.
What is deadlock?
Answer:
When two threads are waiting each other and can’t precede the program is said to be deadlock.
Question 61.
What is the Difference between synchronized and synchronized block?
Answer:
In case of a Synchronized method a thread may need to have the lock for a longer time as compared to the synchronized block.
Another difference between synchronized method and block is that we don’t specify the particular object whose monitor is required to be obtained by a thread for entering a synchronized method, whereas we can specify the particular object in case of synchronized block.
Question 62.
What are synchronized methods and synchronized statements?
Answer:
Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method’s object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement 195. What are the two basic ways in which classes that can be run as threads may be defined? A thread class may be declared as a subclass of Thread, or it may implement the Runnable interface.
Question 63.
Static Synchronization vs Instance Synchronization?
Answer:
When a static synchronized method is called, the program obtains the class lock before calling the method. This mechanism is identical to the case in which the method is non-static, it is just a different lock, and this lock is solely for static method. Apart from the functional relationship between the two locks, they are riot operationally related at all.
Question 64.
Multiple Threads can access a class method at the same time. To avoid this we use SYNCHRONIZED. However, using SYNCHRONIZED can lock that method until released by the particular thread. Is there a way to avoid this locking?
Answer:
Use SYNCHRONIZE with the object to be locked within the method.
Question 65.
Will there be a performance penalty if you make a method synchronized? If so, can you make any design changes to improve the performance.
Answer:
yes, the performance will be down if we use synchronization. One can minimize the penalty by including garbage collection algorithm, which reduces the cost of collecting large numbers of short- lived objects. And also by using improved thread synchronization for invoking the synchronized methods, the invoking will be faster.
Question 66.
How does serialization work?
Answer:
It’s like FIFO method (first in first out)
Question 67.
Can a method be static and synchronized?
Answer:
No, a static method can’t be synchronized.
Question 68.
What is synchronization and why is it important?
Answer:
With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object’s value. This often causes dirty data and leads to significant errors.
Question 69.
Different uses of synchronized keyword?
Answer:
The keyword synchronized is used to acquire a exclusive monitor lock on an object. It can be used to mark either a method or a block of code. In both cases, it means to acquire a lock for the duration of the method or block, and to release the lock at the end. It also takes a parameter, which names the object whose lock will be acquired. (The parameter is implicit when marking a method, as shown below.)
synchronized (foo) {
... 
}
Acquires a lock on the object instance “foo” at the open brace, and releases the lock at the close brace.


synchronized (this) { 
...
}
Acquires a lock on the current object instance (“this”) at the open
brace, and releases the lock at the close brace.


synchronized void bar( ) {
...
}
}
Acquires a lock on the current object instance at the open brace, and releases it at the close brace. This is equivalent (*) to
void bar( ) {
synchronized (this) {
...
}
}
class Foo {
 synchronized static void bar( ) {
... 
}
}

Acquires and releases a lock on the class instance of class Foo. Every class, when loaded, is given an instance of class Class. That means that no matter who invokes method Foo. bar( ), the lock will be on the static instance, and not on any specific instance of class Foo.

I know this sounds confusing, but it has the same semantics as any other use of static: all statics (methods, variables, etc) are essentially global, interact with all other statics of the same class, and do not interact with non-static instance data. Whether a method is public or not makes no difference to the semantics of synchronized.
(* Actually, there is a very small, technical difference between void barO { synchronized (this) {…}} and synchronized void barO { … }: the VM may be able to very slightly optimize the latter case, since the synchronization is marked in the method signature and not in code. However, this is not important in practice.)
Question 70.
What will happen if non-synchronized method calls a static synchronized method and what kind of lock it acquires?
Answer:
If a non-static synchronized method calls a static synchronized method it acquires both locks i.e. lock on the object and lock on the class level.
The class lock does not actually exist the class lock, is the object lock of the “Class” object that models the class. Since there is only one “Class” object per class, using this object achieves the synchronization for the static method.
  • Only one thread can execute a synchronized static method per class.
  • Only one thread per instance of the class can execute a non-static synchronized method.
  • Any number of threads can execute a non-synchronized method static or non-static method.
Question 71.
What object do non-static synchronized methods use for locking?
Answer:
Non-static synchronized methods synchronize on the instance (this) of the class.
Question 72.
What are the different uses of the synchronized keyword?
Answer:
The keyword synchronized is used to acquire an exclusive monitor lock on an object. It can be used to mark either a method or a block of code. In both cases, it means to acquire a lock for the duration of the method or block, and to release the lock at the end. It also takes a parameter, which names the object whose lock will be acquired. (The parameter is implicit when marking a method, as shown below.)
synchronized (foo) {
...
}
Acquires a lock on the object instance “foo” at the open brace, and releases the lock at the close brace.
synchronized (this) {
...
}
Acquires a lock on the current object instance (“this”) at the open brace, and releases the lock at the close brace,
synchronized void bar( ) {
...
}
Acquires a lock on the current object instance at the open brace, and releases it at the close brace. This is equivalent (*) to
void bar( ) {
synchronized (this) {
  ...
  }
}
class Foo {
   synchronized static void bar) {
   ...
}
}

Acquires and releases a lock on the class instance of class Foo. Every class, when loaded, is given an instance of class Class. That means that no matter who invokes method Foo. bar( ), the lock will be on the static instance, and not on any specific instance of class Foo.

I know this sounds confusing, but it has the same semantics as any other use of static: all statics (methods, variables, etc) are essentially global, interact with all other statics of the same class, and do not interact with non-static instance data.
Whether a method is public or not makes no difference to the semantics of synchronized.
(* Actually, there is a very small, technical difference between void bar() {synchronized (this) {…}} and synchronized void bar() {»… }: the VM may be able to very slightly optimize the latter case, since the synchronization is marked in the method signature and not in code. However, this is not important in practice.)
Question 73.
What object do static synchronized methods use for locking?
Answer:
Static synchronized methods synchronize on the class object (this. getClass( )) of the class.
Question 74.
Can a lock be acquired on a class?
Answer:
Yes, a lock can be acquired on a class. This lock is acquired on the class’s Class object.
Question 75.
What is the use of volatile in Java?
Answer:
Threads are allowed to hold the values of variables in local memory (e.g. in a machine register).
If a variable is marked as volatile, every time when the variable is used, it must be read from the main memory, similarly every time the variable is written, the value must be stored in the main memory.
Question 76.
What are the ways in which a thread can enter the waiting state?
Answer:
A thread can enter the waiting state by invoking its sleep( ) method, by blocking on 10, by unsuccessfully attempting to acquire an object’s lock, or by invoking an object’s wait( ) method. It can also enter the waiting state by invoking its (deprecated) suspend( ) method.
Question 77.
How does multi-threading take place on a computer with a single CPU? j
Answer:
The operating system’s task scheduler allocates execution time to multiple tasks. By quickly switching between executing tasks, it creates the impression that tasks execute sequentially.
Question 78.
What invokes a thread’s run() method?
Answer:
After a thread is started, via its start( ) method of the Thread class, the 5

JVM invokes the thread’s run( ) method when the thread is initially executed.

Question 79.
What is the difference between yielding and sleeping?
Answer:
When a task invokes its yield( ) method, it returns to the ready state. When a task invokes its sleep( ) method, it returns to the waiting state.

Question 80.
What’s the difference between the methods sleep( ) and wait()?
Answer:
The code sleep(2000); puts thread aside for exactly two seconds. The code wait(2000), causes a wait of up to two second. A thread could stop waiting earlier if it receives the notify( ) or notifyAll( ) call. The method wait( ) is defined in the class Object and the method sleep( ) is defined in the class Thread.

Question 81.
What is a transient variable?
Answer:
A transient variable is a variable that may not be serialized during Serialization and which is initialized by its default value during de-serialization.

Question 82.
What is the daemon thread?
Answer:
Daemon thread is a low priority thread, which runs intermittently in the background doing the garbage collection operation for the java runtime system.

Question 83.
Is there any limitation on the number of daemon threads in an application?
Answer:
No, there is no limitation on the number of daemon threads in an application.

Question 84.
How can a daemon thread be implemented?
Answer:
After creating an object of a Thread class and before starting the thread, call the setDeamon ( ) functions of the Thread class with parameter as true. This will mark the thread as a daemon thread.

Question 85.
When should I use setDaemon( ) and why?
Answer:
Use setDaemon( ) to tell the JVM to make the thread a daemon thread. According to Webster’s, a daemon (variant of demon) is an attendant power or spirit. Daemon threads are typically used to perform services for your application/applet (such as loading the “fiddley bits”). The core difference between user threads and daemon threads is that the JVM will only shut down a program when all user threads have terminated or starved to death (See the “Starvation” FAQ, #41875). Daemon threads are terminated by the JVM when there are no longer any user threads running, including the main thread of execution. Use daemons as the minions they are.
[In short: daemon threads do not keep the program from quitting; user threads do.]

Question 86.
Which method is used to create the daemon thread?
Answer:
setDaemon method is used to create a daemon thread.

Question 87.
Which method must be implemented by all threads?
Answer:
All tasks must implement the run( ) method

Question 88.
What is multithreading and what are the methods for inter-thread communication and what is the class in which these methods are defined?
Answer:
Multithreading is the mechanism in which more than one thread runs independently of each other within the process.
wait ( )* notify ( ) and notifyAll( ) methods can be used for inter-thread communication and these methods are in the Object class.
wait( ): When a thread executes a call to wait( ) method, it surrenders the object lock and enters into a waiting state.
notify( ) or notifyAll( ) : To remove a thread from the waiting state, some other thread must make a call to notify() or notifyAll() method on the same object.

Question 89.
Why are the methpds wait() and notify() defined in the Object class when they are used with Threads?
Answer:
The wait( ) and notify( ) methods are object.-specific. The waitO^method suspends the current thread of execution, and tells the object to keep track of the suspended thread. The notify( ) method tells the object to wake up the suspended threads that it is currently keeping track of. Since wait( ) and notify( )  object
specific, they must be used within code that is synchronized on the object in question.
It is also important to use state variables when using wait( ) and notify( ), as threads can be woken up by conditions other than notify( ).

Question 90.
What is the purpose of the wait( ), notify( ), and notifyAll( ) methods?
Answer:
The wait( ), notify( ), and notifyAll( ) methodf are used to provide an efficient way for threads to wait for a shared resource. When a thread executes an object’s wait( ) method, it enters the waiting state. It only enters the ready state after another thread invokes the object’s notify( ) or notifyAll( ) methods.

Question 91.
What is “starvation” when used in the context of the Java threading model? ‘
Answer:
Starvation is when the Java runtime (JVM) doesn’t allocate time to a thread to execute. This may be due to a poor scheduling algorithm (like green Threads under Solaris, where a for loop from 1 to 1 million doing something CPU intensive wouldn’t yield the CPU under Solaris but would under Windows), poor programming practice (not returning from the paintO method in an applet), or a hostile attack (like hitting a host with a denial of service attack where the CPU is busy outside the Java process).

Question 92.
What happens when a thread cannot acquire a lock on an object?
Answer:
If a thread attempts to execute a synchronized method or synchronized statement and is unable to acquire an object’s lock, it enters the waiting state until the lock becomes available.

Question 93.
What is the meaning of calling a method or object “thread-safe?”
Answer:
Basically, calling a method “thread-safe” means that even if multiple threads try to access it simultaneously, nothing bad happens. Here “bad” usually means that due to race conditions, or deadlock, or other pitfalls, the object’s state gets corrupted, or its methods produce unreliable results. A method usually achieves thread-safety by protecting access to shared resources. This usually translates to using the Java synchronized keyword to protect blocks of code that access instance variables, or other shared variables.

For an object to be thread-safe, it must be possible for multiple threads to simultaneously access the same method, or multiple methods, in that object. Usually this is achieved by assuring that each method is thread-safe, but this doesn’t always suffice, since methods can call each other in strange ways, leading to deadlock and other weirdness.

It is very difficult to prove that an object is thread-safe. The main rule of thumb for making thread-safe objects is, “Make all the instance variables private, and all the public accessor methods synchronized.” However, this is sometimes difficult to achieve in practice, due to exigencies of performance, architecture, or implementation. Accurate multithreaded programming is a true art, and very difficult to master. Read “Java Threads” by Oaks and Wong, and “Concurrent Programming in Java” by Lea, for inspiration in your quest to become a thread-safe programmer.

Question 94.
What is the keyword volatile used for? What sort of situations should I use volatile when developing a multi-threaded application?
Answer:
Volatile modifiers tells the compiler that the variable can be changed unexpectedly by another part of programme. When you have nore than one thread and you expect any thread can change the variable you should use volatile. This will tell the compiler to check for the master copy of this variable. Mostly used for boolean flags.

Question 95.
When and why IllegalMonitorStateException throw?
Answer:
Thrown to indicate that a thread has attempted to wait on an object’s monitor or to notify other threads waiting on an object’s monitor without owning the specified monitor.

According to the JavaDoc, IllegalMonitorStateException is thrown “to indicate that a thread has attempted to wait on an object’s monitor or to notify other threads waiting on an object’s monitor without owning the specified monitor.”
As explained in How do wait and notify really work? in order to call foo.wait( ) or foo. notify( ), the calling thread must own a lock on object foo. This exception is thrown if you call it without a preceding synchronized (foo).

Question 96.
What is the relationship between synchronized and volatile keywords?
Answer:
The JVM is guaranteed to treat reads and writes of data of 32 bits or less as atomic. (Some JVM might treat reads and writes of data of 64 bits or less as atomic in future) For long or double variable, programmers should take care in multi-threading environment. Either put these variables in a synchronized method or block, or declare them volatile.

Question 97.
What factors are used to decide using synchronized or volatile?
Answer:
Whether you use volatile or synchronized depends on several factors.

a) If you are not updating many variables often in a multithread environment, consider using volatile.
b) If you are updating many variables, consider using synchronized, because using volatile might be slower.

Question 98.
Two methods have keywords static synchronized and synchronized separately. What is the difference between them?
Answer:
Both are synchronized methods. One is instance method, the other is the class method. The method with static modifier is a class method. That means the method belongs to class itself and can be accessed directly with class name and is also called Singleton design. The method without a static modifier is an instance method. That means the instance method belongs to its object. Every instance of the class gets its own copy of its instance method.

Since both methods are synchronized methods, you are not asked to explain what is a synchronized method. You are asked to tell the difference between instance and class method. Of course, your explanation of how synchronized keyword works doesn’t hurt. And you may use this opportunity to show your knowledge scope. When synchronized is used with a static method, a lock for the entire class is obtained. When synchronized is used with a non-static method, a lock for the particular object (that means instance) of the class is obtained.

Question 99.
What is mutual exclusion? How can you take care of mutual exclusion using Java threads?
Answer:
Mutual exclusion is a phenomenon where no two processes can access critical regions of memory at the same time. Using Java multithreading we can arrive at mutual exclusion. For mutual exclusion, you can simply use the synchronized keyword and explicitly or implicitly provide an Object, any Object, to synchronize on. The synchronized keyword can be applied to a class, to a method, or to a block of code. There are several methods in Java used for communicating mutually exclusive threads such as wait(), notify( ), or notifyAll( ). For example, the notifyAll( ) method wakes up all threads that are in the wait list of an object.

Question 100.
Can Java objects be locked down for exclusive use by a given thread?
Or
what happens when a thread cannot acquire a lock on an object?
Answer:
Yes. You can lock an object by putting it in a “synchronized” block. The locked object is inaccessible to any thread other than the one that explicitly claimed sjt. If a thread attempts to execute a synchronized method or synchronized statement and is unable to acquire an object’s lock, it enters the waiting state until the lock becomes available.

Question 101.
What do you understand by Synchronization?
Or
What is synchronization and why is it important?
Or
Describe synchronization in respect to multithreading?
Or
What is synchronization?
Answer: With respect to multithreading, Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access a particular resource at a time. In non synchronized multithreaded application, it is possible for one thread to modify a shared object while another thread is in the process of using or updating the object’s value. Synchronization prevents such type of data corruption which may otherwise lead to dirty reads and significant errors.

E.g. synchronizing a function:
public synchronized void Methodl ( ) {
// method code.
}
E.g. synchronizing a block of code inside a function:
public Method2 ( ){
synchronized (this) {
// synchronized code here.
}
}

Question 102.
When you will synchronize a piece of your code?
Answer:
When you expect that your shared code will be accessed by different threads and these threads may change a particular data causing data corruption, then they are placed in a synchronized construct or a synchronized method.