174.129.160.22174.129.160.22/williamdengtechref/java multi-threading questions...  · web...

26

Click here to load reader

Upload: lynga

Post on 16-Dec-2018

218 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 174.129.160.22174.129.160.22/WilliamDengTechRef/Java Multi-Threading Questions...  · Web viewBlockingQueue interface is part of java ... allocating and de ... When a method or block

Java Multi-Threading Questions Answers1. What is the difference between Process and Thread?

A process is a self contained execution environment and it can be seen as a program or application whereas Thread is a single task of execution within the process. Java runtime environment runs as a single process which contains different classes and programs as processes. Thread can be called lightweight process. Thread requires less resources to create and exists in the process, thread shares the process resources.

2. What are the benefits of multi-threaded programming?In Multi-Threaded programming, multiple threads are executing concurrently that improves the performance because CPU is not idle incase 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 Servlet support multi-threading but CGI doesn’t.

3. What is difference between user Thread and daemon Thread?When we create a Thread in java program, it’s known as user thread. A daemon thread runs in 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 daemon thread is also a daemon thread.

4. How can we create a Thread in Java?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.

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

6. Can we call run() method of a Thread class?Yes, we can call run() method of a Thread class but then it will behave like a normal method. To actually execute it in a Thread, we need to start it usingThread.start() method.

7. How can we pause the execution of a Thread for specific time?We can use Thread class sleep() method to pause the execution of Thread for certain time. Note that this will not stop the processing of thread for specific time, once the thread awake from sleep, it’s state gets changed to runnable and based on thread scheduling, it gets executed.

8. What do you understand about Thread Priority?Every thread has a priority, usually higher priority thread gets precedence in execution but it depends on Thread Scheduler implementation that is OS dependent. We can specify the priority of thread but it doesn’t guarantee that higher priority thread will get executed before lower priority thread. Thread priority is an int whose value varies from 1, 5 to 10 where 1 is the lowest priority thread and 10 is the highest priority thread.

9. What is Thread Scheduler and Time Slicing?Thread Scheduler is the Operating System service that allocates the CPU time 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.

10. What is context-switching in multi-threading?Context Switching is the process of storing and restoring of CPU state so that Thread execution can be resumed from the same point at a later point of time. Context Switching is the essential feature for multitasking operating system and support for multi-threaded environment.

11. How can we make sure main() is the last thread to finish in Java Program?We can use Thread join() method to make sure all the threads created by the program is dead before finishing the main function. Here is an article about Thread join method.

12. How does thread communicate with each other?When threads share resources, communication between Threads is important to coordinate their efforts. Object class wait(), notify() and notifyAll() methods allows threads to communicate about the lock status of a resource. Check this post to learn more about thread wait, notify and notifyAll.

13. Why thread communication methods wait(), notify() and notifyAll() are in Object class?In Java every Object has a monitor and wait, notify methods are used to wait for the Object monitor or to notify other threads that Object monitor is free now. There is no monitor on threads in java and synchronization can be used with any Object, that’s why it’s part of Object class so that every class in java has these essential methods for inter thread communication.

14. Why wait(), notify() and notifyAll() methods have to be called from synchronized method or block?When a Thread calls wait() on any Object, it must have the monitor on the Object that it will leave and goes in wait state until any other thread call notify() on this Object. Similarly when a thread calls notify() on any Object, it leaves the monitor on the

Page 2: 174.129.160.22174.129.160.22/WilliamDengTechRef/Java Multi-Threading Questions...  · Web viewBlockingQueue interface is part of java ... allocating and de ... When a method or block

Object and other waiting threads can get the monitor on the Object. Since all these methods require Thread to have the Object monitor, that can be achieved only by synchronization, they need to be called from synchronized method or block.

15. How can we achieve thread safety in Java?There are several ways to achieve thread safety in java – synchronization, atomic concurrent classes, implementing concurrent Lock interface, using volatile keyword, using immutable classes and Thread safe classes. Learn more at thread safety tutorial.

16. What is volatile keyword in JavaWhen we use volatile keyword with a variable, all the threads read it’s value directly from the memory and don’t cache it. This makes sure that the value read is the same as in the memory.

17. Which is more preferred – Synchronized method or Synchronized block?Synchronized block is more preferred way because it doesn’t lock the Object, synchronized methods lock the Object and if there are multiple synchronization blocks in the class, even though they are not related, it will stop them from execution and put them in wait state to get the lock on Object.

18. How to create daemon thread in Java?Thread class setDaemon(true) can be used to create daemon thread in java. We need to call this method before calling start() method else it will throw IllegalThreadStateException.

19. What is ThreadLocal?Java ThreadLocal is used to create thread-local variables. We know that all threads of an Object share it’s variables, so if the variable is not thread safe, we can use synchronization but if we want to avoid synchronization, we can use ThreadLocal variables.Every thread has it’s own ThreadLocal variable and they can use it’s get() and set() methods to get the default value or change it’s value local to Thread. ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread. Check this post for small example program showing ThreadLocal Example.

20. What is Thread Group? Why it’s advised not to use it?ThreadGroup is a class which was intended to provide information about a thread group. ThreadGroup API is weak and it doesn’t have any functionality that is not provided by Thread. Two of the major feature it had are to get the list of active threads in a thread group and to set the uncaught exception handler for the thread. But Java 1.5 has addedsetUncaughtExceptionHandler(UncaughtExceptionHandler eh) method using which we can add uncaught exception handler to the thread. So ThreadGroup is obsolete and hence not advised to use anymore.12345678

t1.setUncaughtExceptionHandler(new UncaughtExceptionHandler(){ @Override public void uncaughtException(Thread t, Throwable e) { System.out.println("exception occured:"+e.getMessage()); } });

21. What is Java Thread Dump, How can we get Java Thread dump of a Program?Thread dump is list of all the threads active in the JVM, thread dumps are very helpful in analyzing bottlenecks in the application and analyzing deadlock situations. There are many ways using which we can generate Thread dump – Using Profiler, Kill -3 command, /java/bin/jstack tool etc. I prefer jstack tool to generate thread dump of a program because it’s easy to use and comes with JDK installation. Since it’s a terminal based tool, we can create script to generate thread dump at regular intervals to analyze it later on. Read this post to know more about generating thread dump in java.

22. What is Deadlock? How to analyze and avoid deadlock situation?Deadlock is a programming situation where two or more threads are blocked forever, this situation arises with at least two threads and two or more resources.To analyze a deadlock, we need to look at the java thread dump of the application, we need to look out for the threads with state as BLOCKED and then the resources it’s waiting to lock, every resource has a unique ID using which we can find which thread is already holding the lock on the object.Avoid Nested Locks, Lock Only What is Required and Avoid waiting indefinitely are common ways to avoid deadlock situation, read this post to learn how to analyze deadlock in java with sample program.

23. What is Java Timer Class? How to schedule a task to run after specific interval?java.util.Timer is a utility class that can be used to schedule a thread to be executed at certain time in future. Java Timer class can be used to schedule a task to be run one-time or to be run at regular intervals.java.util.TimerTask is an abstract class that implements Runnable interface and we need to extend this class to create our own TimerTask that can be scheduled using java Timer class.Check this post for java Timer example.

24. What is Thread Pool? How can we create Thread Pool in Java?A thread pool manages the pool of worker threads, it contains a queue that keeps tasks waiting to get executed.

Page 3: 174.129.160.22174.129.160.22/WilliamDengTechRef/Java Multi-Threading Questions...  · Web viewBlockingQueue interface is part of java ... allocating and de ... When a method or block

A thread pool manages the collection of Runnable threads and worker threads execute Runnable from the queue.java.util.concurrent.Executors provide implementation of java.util.concurrent.Executor interface to create the thread pool in java. Thread Pool Example program shows how to create and use Thread Pool in java.

Java Concurrency Interview Questions Answers1. What is atomic operation? What are atomic classes in Java Concurrency API?

Atomic operations are performed in a single unit of task without interference from other operations. Atomic operations are necessity in multi-threaded environment to avoid data inconsistency.int++ is not an atomic operation. So by the time one threads read it’s value and increment it by one, other thread has read the older value leading to 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 usage of Synchronization. Go to this article to learn more about atomic concurrent classes.

2. What is Lock interface in Java Concurrency API? What are it’s benefits over synchronization?Lock interface provide 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

3. What is Executors Framework?In Java 5, 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 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 process of creating Thread pools in java. Check out this post to learn with example code to create thread pool using Executors framework.

4. What is BlockingQueue? How can we implement Producer-Consumer problem using Blocking Queue?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 java collections framework and it’s primarily used for implementing producer consumer problem.Check this post for producer-consumer problem implementation using BlockingQueue.

5. What is Callable and Future?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.Callable interface use Generic to define the return type of Object. Executors class provide 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.Check this post for Callable Future Example.

6. What are Concurrent Collection Classes?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.

7. What is Executors Class?Executors class provide utility methods for Executor, ExecutorService, ScheduledExecutorService, ThreadFactory, and Callable classes.

Page 4: 174.129.160.22174.129.160.22/WilliamDengTechRef/Java Multi-Threading Questions...  · Web viewBlockingQueue interface is part of java ... allocating and de ... When a method or block

Executors class can be used to easily create Thread Pool in java, also this is the only class supporting execution of Callable implementations.

What is synchronization in respect to multi-threading in Java?With respect to multi-threading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one Java thread to modify a shared variable while another thread is in the process of using or updating same shared variable. This usually leads to erroneous behavior or program.Explain different way of using thread?A Java thread could be implemented by using Runnable interface or by extending the Thread class. The Runnable is more advantageous, when you are going for multiple inheritance. What is the difference between Thread.start() & Thread.run() method?Thread.start() method (native method) of Thread class actually does the job of running the Thread.run() method in a thread. If we directly call Thread.run() method it will executed in same thread, so does not solve the purpose of creating a new thread.Why do we need run() & start() method both. Can we achieve it with only run method?We need run() & start() method both because JVM needs to create a separate thread which can not be differentiated from a normal method call. So this job is done by start method native implementation which has to be explicitly called. Another advantage of having these two methods is we can have any object run as a thread if it implements Runnable interface. This is to avoid Java’s multiple inheritance problems which will make it difficult to inherit another class with Thread. What is ThreadLocal class? How can it be used?Below are some key points about ThreadLocal variables A thread-local variable effectively provides a separate copy of its value for each thread that uses it. ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread In case when multiple threads access a ThreadLocal instance, separate copy of Threadlocal variable is maintained for each thread. Common use is seen in DAO pattern where the DAO class can be singleton but the Database connection can be maintained separately for each thread. (Per Thread Singleton)ThreadLocal variable are difficult to understand and I have found below reference links very useful in getting better understanding on them Good article on ThreadLocal on IBM DeveloperWorks Managing data : Good example Refer Java API Docs When InvalidMonitorStateException is thrown? Why?This exception is thrown when you try to call wait()/notify()/notifyAll() any of these methods for an Object from a point in your program where u are NOT having a lock on that object.(i.e. u r not executing any synchronized block/method of that object and still trying to call wait()/notify()/notifyAll()) wait(), notify() and notifyAll() all throw IllegalMonitorStateException. since This exception is a subclass of RuntimeException so we r not bound to catch it (although u may if u want to). and being a RuntimeException this exception is not mentioned in the signature of wait(), notify(), notifyAll() methods.What is the difference between sleep(), suspend() and wait() ?Thread.sleep() takes the current thread to a "Not Runnable" state for specified amount of time. The thread holds the monitors it has acquired. For example, if a thread is running a synchronized block or method and sleep method is called then no other thread will be able to enter this block or method. The sleeping thread can wake up when some other thread calls t.interrupt on it. Note that sleep is a static method, that means it always affects the current thread (the one executing sleep method). A common mistake is trying to call t2.sleep() where t2 is a different thread; even then, it is the current thread that will sleep, not the t2 thread. thread.suspend() is deprecated method. Its possible to send other threads into suspended state by making a suspend method call. In suspended state a thread keeps all its monitors and can not be interrupted. This may

Page 5: 174.129.160.22174.129.160.22/WilliamDengTechRef/Java Multi-Threading Questions...  · Web viewBlockingQueue interface is part of java ... allocating and de ... When a method or block

cause deadlocks therefore it has been deprecated. object.wait() call also takes the current thread into a "Not Runnable" state, just like sleep(), but with a slight change. Wait method is invoked on a lock object, not thread. 

Here is the sequence of operations you can think  A thread T1 is already running a synchronized block with a lock on object - lets say "lockObject" Another thread T2 comes to execute the synchronized block and find that its already acquired. Now T2 calls lockObject.wait() method for waiting on lock to be release by T1 thread. T1 thread finishes all its synchronized block work. T1 thread calls lockObject.notifyAll() to notify all waiting threads that its done using the lock. Since T2 thread is first in the queue of waiting it acquires the lock and starts processing.

What happens when I make a static method as synchronized?Synchronized static methods have a lock on the class "Class", so when a thread enters a synchronized static method, the class itself gets locked by the thread monitor and no other thread can enter any static synchronized methods on that class. This is unlike instance methods, as multiple threads can access " same synchronized instance methods " at same time for different instances .

Can a thread call a non-synchronized instance method of an Object when a synchronized method is being executed ?Yes, a Non synchronized method can always be called without any problem. In fact Java does not do any check for a non-synchronized method. The Lock object check is performed only for synchronized methods/blocks. In case the method is not declared synchronized Jave will call even if you are playing with shared data. So you have to be careful while doing such thing. The decision of declaring a method as synchronized has to be based on critical section access. If your method does not access a critical section (shared resource or data structure) it need not be declared synchronized. Below is the example which demonstrates this, The Common class has two methods synchronizedMethod1() and method1() MyThread class is calling both the methods in separate threads,1. public class Common {  2.   3. public synchronized void synchronizedMethod1() {  4. System.out.println("synchronizedMethod1 called");  5. try {  6. Thread.sleep(1000);  7. } catch (InterruptedException e) {  8. e.printStackTrace();  9. }  10. System.out.println("synchronizedMethod1 done");  11. }  12. public void method1() {  13. System.out.println("Method 1 called");  14. try {  15. Thread.sleep(1000);  16. } catch (InterruptedException e) {  17. e.printStackTrace();  18. }  19. System.out.println("Method 1 done");  20. }  21. }  view plain print ? 1. public class MyThread extends Thread {  2. private int id = 0;  3. private Common common;  4.   5. public MyThread(String name, int no, Common object) {  6. super(name);  7. common = object;  8. id = no;  9. }  10.   11. public void run() {  12. System.out.println("Running Thread" + this.getName());  13. try {  14. if (id == 0) {  15. common.synchronizedMethod1();  

Page 6: 174.129.160.22174.129.160.22/WilliamDengTechRef/Java Multi-Threading Questions...  · Web viewBlockingQueue interface is part of java ... allocating and de ... When a method or block

16. } else {  17. common.method1();  18. }  19. } catch (Exception e) {  20. e.printStackTrace();  21. }  22. }  23.   24. public static void main(String[] args) {  25. Common c = new Common();  26. MyThread t1 = new MyThread("MyThread-1", 0, c);  27. MyThread t2 = new MyThread("MyThread-2", 1, c);  28. t1.start();  29. t2.start();  30. }  31. }  Here is the output of the programview plain print ? 1. Running ThreadMyThread-1  2. synchronizedMethod1 called  3. Running ThreadMyThread-2  4. Method 1 called  5. synchronizedMethod1 done  6. Method 1 done  This shows that method1() - is called even though the synchronizedMethod1() was in execution. 

Can two threads call two different synchronized instance methods of an Object instance?No. If an object has synchronized instance methods then the Object itself is used a lock object for controlling the synchronization. Therefore all other instance methods need to wait until previous method call is completed. See the below sample code which demonstrate it very clearly. The Class Common has 2 methods called synchronizedMethod1() and synchronizedMethod2() MyThread class is calling both the methods1. public class Common {  2. public synchronized void synchronizedMethod1() {  3. System.out.println("synchronizedMethod1 called");  4. try {  5. Thread.sleep(1000);  6. } catch (InterruptedException e) {  7. e.printStackTrace();  8. }  9. System.out.println("synchronizedMethod1 done");  10. }  11.   12. public synchronized void synchronizedMethod2() {  13. System.out.println("synchronizedMethod2 called");  14. try {  15. Thread.sleep(1000);  16. } catch (InterruptedException e) {  17. e.printStackTrace();  18. }  19. System.out.println("synchronizedMethod2 done");  20. }  21. }  view plain print ? 1. public class MyThread extends Thread {  2. private int id = 0;  3. private Common common;  4.   5. public MyThread(String name, int no, Common object) {  6. super(name);  7. common = object;  8. id = no;  9. }  10.   11. public void run() {  12. System.out.println("Running Thread" + this.getName());  13. try {  14. if (id == 0) {  15. common.synchronizedMethod1();  16. } else {  17. common.synchronizedMethod2();  

Page 7: 174.129.160.22174.129.160.22/WilliamDengTechRef/Java Multi-Threading Questions...  · Web viewBlockingQueue interface is part of java ... allocating and de ... When a method or block

18. }  19. } catch (Exception e) {  20. e.printStackTrace();  21. }  22. }  23.   24. public static void main(String[] args) {  25. Common c = new Common();  26. MyThread t1 = new MyThread("MyThread-1", 0, c);  27. MyThread t2 = new MyThread("MyThread-2", 1, c);  28. t1.start();  29. t2.start();  30. }  31. }  

What is a deadlock?Deadlock is a situation where two or more threads are blocked forever, waiting for each other. This may occur when two threads, each having a lock on one resource, attempt to acquire a lock on the other's resource. Each thread would wait indefinitely for the other to release the lock, unless one of the user processes is terminated. In terms of Java API, thread deadlock can occur in following conditions: When two threads call Thread.join() on each other. When two threads use nested synchronized blocks to lock two objects and the blocks lock the same objects in different order.

What is Starvation? and What is a Livelock?Starvation and livelock are much less common a problem than deadlock, but are still problems that every designer of concurrent software is likely to encounter.LiveLockLivelock occurs when all threads are blocked, or are otherwise unable to proceed due to unavailability of required resources, and the non-existence of any unblocked thread to make those resources available. In terms of Java API, thread livelock can occur in following conditions: When all the threads in a program execute Object.wait(0) on an object with zero parameter. The program is live-locked and cannot proceed until one or more threads call Object.notify() or Object.notifyAll() on the relevant objects. Because all the threads are blocked, neither call can be made. When all the threads in a program are stuck in infinite loops.StarvationStarvation describes a situation where a thread is unable to gain regular access to shared resources and is unable to make progress. This happens when shared resources are made unavailable for long periods by "greedy" threads. For example, suppose an object provides a synchronized method that often takes a long time to return. If one thread invokes this method frequently, other threads that also need frequent synchronized access to the same object will often be blocked. Starvation occurs when one thread cannot access the CPU because one or more other threads are monopolizing the CPU. In Java, thread starvation can be caused by setting thread priorities inappropriately. A lower-priority thread can be starved by higher-priority threads if the higher-priority threads do not yield control of the CPU from time to time.

How to find a deadlock has occurred in Java? How to detect a Deadlock in Java?Since JDK 1.5 there are some powerful methods added in the java.lang.management package to diagnose and detect deadlocks. The java.lang.management.ThreadMXBean interface is management interface for the thread system of the Java virtual machine. It has two methods which can leveraged to detect deadlock in a Java application. findMonitorDeadlockedThreads() - This method can be used to detect cycles of threads that are in deadlock waiting to acquire object monitors. It returns an array of thread IDs that are deadlocked waiting on monitor.

Page 8: 174.129.160.22174.129.160.22/WilliamDengTechRef/Java Multi-Threading Questions...  · Web viewBlockingQueue interface is part of java ... allocating and de ... When a method or block

findDeadlockedThreads() - It returns an array of thread IDs that are deadlocked waiting on monitor or ownable synchronizers.

What is immutable object? How does it help in writing concurrent application? An object is considered immutable if its state cannot change after it is constructed. Maximum reliance on immutable objects is widely accepted as a sound strategy for creating simple, reliable code. Immutable objects are particularly useful in concurrent applications. Since they cannot change state, they cannot be corrupted by thread interference or observed in an inconsistent state. Examples of immutable objects from the JDK include String and Integer. Immutable objects greatly simplify your multi threaded program, since they are Simple to construct, test, and use. – no Setter methods. Automatically thread-safe and have no synchronization issues.To create a object immutable You need to make the class final and all its member final so that once objects gets created no one can modify its state. You can achieve same functionality by making member as non final but private and not modifying them except in constructor.Implement update() / change() / insert() methods to create NEW instance of same immutable object.

How will you take thread dump in Java? How will you analyze Thread dump?A Thread Dump is a complete list of active threads. A java thread dump is a way of finding out what each thread in the JVM is doing at a particular point of time. This is especially useful when your java application seems to have some performance issues. Thread dump will help you to find out which thread is causing this. There are several ways to take thread dumps from a JVM. It is highly recommended to take more than 1 thread dump and analyze the results based on it. Follow below steps to take thread dump of a java processOn UNIX, Linux and Mac OSX Environment run below command: ps -el | grep java Use jstack command to print the Java stack traces for a given Java process PID jstack [PID] More details of jstack command can be found here : JSTACK Command Manual 

What is a thread leak? What does it mean in Java?Thread leak is when an application does not release references to a thread object properly. Due to this some Threads do not get garbage collected and the number of unused threads grow with time. Thread leak can often cause serious issues on a Java application since over a period of time too many threads will be created but not released and may cause applications to respond slow or hang. 

How can I trace whether the application has a thread leak?If an application has thread leak then with time it will have too many unused threads. Try to find out what type of threads is leaking out. This can be done using following ways Give unique and descriptive names to the threads created in application. - Add log entry in all thread at various entry and exit points in threads. Change debugging config levels (debug, info, error etc) and analyze log messages. When you find the class that is leaking out threads check how new threads are instantiated and how they're closed. Make sure the thread is Guaranteed to close properly by doing following

-Handling all Exceptions properly.-Releasing all resources (e.g. connections, files etc) before it closes.

What is thread pool? Why should we use thread pools?A thread pool is a collection of threads on which task can be scheduled. Instead of creating a new thread for each task, you can have one of the threads from the thread pool pulled out of the pool and assigned to the task. When the thread is finished with the task, it adds itself back to the pool and waits for another assignment. One common type of thread pool is the fixed thread pool. This type of pool always has a specified number of threads running; if a thread is somehow terminated while it is still in use, it is automatically replaced with a new thread. Below are key reasons to use a Thread Pool

Page 9: 174.129.160.22174.129.160.22/WilliamDengTechRef/Java Multi-Threading Questions...  · Web viewBlockingQueue interface is part of java ... allocating and de ... When a method or block

Using thread pools minimizes the JVM overhead of thread creation. Thread objects use a significant amount of memory, and in a large-scale application, allocating and de-allocating many thread objects creates a significant memory management overhead. You have control over the maximum number of tasks that are being processed in parallel (= number of threads in the pool).Most of the executor implementations in java.util.concurrent use thread pools, which consist of worker threads. This kind of thread exists separately from the Runnable and Callable tasks it executes and is often used to execute multiple tasks. 

Can we synchronize the run method? If yes then what will be the behavior?Yes, the run method of a runnable class can be synchronized. If you make run method synchronized then the lock on runnable object will be occupied before executing the run method. In case we start multiple threads using the same runnable object in the constructor of the Thread then it would work. But until the 1st thread ends the 2nd thread cannot start and until the 2nd thread ends the next cannot start as all the threads depend on lock on same object

Can we synchronize the constructor of a Java Class?As per Java Language Specification, constructors cannot be synchronized because other threads cannot see the object being created before the thread creating it has finished it. There is no practical need of a Java Objects constructor to be synchronized, since it would lock the object being constructed, which is normally not available to other threads until all constructors of the object finish

Q. What is the difference between processes and threads? A. A process is an execution of a program but a thread is a single execution sequence within the process. A process can contain multiple threads. A thread is sometimes called a lightweight process. 

A JVM runs in a single process and threads in a JVM share the heap belonging to that process. That is why several threads may access the same object. Threads share the heap and have their own stack space. This is how one thread’s invocation of a method and its local variables are kept thread safe from other threads. But the heap is not thread-safe and must be synchronized for thread safety

Q. Briefly explain high-level thread states? A. The state chart diagram below describes the thread states.

Page 10: 174.129.160.22174.129.160.22/WilliamDengTechRef/Java Multi-Threading Questions...  · Web viewBlockingQueue interface is part of java ... allocating and de ... When a method or block

Runnable — A thread becomes runnable when you call the start( ), but does  not necessarily start running immediately.  It will be pooled waiting for its turn to be picked for execution by the thread scheduler based on thread priorities. ?

12

MyThread aThread = new MyThread();aThread.start();                   //becomes runnable

Running: The processor is actively executing the thread code. It runs until it becomes blocked, or voluntarily gives up its turn with this static method Thread.yield( ). Because of context switching overhead, yield( ) should not be used very frequently

Waiting: A thread is in a blocked state while it waits for some external processing such as file I/O to finish.A call to currObject.wait( ) method causes the current thread to wait until some other thread invokescurrObject.notify( ) or the currObject.notifyAll( ) is executed.

Sleeping: Java threads are forcibly put to sleep (suspended) with this overloaded method: Thread.sleep(milliseconds), Thread.sleep(milliseconds, nanoseconds);

Blocked on I/O: Will move to runnable after I/O condition like reading bytes of data etc changes.

Blocked on synchronization: will move to running when a lock is acquired. 

Dead: The thread is finished working.

Thread.State enumeration contains the possible states of a Java thread in the underlying JVM. These thread states are possible due to Java's following thread concepts: The objects can be shared and modified (i.e. if mutable) by any threads.

The preemptive nature of the thread scheduler can swap threads on and off cores in a multi-core CPU machine at any time.

This means the methods can be swapped out while they are running. Otherwise a method in an infinite loop will clog the CPU forever leaving the other methods on different threads to starve. 

To prevent thread safety issues, the methods and block of code that has vulnerable data can be locked. 

This enables the threads to be in locked or waiting to acquire a lock states. 

The threads also get into the waiting state for I/O resources like sockets, file handles, and database connections. 

The threads that are performing I/O read/write operations can not be swapped. Hence, they need to either complete to the finished state with success/failure or another thread must close the socket for it to get to the state of dead or finished. This is why proper service timeout values are necessary to prevent the thread to get blocked for ever in an I/O operation, causing performance issues. 

Page 11: 174.129.160.22174.129.160.22/WilliamDengTechRef/Java Multi-Threading Questions...  · Web viewBlockingQueue interface is part of java ... allocating and de ... When a method or block

The threads can be put to sleep to give other threads in waiting state an opportunity to execute.

Q. Why is locking of a method or block of code for thread safety is called "synchronized" and not "lock" or "locked"?A. When a method or block of code is locked with the reserved "synchronized" key word in Java, the memory (i.e. heap) where the shared data is kept is synchronized. This means, When a synchronized block or method is entered after the lock has been acquired by a thread, it first reads any changes to the locked object from the main heap memory to ensure that the thread that has the lock has the current info before start executing.

After the synchronized  block has completed and the thread is ready to relinquish the lock, all the changes that were made to the object that was locked is written or flushed back to the main heap memory so that the other threads that acquire the lock next has the current info.

This is why it is called "synchronized" and not "locked". This is also the reason why the immutable objects are inherently thread-safe and does not require any synchronization. Once created, the immutable objects cannot be modified.

Q. How does thread synchronization occurs inside a monitor? What levels of synchronization can you apply? What is the difference between synchronized method and synchronized block? A. In Java programming, each object has a lock. A thread can acquire the lock for an object by using the synchronized keyword. The synchronized keyword can be applied in method level (coarse grained lock – can affect performance adversely) or block level of code (fine grained lock). Often using a lock on a method level is too coarse. Why lock up a piece of code that does not access any shared resources by locking up an entire method. Since each object has a lock, dummy objects can be created to implement block level synchronization. The block level is more efficient because it does not lock the whole method. 

The JVM uses locks in conjunction with monitors. A monitor is basically a guardian who watches over a sequence of synchronized code and making sure only one thread at a time executes a synchronized piece of code. Each monitor is associated with an object reference. When a thread arrives at the first instruction in a block of code it must obtain a lock on the referenced object. The thread is not allowed to execute the code until it obtains the lock. Once it has

Page 12: 174.129.160.22174.129.160.22/WilliamDengTechRef/Java Multi-Threading Questions...  · Web viewBlockingQueue interface is part of java ... allocating and de ... When a method or block

obtained the lock, the thread enters the block of protected code. When the thread leaves the block, no matter how it leaves the block, it releases the lock on the associated object. For static methods, you acquire a class level lock. 

Page 13: 174.129.160.22174.129.160.22/WilliamDengTechRef/Java Multi-Threading Questions...  · Web viewBlockingQueue interface is part of java ... allocating and de ... When a method or block

Q. Explain how you would get a Thread Deadlock with a code example?A. The example below causes a deadlock situation by thread-1 waiting for lock2 and thread-0 waiting for lock1.

?12345678910111213

package deadlock; public class DeadlockTest extends Thread {     public static Object lock1 = new Object();    public static Object lock2 = new Object();     public void method1() {        synchronized (lock1) {            delay(500);  //some operation            System.out.println("method1: " + Thread.currentThread().getName());            synchronized (lock2) {                System.out.println("method1 is executing .... ");            }        }

Page 14: 174.129.160.22174.129.160.22/WilliamDengTechRef/Java Multi-Threading Questions...  · Web viewBlockingQueue interface is part of java ... allocating and de ... When a method or block

1415161718192021222324252627282930313233343536373839404142434445464748495051525354

    }     public void method2() {        synchronized (lock2) {            delay(500);   //some operation            System.out.println("method1: " + Thread.currentThread().getName());            synchronized (lock1) {                System.out.println("method2 is executing .... ");            }        }    }     @Override    public void run() {        method1();        method2();    }     public static void main(String[] args) {        DeadlockTest thread1 = new DeadlockTest();        DeadlockTest thread2 = new DeadlockTest();         thread1.start();        thread2.start();    }     /**     * The delay is to simulate some real operation happening.     * @param timeInMillis     */    private void delay(long timeInMillis) {        try {            Thread.sleep(timeInMillis);        } catch (InterruptedException e) {            e.printStackTrace();        }    } }

The output will be something like:

?12345

method1: Thread-0method1 is executing .... method2: Thread-0method1: Thread-1---deadlock ----- can't proceed further

Page 15: 174.129.160.22174.129.160.22/WilliamDengTechRef/Java Multi-Threading Questions...  · Web viewBlockingQueue interface is part of java ... allocating and de ... When a method or block

Q. What happens if you restart a thread that has already started?A. You will get the following exception

?123

Exception in thread "main" java.lang.<b>IllegalThreadStateException</b> at java.lang.Thread.start(Thread.java:595) at deadlock.DeadlockTest.main(DeadlockTest.java:38)

Q. Can you write a program with 2  threads, in which one prints odd numbers and the other prints even numbers up to 10?A. In Java, you can use wait(  ) and notifyAll(  ) to communicate between threads. The code below demonstrates that.

Firstly, create the thread classes and the main method that creates the thread and run it.

?1234567

package multithreading; public class NumberGenerator extends Thread {     private NumberUtility numberUtility;    private int maxNumber;    private boolean isEvenNumber;     

Page 16: 174.129.160.22174.129.160.22/WilliamDengTechRef/Java Multi-Threading Questions...  · Web viewBlockingQueue interface is part of java ... allocating and de ... When a method or block

891011121314151617181920212223242526272829303132333435363738394041424344

     public NumberGenerator(NumberUtility numberUtility, int maxNumber, boolean isEvenNumber) {        this.numberUtility = numberUtility;        this.maxNumber = maxNumber;        this.isEvenNumber = isEvenNumber;    }     public void run() {        int i = isEvenNumber == true ? 2 : 1;        while (i <= maxNumber) {            if(isEvenNumber == true) {                numberUtility.printEven(i);            }            else {                numberUtility.printOdd(i);                }                         i = i + 2;        }    }              public static void main(String[] args) {        NumberUtility numUtility = new NumberUtility(); //single instance shared by oddGen and evenGen threads        final int MAX_NUM = 10;          //create 2 threads, one to generate odd numbers and the other to generate even numbers        NumberGenerator oddGen = new NumberGenerator(numUtility, MAX_NUM, false);        NumberGenerator evenGen = new NumberGenerator(numUtility, MAX_NUM, true);                 oddGen.start();  //start the thread - invokes the run() method on NumberGenerator        evenGen.start(); //start the thread - invokes the run() method on NumberGenerator             } }

Next, create the utility class that is used for communicating between the two threads with wait() and notifyAll() methods via synchronized methods.

?123456789

package multithreading; import static java.lang.System.out; public class NumberUtility {     boolean oddPrinted = false;     public synchronized void printOdd(int number) { 

Page 17: 174.129.160.22174.129.160.22/WilliamDengTechRef/Java Multi-Threading Questions...  · Web viewBlockingQueue interface is part of java ... allocating and de ... When a method or block

10111213141516171819202122232425262728293031323334353637383940

        while (oddPrinted == true) {            try {                wait();   // waits until notified by even thread             } catch (InterruptedException e) {                e.printStackTrace();            }        }         out.println("printOdd() " + number);        oddPrinted = true;        notifyAll();  //notify all waiting threads     }     public synchronized void printEven(int number) {        while (oddPrinted == false) {            try {                wait();  //waits until notified by the odd thread             } catch (InterruptedException e) {             }        }         oddPrinted = false;        out.println("printEven() " + number);        notifyAll();  //notify all waiting threads    }}

The output will be something like

?12345678910

printOdd() 1printEven() 2printOdd() 3printEven() 4printOdd() 5printEven() 6printOdd() 7printEven() 8printOdd() 9printEven() 10 

Note: This a typical example of splitting tasks among threads. A method calls notify/notifyAll( ) as the last thing it does (besides return). Since the printOdd( ) and printEven( ) methods were void, the notifyAll( ) was the last statement. If it were to return some value, the notifyAll( ) would have been placed just before the return statement.

Q. Write a multi-threaded Java program in which, one thread generates odd numbers and write to a pipe and the

Page 18: 174.129.160.22174.129.160.22/WilliamDengTechRef/Java Multi-Threading Questions...  · Web viewBlockingQueue interface is part of java ... allocating and de ... When a method or block

second thread generates even numbers and write to another pipe, and a third thread receives the numbers from both the pipes and evaluates if the sum is multiples of 5?

A. In Unix, a pipe (“|”) operator helps you to redirect output from one command to another. PipedReader and PipedWriterclasses in java.io package helps you to do the same. It helps you to redirect the read input into writer seamlessly. In Unix, two different processes on different address spaces can communicate using pipe, but in java two threads on the JVM can communicate using Piped ByteStream/CharacterStream within the same process (i.e same address space)

Here is the code snippet. The Writer threads responsible for writing odd and even numbers to the respective pipes.

?123456789

package multithreading; import java.io.IOException;import java.io.PipedWriter; public class NumberWriter extends Thread {     private PipedWriter writer;    private int maxNumber;    private boolean isEvenNumber;

Page 19: 174.129.160.22174.129.160.22/WilliamDengTechRef/Java Multi-Threading Questions...  · Web viewBlockingQueue interface is part of java ... allocating and de ... When a method or block

1011121314151617181920212223242526272829303132333435363738394041424344454647484950

     public NumberWriter(PipedWriter writer, int maxNumber, boolean isEvenNumber) {        this.writer = writer;        this.maxNumber = maxNumber;        this.isEvenNumber = isEvenNumber;    }     public void run() {        int i = 1;        while (i <= maxNumber) {            try {                if (isEvenNumber && (i % 2) == 0) {                    writer.write(i);                } else if (!isEvenNumber && i%2 != 0) {                    writer.write(i);                }                ++i;            } catch (IOException e) {                e.printStackTrace();            }        }    }     public static void main(String[] args) {        final int MAX_NUM = 10;         PipedWriter oddNumberWriter = new PipedWriter();        PipedWriter evenNumberWriter = new PipedWriter();         NumberWriter oddGen = new NumberWriter(oddNumberWriter, MAX_NUM, false);        NumberWriter evenGen = new NumberWriter(evenNumberWriter, MAX_NUM, true);        NumberReceiver receiver = new NumberReceiver(oddNumberWriter, evenNumberWriter);         oddGen.start();        evenGen.start();        receiver.start();     } }

The receiver thread that listens to both odd and even number pipes and computes the sum. If the sum is a multiple of 5, it prints the numbers and the sum.

?12345

package multithreading; import java.io.IOException;import java.io.PipedReader;import java.io.PipedWriter; 

Page 20: 174.129.160.22174.129.160.22/WilliamDengTechRef/Java Multi-Threading Questions...  · Web viewBlockingQueue interface is part of java ... allocating and de ... When a method or block

678910111213141516171819202122232425262728293031323334353637383940

public class NumberReceiver extends Thread {     private PipedReader oddReader;    private PipedReader evenReader;     public NumberReceiver(PipedWriter oddWriter, PipedWriter evenWriter) {        try {            this.oddReader = new PipedReader(oddWriter);            this.evenReader = new PipedReader(evenWriter);        } catch (IOException e) {            e.printStackTrace();        }    }     public void run() {        int odd =0, even=0;                 try {            while (odd != -1) {                odd = oddReader.read();                even = evenReader.read();                                 if ((odd + even) % 5 == 0) {                    System.out.println("match found " + odd + " + " + even + " = " + (odd + even));                }            }                        } catch (IOException e) {            System.exit(1);        }                     }}

The output will be something like

?1 match found 7 + 8 = 15