Sat 1/6/2018. MULTITHREAD... 5 THREADS What do you mean by Multithreaded program?... 5 LIFE CYCLE OF A THREAD:... 5

Size: px
Start display at page:

Download "Sat 1/6/2018. MULTITHREAD... 5 THREADS What do you mean by Multithreaded program?... 5 LIFE CYCLE OF A THREAD:... 5"

Transcription

1 MULTITHREAD... 5 THREADS What do you mean by Multithreaded program?... 5 LIFE CYCLE OF A THREAD:... 5 THREAD METHODS: Implement Runnable method Example: class which extends Thread class: makes use of above defined classes:... 7 THREAD PRIORITIES: MIN_PRIORITY (a constant of and MAX_PRIORITY (a constant of 10) What are the two ways to implement and create a running thread? Summary Java Thread by Extending from the Thread class Implementing Runnable INTERFACE : Difference between Runnable and Callable INTERFACE in Java? Execution Mechanism Return Values With Runnable With Callable Exception Handling With Runnable With Callable Explain the available thread states in a high-level. During its execution, a thread can reside in one of the following states: Difference between "implements Runnable" and "extends Thread" in Java When to use "extends Thread" over "implements Runnable" When a thread is created and started, what is its initial state? Explain suspend() method under Thread class> Explain isalive() method under Thread class? What is currentthread()? Explain main thread under Thread class execution? What is daemon thread? Which method is used to create the daemon thread? Which method must be implemented by all threads? What are concurrentcollectionclasses? - Advanced Design a Concurrent Rule pipeline in Java? Class declaration java.lang.thread class MULTITHREADING, CONCURRENCY AND THREAD BASICS QUESTIONS What is false sharing in the context of multi-threading? How do you take thread dump in Java? is Swing thread-safe? What is a thread local variable in Java? Write wait-notify code for producer-consumer problem? What is a Singleton Class in Java? Normal Class vs Singleton Class in Java? Write code for thread-safe Singleton in Java? Write code for creating Singleton in synchronized block/class in Java? Write code for creating Eager Initialization Singleton? Write code for creating Lazy Initialization Singleton (thread safe) The difference between sleep and wait in Java? Can we create an IMMUTABLE object, which contains a mutable object? How do you share an object between threads? or How to pass an object from one thread to another? How do find if your program has a deadlock? How do you avoid deadlock while coding? What are Enum Types an Enum type can be a subclass of java.lang.string SERIALIZE, SERIALIZABLE, SERIALIZATION

2 40. Serialization Class class xyz implements serializable Serialization Object transient to indicate that they are not part of the persistent state of an object Externalizable variables Serializable variables How many methods Serializable has? If no method then what is the purpose of Serializable INTERFACE? What will happen if one of the members in the class doesn't implement Serializable INTERFACE? If a class is Serializable but its super class in not, what will be the state of the instance variables inherited from super class after deserialization? what does it mean if a class is serializable Can you Customize Serialization process or can you override default Serialization process in Java? Suppose super class of a new class implement Serializable INTERFACE, how can you avoid new class to being serialized? Which methods are used during Serialization and Deserialization process in Java? Suppose you have a class which you serialized it and stored in persistence and later modified that class to add a new field. What will happen if you deserialized the object already serialized? What is serialversionuid? What would happen if you don't define this? What are the compatible changes and incompatible changes in Java Serialization Mechanism? Can we transfer a Serialized object vie network? Which kind of variables is not serialized during Java Serialization? EXTERNALIZE, EXTERNALIZABLE, EXTERNALIZATION What is Externalizable Diff between Serializable and Externalizable INTERFACE in Java Serializable Externalizable VOLATILE VARIABLE What is volatile variable in Java and when to use, multi-threading Why create instance lazily? Important points on Volatile keyword in Java What is a transient variable? **Diff between volatile and transient keywords initializing two variables and both are not volatile, and two threads T1 and T2 are modifying these values as following, both are not SYNCHRONIZED is it possible for Thread 2 to print x=0? JMM semantics for Volatile fields Read & write to volatile variables have same memory semantics as that of acquiring and releasing a monitor using SYNCHRONIZED code block Can we make array volatile in Java? Can volatile make a non-atomic operation to atomic? What are practical uses of volatile modifier? What guarantee volatile variable provides? SYNCHRONIZED Difference between SYNCHRONIZED block and SYNCHRONIZED method? Difference between volatile and SYNCHRONIZED keyword in Java How do you share data between two threads in Java? What are SYNCHRONIZED methods and SYNCHRONIZED statements? What is an object's lock and which objects have locks? Is it better to make whole getinstance() method SYNCHRONIZED or just critical section is enough? Which one you will prefer? What is ReentrantLock in Java? Have you used it before? JMM semantics for SYNCHRONIZED What is difference between synchronize Collection and concurrent Collection in Java? What do you mean by SYNCHRONIZED Non Access Modifier? What is BlockingQueue, how it is different than other collection classes? Synchronized thread error Synchronized? When to synchronize? Synchronized methods? Thread execution order when synchronized? Write a Program to solve Producer Consumer problem in Java?

3 87. Synchronized code? Why wait and notify methods are declared in Object class? Checking a Thread is alive or not Monitoring a thread's status How to check a thread has stopped or not? How to get the priorities of running threads? What s the difference between notify() and notifyall()? How do you solve producer consumer problem in Java? What is difference between submit () and execute () method of Executor and ExecutorService in Java? What is ReadWriteLock in Java? What is benefit of using ReadWriteLock in Java? What are differences between wait and sleep method in java? Write code to implement blocking queue in Java? Write a program, which will result in deadlock? How will you fix deadlock in Java? What is race condition? How will you find and solve race condition? How will you take thread dump in Java? How will you analyze Thread dump? How will you awake a blocked thread in java? What is Busy Spinning? Why you will use Busy Spinning as wait strategy? What are some common problems you have faced in multi-threading environment? How did you resolve it? MUTEX VS SEMAPHORE USING MUTEX: Synchronized blocks The wait and notifyall methods Reason Why Wait, Notify and NotifyAll are in Object Class Java monitors are recursive Synchronized Methods SEMAPHORE: General Questions: Can a thread acquire more than one lock (Mutex)? Can a mutex be locked more than once? What will happen if a non-recursive mutex is locked more than once Are binary semaphore and mutex same? Can we acquire mutex/semaphore in an Interrupt Service Routine? Is it necessary that a thread must block always when resource is not available? Let's first discuss about Memory Barrier which are the base for our further discussions read barriers write barrier How do you ensure that N thread can access N resources without deadlock What is difference between CyclicBarrier and CountDownLatch in Java What is the Stack Size: Daemon Thread in Java? Which method is used to create the daemon thread? Can a lock be acquired on a class? What state does a thread enter when it terminates its processing? What is difference between calling start() and run() method of Thread? What are the ways in which a thread can enter the waiting state? How does multi-threading take place on a computer with a single CPU? What invokes a thread's run() method? What is the difference between yielding and sleeping? How can a dead thread be restarted? What is difference between Executor.submit () and Executer.execute () method? Difference between fail-fast Iterator vs fail-safe Iterator in Java - Collections fail-fast Iterator fail-safe Iterator Write a Java program to prevent deadlock in Java? How do you ensure that N thread can access N resources without deadlock is it possible for Thread 2 to print x=0?

4 134. What is Busy Spinning? Why Should You Use It in Java? Is ++ operator is thread-safe in Java? DEUTSCHE BANK INTERVIEW QUESTIONS Multithreading and Locks for Concurrent Application Logic Thread start executes thread run? Implements Runnable, override run? Which three guarantee that a thread will leave the running state? Which of the following line of code is suitable to start a thread? Can you start a thread that has already started? Run multiple thread output? Run multiple thread output Which two are valid constructors for Thread? Which two of the following methods are defined in class Thread? Under which conditions will a currently executing thread stop? Which thread statement is true? Which three guarantee that a thread will leave the running state? Which will contain the body of the thread? Thread execution order? New thread execution? Thread blocking? Which of the following will directly stop the execution of a Thread? Which class or interface defines the wait(), notify(),and notifyall() methods? different threads that share one reference to a common object Which two can be used to create a new Thread? The following block of code creates a Thread using a Runnable target: run()? Thread execution? What will be the output of the program? Which two statements are true for any concrete class implementing the java. lang.runnable interface? Which cannot directly cause a thread to start executing? Which method registers a thread in a thread scheduler? which of these will create and start this thread? Which two statements are true? Can you override run?

5 Multithread Threads 1. What do you mean by Multithreaded program? A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution. Life Cycle of a Thread: A thread goes through various stages in its life cycle. For example, a thread is born, started, runs, and then dies. Following diagram shows complete life cycle of a thread. Above-mentioned stages are explained here: New: A new thread begins its life cycle in the new state. It remains in this state until the program starts the thread. It is also referred to as a born thread. Runnable: After a newly born thread is started, the thread becomes runnable. A thread in this state is considered to be executing its task. Waiting: Sometimes, a thread transitions to the waiting state while the thread waits for another thread to perform a task. A thread transitions back to the runnable state only when another thread signals the waiting thread to continue executing. Timed waiting: A runnable thread can enter the timed waiting state for a specified interval of time. A thread in this state transitions back to the runnable state when that time interval expires or when the event it is waiting for occurs. Terminated: A runnable thread enters the terminated state when it completes its task or otherwise terminates. thread Methods: Following is the list of important methods available in the Thread class. public void start() 5

6 Starts the thread in a separate path of execution, then invokes the run() method on this Thread object. public void run() If this Thread object was instantiated using a separate Runnable target, the run() method is invoked on that Runnable object. public final void setname(string name) Changes the name of the Thread object. There is also a getname() method for retrieving the name. public final void setpriority(int priority) Sets the priority of this Thread object. The possible values are between 1 and 10. public final void setdaemon(boolean on) A parameter of true denotes this Thread as a daemon thread. public final void join(long millisec) The current thread invokes this method on a second thread, causing the current thread to block until the second thread terminates or the specified number of milliseconds passes. public void interrupt() Interrupts this thread, causing it to continue execution if it was blocked for any reason. public final boolean isalive() Returns true if the thread is alive, which is any time after the thread has been started but before it runs to completion. The previous methods are invoked on a particular Thread object. The following methods in the Thread class are static. Invoking one of the static methods performs the operation on the currently running thread. public static void yield() Causes the currently running thread to yield to any other threads of the same priority that are waiting to be scheduled. public static void sleep(long millisec) Causes the currently running thread to block for at least the specified number of milliseconds. public static boolean holdslock(object x) Returns true if the current thread holds the lock on the given Object. public static Thread currentthread() Returns a reference to the currently running thread, which is the thread that invokes this method. public static void dumpstack() Prints the stack trace for the currently running thread, which is useful when debugging a multithreaded application. 2. Implement Runnable method Example: The following ThreadClassDemo program demonstrates some of these methods of the Thread class. Consider a class DisplayMessage which implements Runnable: 6

7 // File Name : DisplayMessage.java // Create a thread to implement Runnable public class DisplayMessage implements Runnable private String message; public DisplayMessage(String message) this.message = message; public void run() while(true) System.out.println(message); 3. class which extends Thread class: // File Name : GuessANumber.java // Create a thread to extentd Thread public class GuessANumber extends Thread private int number; public GuessANumber(int number) this.number = number; public void run() int counter = 0; int guess = 0; do guess = (int) (Math.random() * ); System.out.println(this.getName() + " guesses " + guess); counter++; while(guess!= number); System.out.println("** Correct! " + this.getname() + " in " + counter + " guesses.**"); 4. makes use of above defined classes: 7 // File Name : ThreadClassDemo.java public class ThreadClassDemo public static void main(string [] args) Runnable hello = new DisplayMessage("Hello"); Thread thread1 = new Thread(hello); thread1.setdaemon(true); thread1.setname("hello"); System.out.println("Starting hello thread..."); thread1.start(); Runnable bye = new DisplayMessage("Goodbye"); Thread thread2 = new Thread(bye); thread2.setpriority(thread.min_priority); thread2.setdaemon(true); System.out.println("Starting goodbye thread...");

8 thread2.start(); System.out.println("Starting thread3..."); Thread thread3 = new GuessANumber(27); thread3.start(); try thread3.join(); catch(interruptedexception e) System.out.println("Thread interrupted."); System.out.println("Starting thread4..."); Thread thread4 = new GuessANumber(75); thread4.start(); System.out.println("main() is ending..."); This would produce the following result. You can try this example again and again and you would get different result every time. Starting hello thread... Starting goodbye thread... Hello Hello Hello Hello Hello Hello Goodbye Goodbye Goodbye Goodbye Goodbye Thread Priorities: Every Java thread has a priority that helps the operating system determine the order in which threads are scheduled. Java thread priorities are in the range between 5. MIN_PRIORITY (a constant of and MAX_PRIORITY (a constant of 10). By default, every thread is given priority NORM_PRIORITY (a constant of 5). Threads with higher priority are more important to a program and should be allocated processor time before lower-priority threads. However, thread priorities cannot guarantee the order in which threads execute and very much platform dependent. 8

9 6. What are the two ways to implement and create a running thread? Summary 1- Java Thread by Extending from the Thread class A - Extends Thread public class HelloThread extends Thread public void run() some code public static void main (String args[]) (new HelloThread()).start(); //new creates thread //start() starts running thread 2- Implementing Runnable INTERFACE : public class HelloRunnable Implements Runnable public void run( ) some code public static void main (String args[]) (new Thread(new HelloRunnable())).start); // use constructor, // new creates thread // call start which calls run() 7. Difference between Runnable and Callable INTERFACE in Java? Old - Runnable run() was the only way to implement a task before JDK 1.5 adds Callable also defines a single call() method it can return values and throw exceptions. package com.example.thread.callable; import java.util.concurrent.callable; public class CallableAdder implements Callable<Integer> Integer operand1; Integer operand2; CallableAdder(Integer operand1,integer operand2) this.operand1=operand1; this.operand2=operand2; public Integer call() throws Exception // TODO Auto-generated method stub System.out.println(Thread.currentThread().getName()+" says : partial Sum for " + operand1 + " and "+ operand2+ " is " +(operand1+operand2)); return operand1+operand2; 9

10 2. Execution Mechanism Both interfaces are designed to represent a task that can be executed by multiple threads. Runnable tasks can be run using the Thread class or ExecutorService whereas Callables can be run only using the latter. Return Values With Runnable The Runnable interface is a functional interface and has a single run() method which doesn t accept any parameters and does not return any values. This is suitable for situations where we are not looking for a result of the thread execution, for example, incoming events logging: This is suitable for situations where we re not looking for a result of the thread execution, for example, incoming events logging: public interface Runnable public void run(); public class EventLoggingTask implements Runnable private Logger logger = public void run() logger.info("message"); In this example, the thread will just read a message from the queue and log it in a log file. There s no value returned from the task; the task can be launched using ExecutorService: public void executetask() executorservice = Executors.newSingleThreadExecutor(); Future future = executorservice.submit(new EventLoggingTask()); executorservice.shutdown(); In this case, the Future object will not hold any value. With Callable The Callable interface is a generic interface containing a single call() method which returns a generic value V: 10 public interface Callable<V> V call() throws Exception; Let s have a look at calculating the factorial of a number: public class FactorialTask implements Callable<Integer> int number;

11 // standard constructors public Integer call() throws InvalidParamaterException int fact = 1; //... for(int count = number; count > 1; count--) fact = fact * count; return fact; The result of call() method is returned within a Future public void whentasksubmitted_thenfutureresultobtained() FactorialTask task = new FactorialTask(5); Future<Integer> future = executorservice.submit(task); assertequals(120, future.get().intvalue()); Exception Handling With Runnable Since the method signature does not have the throws clause specified, there is no way to propagate further checked exceptions. With Callable Callable s call() method contains throws Exception clause so we can easily propagate checked exceptions further: public class FactorialTask implements Callable<Integer> //... public Integer call() throws InvalidParamaterException if(number < 0) throw new InvalidParamaterException("Number should be positive"); //... In case of running a Callable using an ExecutorService, the exceptions are collected in the Future object, which can be checked by making a call to the Future.get() method. This will throw an ExecutionException which wraps the original = ExecutionException.class) public void whenexception_thencallablethrowsit() FactorialCallableTask task = new FactorialCallableTask(-5); Future<Integer> future = executorservice.submit(task); Integer result = future.get().intvalue(); In the above test, the ExecutionException is being thrown as we are passing an invalid number. We can call the getcause() method on this exception object to get the original checked exception. If we don t make the call to the get() method of Future class then the exception thrown by call() method will not be reported back, and the task will still be marked as 11

12 public void whenexception_thencallabledoesntthrowsitifgetisnotcalled() FactorialCallableTask task = new FactorialCallableTask(-5); Future<Integer> future = executorservice.submit(task); assertequals(true, future.isdone()); The above test will pass successfully even though we ve thrown an exception for the negative values of the parameter to FactorialCallableTask. 8. Explain the available thread states in a high-level. During its execution, a thread can reside in one of the following states: NEW: The thread becomes ready to run, but does not necessarily start running immediately. RUNNABLE: The Java Virtual Machine (JVM) is actively executing the thread s code. BLOCKED: The thread is in a blocked state while waiting for a monitor lock. WAITING: The thread waits for another thread to perform a particular action. TIMED_WAITING: The thread waits for another thread to perform a particular action up to a specified waiting time. TERMINATED: The thread has finished its execution. 9. Difference between "implements Runnable" and "extends Thread" in Java 1. INHERITANCE Option: The limitation with "extends Thread" approach is that if you extend Thread, you can not extend anything else. Java does not support multiple INHERITANCE. In reality, you do not need Thread class behavior, because in order to use a thread you need to instantiate one anyway. On the other hand, Implementing the Runnable INTERFACE gives you the choice to extend any class you like, but still define behavior that will be run by separate thread. 2. Reusability : In "implements Runnable", we are creating a different Runnable class for a specific behavior job (if the work you want to be done is job). It gives us the freedom to reuse the specific behavior job whenever required. "extends Thread" contains both thread and job specific behavior code. Hence once thread completes execution, it can not be restart again. Object Oriented Design: Implementing Runnable should be preferred. It does not specializing or modifying the thread behavior. You are giving thread something to run. We conclude that Composition is the better way. Composition means two objects A and B satisfies has-a relationship. "extends Thread" is not a good Object Oriented practice. Loosely-coupled : "implements Runnable" makes the code loosely-coupled and easier to read. Because the code is split into two classes. Thread class for the thread specific code and your Runnable implementation class for your job that should be run by a thread code. "extends Thread" makes the code tightly coupled. Single class contains the thread code as well as the job that needs to be done by the thread. Functions overhead : " 12

13 extends Thread" means inheriting all the functions of the Thread class which we may do not need. job can be done easily by Runnable without the Thread class functions overhead. 10. When to use "extends Thread" over "implements Runnable" The only time it make sense to use "extends Thread" is when you have a more specialized version of Thread class. In other words, because you have more specialized thread specific behavior. But the conditions are that the thread work you want is really just a job to be done by a thread. In that case you need to use "implements Runnable" which also leaves your class free to extend some other class. 11. When a thread is created and started, what is its initial state? A thread is in the ready state as initial state after it has been created and started. 12. Explain suspend() method under Thread class> It is used to pause or temporarily stop the execution of the thread. 13. Explain isalive() method under Thread class? It is used to find out whether a thread is still running or not. 14. What is currentthread()? It is a public static method used to obtain a reference to the current thread. 15. Explain main thread under Thread class execution? The main thread is created automatically and it begins to execute immediately when a program starts. It is a thread from which all other child threads originate. 16. What is daemon thread? Daemon thread is a low priority thread, which runs intermittently in the background doing the garbage collection operation for the java runtime system. 17. Which method is used to create the daemon thread? setdaemon method is used to create a daemon thread. 18. Which method must be implemented by all threads? All tasks must implement the run() method 19. What are concurrentcollectionclasses? - Advanced In jdk1.5, Java Api developers had introduced new package called java.util.concurrent that have thread-safe collection classes as they allow collections to be modified while iterating. The iterator is fail-fast that is it will throw ConcurrentModificationException. Some examples of concurrentcollectionclasses are : a. CopyOnWriteArrayList b. ConcurrentHashMap 20. Design a Concurrent Rule pipeline in Java? 13

14 Concurrent programming or concurrent design is very hot now days to leverage power of everincreasing cores in advanced processor and Java being a multi-threaded language has benefit over others. Do design a concurrent system key point to note is thread-safety, immutability, local variables and avoid using static or instance variables. You just to think that one class can be executed by multiple threads a same time, so best approach are that every thread work on its own data, doesn't interfere on other data and have minimal synchronization preferred at start of pipeline. This question can lead from initial discussion to full coding of classes and INTERFACE but if you remember key points and issues around concurrency e.g. race condition, deadlock, memory interference, atomicity, ThreadLocal variables etc. you can get around it. 21. Class declaration java.lang.thread class Following is the declaration for java.lang.thread class: public class Thread extends Object implements Runnable Following are the fields for java.lang.thread class: static int MAX_PRIORITY -- This is the minimum priority that a thread can have. static int NORM_PRIORITY -- This is the default priority that is assigned to a thread. 14

15 Multithreading, Concurrency and Thread basics Questions 22. What is false sharing in the context of multi-threading? false sharing is one of the well-known performance issues on multi-core systems, where each process has its local cache. false sharing occurs when threads on different processor modify variables that reside on same cache line as shown in the following image: False sharing is very hard to detect because the thread may be accessing completely different global variables that happen to be relatively close together in memory. Like many concurrency issues, the primary way to avoid false sharing is careful code review and aligning your data structure with the size of a cache line. 23. How do you take thread dump in Java? 15 You can take a thread dump of Java application in Linux by using kill -3 PID, where PID is the process id of Java process. In Windows, you can press Ctrl + Break. This will instruct JVM to print thread dump in standard out or err and it could go to console or log file depending upon your application configuration. If you have used Tomcat then when 24. is Swing thread-safe? No, Swing is not thread-safe. You cannot update Swing components e.g. JTable, JList or JPanel from any thread, in fact, they must be updated from GUI or AWT thread. That's why swings provide invokeandwait() and invokelater() method to request GUI update from any other threads. This methods put update request in AWT threads queue and can wait till update or return immediately for an asynchronous update. You can also check the detailed answer to learn more. 25. What is a thread local variable in Java? Thread-local variables are variables confined to a thread, its like thread's own copy which is not shared between multiple threads. Java provides a ThreadLocal class to support thread-local variables. It's one

16 of the many ways to achieve thread-safety. Though be careful while using thread local variable in manged environment e.g. with web servers where worker thread out lives any application variable. Any thread local variable which is not removed once its work is done can potentially cause a memory leak in Java application. 26. Write wait-notify code for producer-consumer problem? Just remember to call wait() and notify() method from SYNCHRONIZED block and test waiting for condition on the loop instead of if block. 16

17 27. What is a Singleton Class in Java? Class that can have only one object at a time After first time, if we try to instantiate the Singleton class, the new variable also points to the first instance created. 28. Normal Class vs Singleton Class in Java? Normal use constructor Singleton class use getinstance() method. 29. Write code for thread-safe Singleton in Java? Singleton should remain singleton even if initialization occurs in the case of multiple threads. Using Java enum as Singleton class is one of the easiest ways to create a thread-safe singleton in Java. enum is guaranteed to be Singleton. //has an implicit empty constructor. Let's be explicit instead, public enum MySingleton INSTANCE; private MySingleton() System.out.println("Here"); //If you then added another class with a main() method like public static void main(string[] args) System.out.println(MySingleton.INSTANCE); You would see Here INSTANCE enum fields are compile time constants, but they are instances of their enum type. And, they're constructed when the enum type is referenced for the first time. 30. Write code for creating Singleton in synchronized block/class in Java? public class MySingleton private static MySingleton INSTANCE; private MySingleton () //Private instantiation public static synchronized MySingleton getinstance() //If you want your method thread safe... //Threads will now block and enter the method one at a time. if (INSTANCE == null) INSTANCE = new MySingleton (); return INSTANCE; it synchronizes all calls to getinstance(), including reads. 17

18 Reads do not need to be synchronized as they simply return the value of INSTANCE. Since reads will make up the bulk of our calls (remember, instantiation only happens on the first call), we will incur an unnecessary performance hit by synchronizing the entire method. private static MySingleton INSTANCE; public static MySingleton getinstance() if (INSTANCE == null) synchronized(mysingleton.class) if (INSTANCE == null) INSTANCE = createinstance(); return INSTANCE; We solve this by using the volatile keyword on the declaration of the INSTANCE member. This will tell the compiler to always read from, and write to, main memory, and not the CPU cache. private static volatile MySingleton INSTANCE; public static MySingleton getinstance() if (INSTANCE == null) synchronized(mysingleton.class) if (INSTANCE == null) INSTANCE = createinstance(); return INSTANCE; But this simple change comes at a cost. Because we are bypassing the CPU cache, we will take a performance hit each time we operate on the volatile INSTANCE member which we do 4 times. We double-check existence (1 and 2), set the value (3), and then return the value (4). private static volatile MySingleton INSTANCE; public static MySingleton getinstance() MySingleton result = INSTANCE; if (result == null) synchronized(mysingleton.class) result = INSTANCE; if (result == null) INSTANCE = result = createinstance(); return result; Since the performance hit is due to operating directly on the volatile member, let s set a local variable to the value of the volatile and operate on the local variable instead. This will decrease the number of times we operate on the volatile, thereby reclaiming some of our lost performance. Note that we have to set our local variable again when we enter the synchronized block. This ensures it is up to date with any changes that occured while we were waiting for the lock. 31. Write code for creating Eager Initialization Singleton? 18

19 public class Test private static final Test test = new Test(); private Test() public static Test gettest() return test; 32. Write code for creating Lazy Initialization Singleton (thread safe). public class Test private static volatile Test test; private Test() public static Test gettest() if(test == null) synchronized(test.class) if(test == null)test = new Test(); return test; 19

20 33. The difference between sleep and wait in Java? Though both are used to pause currently running thread, sleep() is actually meant for short pause because it doesn't release lock, while wait() is meant for conditional wait and that's why it release lock which can then be acquired by another thread to change the condition on which it is waiting. 34. Can we create an IMMUTABLE object, which contains a mutable object? Yes, its possible to create an IMMUTABLE object which may contain a mutable object, you just need to be a little bit careful not to share the reference of the mutable component, instead, you should return a copy of it if you have to. Most common example is an Object which contain the reference of java.util.date object. 35. How do you share an object between threads? or How to pass an object from one thread to another? There are multiple ways to do that e.g. Queues, Exchanger etc, but BlockingQueue using Producer Consumer pattern is the easiest way to pass an object from thread to another. 36. How do find if your program has a deadlock? By taking thread dump using kill -3, using JConsole or VisualVM), 37. How do you avoid deadlock while coding? By ensuring locks are acquire and released in an ordered manner, 38. What are Enum Types An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week. Because they are constants, the names of an enum type's fields are in uppercase letters. In the Java programming language, you define an enum type by using the enum keyword. For example, you would specify a days-of-the-week enum type as: public enum Day SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY Java programming language enum types are much more powerful than their counterparts in other languages. The enum declaration defines a class (called an enum type). The enum class body can include methods and other fields. The compiler automatically adds some special methods when it creates an enum. For example, they have a static values method that returns an array containing all of the values of the enum in the order they are declared. This method is commonly used in combination with the for-each construct to iterate over the values of an enum type. For example, this code from the Planet class example below iterates over all the planets in the solar system. for (Planet p : Planet.values()) System.out.printf("Your weight on %s is %f%n", p, p.surfaceweight(mass)); 20

21 In the following example, Planet is an enum type that represents the planets in the solar system. They are defined with constant mass and radius properties. Each enum constant is declared with values for the mass and radius parameters. These values are passed to the constructor when the constant is created. Java requires that the constants be defined first, prior to any fields or methods. Also, when there are fields and methods, the list of enum constants must end with a semicolon. Note: The constructor for an enum type must be package-private or private access. It automatically creates the constants that are defined at the beginning of the enum body. You cannot invoke an enum constructor yourself. In addition to its properties and constructor, Planet has methods that allow you to retrieve the surface gravity and weight of an object on each planet. Here is a sample program that takes your weight on earth (in any unit) and calculates and prints your weight on all of the planets (in the same unit): public enum Planet MERCURY (3.303e+23, e6), VENUS (4.869e+24, e6), EARTH (5.976e+24, e6), MARS (6.421e+23, e6), JUPITER (1.9e+27, e7), SATURN (5.688e+26, e7), URANUS (8.686e+25, e7), NEPTUNE (1.024e+26, e7); private final double mass; // in kilograms private final double radius; // in meters Planet(double mass, double radius) this.mass = mass; this.radius = radius; private double mass() return mass; private double radius() return radius; // universal gravitational constant (m3 kg-1 s-2) public static final double G = E-11; double surfacegravity() return G * mass / (radius * radius); double surfaceweight(double othermass) return othermass * surfacegravity(); public static void main(string[] args) if (args.length!= 1) System.err.println("Usage: java Planet <earth_weight>"); System.exit(-1); double earthweight = Double.parseDouble(args[0]); double mass = earthweight/earth.surfacegravity(); for (Planet p : Planet.values()) System.out.printf("Your weight on %s is %f%n", p, p.surfaceweight(mass)); If you run Planet.class from the command line with an argument of 175, you get this output: 21

22 $ java Planet 175 Your weight on MERCURY is Your weight on VENUS is Your weight on EARTH is Your weight on MARS is Your weight on JUPITER is Your weight on SATURN is Your weight on URANUS is Your weight on NEPTUNE is an Enum type can be a subclass of java.lang.string. Answer: False. All enums implicitly extend java.lang.enum. Because a class can only extend one parent, the Java language does not support multiple inheritance of state, and therefore an enum cannot extend anything else. Serialize, Serializable, Serialization 40. Serialization Class class xyz implements serializable 22 Class needs to implement java.io.serializable INTERFACE and JVM will take care of serializing the object. constraints on your ability to change class is SerialVersionUID. 41. Serialization Object object s state persistent. That means the state of the object is converted into a stream of bytes and stored in a file. Mostly used in the networking programming. The objects that need to be transmitted through the network have to be dconverted into bytes. Objects var s converted into a persistent state by default Some cases, avoid persisting some variable because you don t have a need for it to persist, maybe to conserve memory ex class GalleryImage implements Serializable private Image image; private transient Image thumbnailimage; private void generatethumbnail() // Generate thumbnail. The thumbnailimage field is marked as transient, so only the original image is serialized rather than persisting both the original image and the thumbnail image. This means that less storage would be needed to save the serialized object. deserialization, the readobject method is called to perform any operations necessary to restore the state of the object back to the state at which the serialization occurred. variable that may not be serialized

23 De-serialization (reading a file into a program) initialized with default value during de-serialization and there assignment or restoration of value has to be handled by application code. Cannot be used with static 42. transient to indicate that they are not part of the persistent state of an object declare it either static or transient and it will not be included during Java serialization process. 43. Externalizable variables provides us writeexternal() and readexternal() method which gives us flexibility to control java serialization mechanism instead of relying on Java's default serialization. 44. Serializable variables process is to convert an Object into a binary format which can be persisted into disk or sent over network to any other running Java virtual machine storing object s state into a file with extension.ser and recreating object's state from that file, this reverse process is called deserialization. Setup - Java class needs to implement java.io.serializable INTERFACE (Java Serialization API with either Serializable or Externalizable INTERFACE ) and JVM will automatically serialize its instance when passed over to java.io.onjectoutputstream using WriteObject(). Serializable aka marker INTERFACES or tag INTERFACE because it does not contain any method of behavior and just uses as a tag to a class. Most commercial Java users store in flat file, DB or memory, few use technique of storing Object's state in Java. High Maintenance - Hard to ensure backward compatibility. 45. How many methods Serializable has? If no method then what is the purpose of Serializable INTERFACE? Serializable INTERFACE exists in java.io package and forms core of java serialization mechanism. It doesn't have any method and also called Marker INTERFACE in Java. When your class implements java.io.serializable INTERFACE it becomes Serializable in Java and gives compiler an indication that use Java Serialization mechanism to serialize this object. 46. What will happen if one of the members in the class doesn't implement Serializable INTERFACE? If you try to serialize an object of a class which implements Serializable, but the object includes a reference to an non- Serializable class then a NotSerializableException will be thrown at runtime and this is why I 23

24 always put a SerializableAlert (comment section in my code), one of the code comment best practices, to instruct developer to remember this fact while adding a new field in a Serializable class. 47. If a class is Serializable but its super class in not, what will be the state of the instance variables inherited from super class after deserialization? Java serialization process only continues in object hierarchy till the class is Serializable i.e. implements Serializable INTERFACE in Java and values of the instance variables inherited from super class will be initialized by calling CONSTRUCTOR of Non-Serializable Super class during deserialization process. Once the CONSTRUCTOR chaining will started it wouldn't be possible to stop that, hence even if classes higher in hierarchy implements Serializable INTERFACE, there CONSTRUCTOR will be executed. As you see from the statement this Serialization interview question looks very tricky and tough but if you are familiar with key concepts it s not that difficult. 48. what does it mean if a class is serializable if and when it implements the Serializable INTERFACE, which is an INTERFACE residing in the java.io package. If a class is serializable, it means that any object of that class can be converted into a sequence of bits so that it can be written to some storage medium (like a file), or even transmitted across a network. Here s what a serializable class looks like: Example of a serializable class in Java public class SomeClass implements java.io.serializable // this class is serializable Can you Customize Serialization process or can you override default Serialization process in Java? yes serializing an object ObjectOutputStream.writeObject (savethisobject) is invoked reading object ObjectInputStream.readObject() is invoked If you define these two methods in your class then JVM will invoke these two methods instead of applying default serialization mechanism. You can customize behavior of object serialization and deserialization here by doing any kind of pre or post processing task. Important point to note is making these methods private to avoid being inherited, overridden or overloaded. Since only Java Virtual Machine can call private method integrity of your class will remain and Java Serialization will work as normal. 50. Suppose super class of a new class implement Serializable INTERFACE, how can you avoid new class to being serialized? If Super Class of a Class already implements Serializable INTERFACE in Java then its already Serializable in Java, since you cannot unimplemented an INTERFACE it s not really possible to make it Non Serializable class yes there is a way to avoid serialization of new class. To avoid Java serialization you need to implement writeobject() and readobject() method in your Class and need to throw NotSerializableException from those method. This is another benefit of customizing java serialization process as described in above. 24

25 51. Which methods are used during Serialization and Deserialization process in Java? Whether you are familiar with usage of readobject(), writeobject(), readexternal() and writeexternal() or not. Java Serialization is done by java.io.objectoutputstream class.. To store any object via serialization mechanism we call ObjectOutputStream.writeObject(saveThisobject) to deserialized that object we call ObjectInputStream.readObject() method. Call to writeobject() method trigger serialization process in java. important thing to note about readobject() method is that it is used to read bytes from the persistence and to create object from those bytes and its return an Object which needs to be type cast to correct type. 52. Suppose you have a class which you serialized it and stored in persistence and later modified that class to add a new field. What will happen if you deserialized the object already serialized? It depends on whether class has its own serialversionuid or not. As we know from above question that if we don't provide serialversionuid in our code java compiler will generate it and normally it s equal to hashcode of object. by adding any new field there is chance that new serialversionuid generated for that class version is not the same of already serialized object and in this case Java Serialization API will throw java.io.invalidclassexception and this is the reason its recommended to have your own serialversionuid in code and make sure to keep it same always for a single class. 53. What is serialversionuid? What would happen if you don't define this? an ID which is stamped on object when it get serialized used for version control of object, usually hashcode of object, Consequence of not specifying serialversionuid is that when you add or modify any field in class then already serialized class will not be able to recover because serialversionuid generated for new class and for old serialized object will be different. Java serialization process relies on correct serialversionuid for recovering state of serialized object and throws java.io.invalidclassexception in case of serialversionuid mismatch, 54. What are the compatible changes and incompatible changes in Java Serialization Mechanism? adding any field or method comes under compatible change and changing class hierarchy or UNimplementing Serializable INTERFACES some under non-compatible changes. For complete list of compatible and non-compatible changes I would advise reading Java serialization specification. 55. Can we transfer a Serialized object vie network? Yes you can transfer a Serialized object via network because Java serialized object remains in form of bytes, which can be transmitted via network. You can also store serialized object in Disk or database as Blob. 56. Which kind of variables is not serialized during Java Serialization? static variables belong to the class and not to an object they are not the part of the state of object so they are not saved during Java Serialization process. As Java Serialization only persist state of object and not object itself. 25

26 Transient variables are also not included in java serialization process and are not the part of the object s serialized state. After this question sometime interviewer ask a follow-up if you don't store values of these variables then what would be value of these variable once you deserialized and recreate those object? Externalize, Externalizable, Externalization 57. What is Externalizable Externalizable INTERFACE provides complete control of serialization process to application. If a class is declared within a class and specifies the static modifier, the compiler treats the class just like any other top-level class. Nested top-level class is an Inner class. 58. Diff between Serializable and Externalizable INTERFACE in Java Serializable default serialization process is used Externalizable Externalizable INTERFACE provides complete control of serialization process to application custom serialization process is used ie JVM gives call back to readexternel() and writeexternal() of java.io. which gives us flexibility to control java serialization mechanism instead of relying on Java s default serialization. Correct implementation of Externalizable INTERFACE can improve performance of application. Volatile Variable 59. What is volatile variable in Java and when to use, multi-threading do not cache value of this variable and always read it from main memory. Other threads able to access if you don t want any field to be part of the objects state then declare it either static or transient. Can be used with static Value is visible to all threads Any changes will be seen by all threads one thread to another also as "happens-before" which solves the problem of memory writes that happen in one thread can "leak through" and be seen by another thread. Java volatile keyword cannot be used with method or class and it can only be used with variable. 26 public class Singleton private static volatile Singleton _instance; //ensure other threads access public static Singleton getinstance() // Singleton Ensures that only one instance if(_instance == null) SYNCHRONIZED(Singleton.class) // of a class

27 _ if(_instance == null) _instance = new Singleton(); return _instance; If you look at the code carefully you will be able to figure out: We are only creating instance one time 60. Why create instance lazily? If we do not make _instance variable volatile then Thread which is creating instance of Singleton is not able to communicate other thread, that instance has been created until it comes out of the Singleton block, so if Thread A is creating Singleton instance and just after creation lost the CPU, all other thread will not be able to see value of _instance as not null and they will believe it s still null. ex2 use a variable bexit to check whether user has pressed exit button or not, value of this variable is updated in event thread and checked in game thread, So if we don't use volatile keyword with this variable, Game Thread might miss update from event handler thread if it s not SYNCHRONIZED in java already. volatile keyword in java guarantees that value of volatile variable will always be read from main memory and "happens-before" relationship in Java Memory model will ensure that content of memory will be communicated to different threads. private boolean bexit; while(!bexit) checkuserposition(); updateuserposition(); In this code example One Thread (Game Thread) can cache the value of "bexit" instead of getting it from main memory every time and if in between any other thread (Event handler Thread) changes the value; it would not be visible to this thread. Making boolean variable "bexit" as volatile in java ensures this will not happen. used as an alternative way of achieving synchronization in Java in some cases, like Visibility. with volatile variable it s guaranteed that all reader thread will see updated value of volatile variable once write operation completed, without volatile keyword different reader thread may see different values. volatile variable can be used to inform compiler that a particular field is subject to be accessed by multiple threads, which will prevent compiler from doing any reordering or any kind of optimization, which is not desirable in multi-threaded environment. Without volatile variable compiler can re-order code, free to cache value of volatile variable instead of always reading from main memory. like following example without volatile variable may result in infinite loop 27

28 class ThreadDemo extends Thread private Thread t; private String threadname; PrintDemo PD; ThreadDemo( String name, PrintDemo pd) threadname = name; PD = pd; public void start () System.out.println("Starting " + threadname ); if (t == null) t = new Thread (this, threadname); start (); public class TestThread public static void main(string args[]) PrintDemo PD = new PrintDemo(); ThreadDemo T1 = new ThreadDemo( "Thread - 1 ", PD ); ThreadDemo T2 = new ThreadDemo( "Thread - 2 ", PD ); T1.start(); T2.start(); // wait for threads to end try T1.join(); T2.join(); catch( Exception e) System.out.println("Interrupted"); without volatile modifier it s not guaranteed that one Thread see the updated value of isactive from other thread. compiler is also free to cache value of isactive instead of reading it from main memory in every iteration. By making isactive a volatile variable you avoid this issue. Another place where volatile variable can be used is to fixing double checked locking in Singleton pattern. 61. Important points on Volatile keyword in Java 1. only application to variable and using volatile keyword with class and method is illegal. 2. guarantees that value of volatile variable will always be read from main memory and not from Thread's local cache. 3. Java volatile keyword doesn't means atomic, its common misconception that after declaring volatile ++ will be atomic, to make the operation atomic you still need to ensure exclusive access using SYNCHRONIZED method or block in Java. 4. reduces the risk of memory consistency errors, because any write to a volatile variable 5. changes to a volatile variable are always visible to other threads. 7. An access to a volatile variable in Java never has chance to block, since we are only doing a simple read or write, so unlike a SYNCHRONIZED block we will never hold on to any lock or wait for any lock. 8. Java volatile variable that is an object reference may be null. 62. What is a transient variable? Is Not a part of the persistent state of a serialized object. Suppose that there s a particular object data member (like a password) that we may not want to be saved when an object is serialized. Then, what we can do is declare that data member to be "transient". A transient variable is not a part of the persistent state of a serialized object. Here s an 28

29 example of what a transient variable looks like in a serializable class: Example of transient in a serializable class public class SomeClass implements java.io.serializable // this variable will not persist private transient String password;... So, if we were to write a serializable object to a file, any transient variable that was part of that object will not be saved to the file. 63. **Diff between volatile and transient keywords nothing in common transient instance variables to exclude them from serialization process. if a field is transient its value will not be persisted. transient variables are initialized with default value during de-serialization and there assignment or restoration of value has to be handled by application code. volatile variables to indicate compiler and JVM that always read its value from main memory static volatile OK static transient Wrong 64. initializing two variables and both are not volatile, and two threads T1 and T2 are modifying these values as following, both are not SYNCHRONIZED is it possible for Thread 2 to print x=0? volatile variables are signal to compiler that multiple threads are interested on this variable and it shouldn't reorder its access. Makes Vars thread-safe int x = 0; boolean bexit = false; Thread 1 (not SYNCHRONIZED) x = 1; bexit = true; // make bexit as volatile volatile bexit = true; Thread 2 (not SYNCHRONIZED) // may print x=0. if (bexit == true) System.out.println("x=" + x); Yes, It's possible that thread T2 may print x=0.why? because without any instruction to compiler e.g. SYNCHRONIZED or volatile, bexit=true might come before x=1 in compiler reordering. Also, x=1 might not become visible in Thread 2, so Thread 2 will load x=0. Now, how do you fix it? Fix Either make both threads SYNCHRONIZED on a common mutex, OR make both variable volatile. Both are correct, as it will prevent reordering and guarantee visibility. best answer is you just need to make bexit as volatile, volatile bexit = true; then Thread 2 can only print x=1. x does not need to be volatile because x cannot be reordered to come after bexit=true when bexit is volatile. 29

30 65. JMM semantics for Volatile fields Read & write to volatile variables have same memory semantics as that of acquiring and releasing a monitor using SYNCHRONIZED code block. So the visibility of volatile field is guaranteed by the JMM. Moreover afterwards Java 1.5, volatile reads and writes are not reorderable with any other memory operations (volatile and non-volatile both). Thus when Thread A writes to a volatile variable V, and afterwards Thread B reads from variable V, any variable values that were visible to A at the time V was written are guaranteed now to be visible to B. Let's try to understand the same using the following code Data data = null; volatile boolean flag = false; Thread A data = new Data(); flag = true; // writing to volatile will flush data as well as flag to main memory Thread B if(flag==true) <-- as="" barrier="" data.="" flag="" font="" for="" from="" perform="" read="" reading="" volatile="" well="" will=""> use data; // data is guaranteed to visible even though it is not declared volatile because of the JMM semantics of volatile flag. 66. Can we make array volatile in Java? Yes, you can make an array volatile in Java but only the reference which is pointing to an array, not the whole array. What I mean, if one thread changes the reference variable to points to another array, that will provide a volatile guarantee, but if multiple threads are changing individual array elements they won't be having happens before guarantee provided by the volatile modifier. 67. Can volatile make a non-atomic operation to atomic? YES. having a long field in your class. If you know that a long field is accessed by more than one thread e.g. a counter, a price filed or anything, you better make it volatile. Why? because reading to a long variable is not atomic in Java and done in two steps, If one thread is writing or updating long value, it's possible for another thread to see half value (fist 32-bit). While reading/writing a volatile long or double (64 bit) is atomic. 68. What are practical uses of volatile modifier? make reading double and long atomic. Both double and long are 64-bit wide and they are read in two parts, first 32-bit first time and next 32-bit second time, which is non-atomic but volatile double and long read is atomic in Java. Another use of the volatile variable is to provide a memory barrier, just like it is used in Disrupter framework. Basically, Java Memory model inserts a write barrier after you write to a volatile variable and a read barrier before you read it. Which means, if you write to volatile field then its guaranteed that any thread accessing that variable will see the value you wrote and anything you did before doing that write into the thread is guaranteed to have happened and any updated data values will also be visible to all threads, because the memory barrier flushed all other writes to the cache. 30

31 69. What guarantee volatile variable provides? guarantee volatile assignment cannot be re-ordered happens-before guarantee which ensure changes made in one thread is visible to others. atomicity e.g. reading 64-bit data types like long and double are not atomic but read of volatile double or long is atomic. SYNCHRONIZED 70. Difference between SYNCHRONIZED block and SYNCHRONIZED method? SYNCHRONIZED block can choose which object it synchronizes on. SYNCHRONIZED method can only use 'this' (or the corresponding Class instance for a SYNCHRONIZED class method). SYNCHRONIZED Method defines a self contained block and its easy to handle in multi-threaded environment. Both act as similar; there is no major advantage over each other Difference between volatile and SYNCHRONIZED keyword in Java Volatile SYNCHRONIZED In Summary volatile is not a replacement of SYNCHRONIZED block or method but in some situation is very handy and can save performance overhead which comes with use of synchronization in Java synchronizes the value of one variable between Thread memory and "main memory synchronizes the value of all variable between thread memory and "main" memory and locks and releases a monitor to boot. keyword is a field modifier modifies code blocks and methods doesn't require release lock obtains and releases lock on monitor s Notta Threads can be blocked for waiting SYNCHRONIZED method affects performance more than volatile Due to this reason likely to have more overhead than volatile. could be null cannot synchronize on null object Writing into a volatile field has the same memory effect as a monitor release and reading from a volatile field has the same memory effect as a monitor acquire 72. How do you share data between two threads in Java? using shared object or shared data structures like Queue. Depending upon, what you are using, you need to provide thread-safety guarantee, and one way of providing thread-safety is using SYNCHRONIZED keyword. 31

32 If you use concurrent collection classes from Java 5 e.g. BlockingQueue, you can easily share data without being bothered about thread safety and inter thread communication. 73. What are SYNCHRONIZED methods and SYNCHRONIZED statements? SYNCHRONIZED methods are methods that are used to control access to an object. A SYNCHRONIZED statement can only be executed after a thread has acquired the lock for the object or class referenced in the SYNCHRONIZED statement. 74. What is an object's lock and which objects have locks? An object's lock is a mechanism that is used by multiple threads to obtain SYNCHRONIZED access to the object. A thread may execute a SYNCHRONIZED method of an object only after it has acquired the object's lock. 75. Is it better to make whole getinstance() method SYNCHRONIZED or just critical section is enough? Which one you will prefer? candidate is aware of performance trade off of unnecessary locking or not. Since locking only make sense when we need to create instance and rest of the time its just read only access so locking of critical section is always better option. related to double checked locking pattern, well synchronization is costly and when you apply this on whole method than call to getinstance() will be SYNCHRONIZED and contented. Since synchronization is only needed during initialization on singleton instance, to prevent creating another instance of Singleton, It s better to only synchronize critical section and not whole method. Singleton pattern is also closely related to factory design pattern where getinstance() serves as static factory method. 76. What is ReentrantLock in Java? Have you used it before? ReentrantLock is an alternative of SYNCHRONIZED keyword in Java; it is introduced to handle some of the limitations of SYNCHRONIZED keywords. Many concurrency utility classes and concurrent collection classes from Java 5, including ConcurrentHashMap uses ReentrantLock, to leverage optimization. ReentrantLock mostly uses atomic variable and faster CAS operation to provide better performance. Diff with SYNCHRONIZED includes ability to acquire lock interruptible, timeout feature while waiting for lock etc. 77. JMM semantics for SYNCHRONIZED thread acquires monitor of an object by entering into a SYNCHRONIZED block of code, it performs a read barrier (invalidates the local memory and reads from the heap instead). Similarly exiting from a SYNCHRONIZED block as part of releasing the associated monitor, it performs a write barrier (flushes changes to the main memory) Thus modifications to a shared state using SYNCHRONIZED block by one Thread, is guaranteed to be visible to subsequent SYNCHRONIZED reads by other threads. This guarantee is provided by JMM in presence of SYNCHRONIZED code block. 78. What is difference between synchronize Collection and concurrent Collection in Java? 32

33 SYNCHRONIZED collection if you need them in a multi-threaded Java program. they lock the whole collection or map whenever a thread reads or writes. Concurrent collection classes e.g. ConcurrentHashMap, CopyOnWriteArrayList and BlockingQueue to provide more scalability and performance. 79. What do you mean by SYNCHRONIZED Non Access Modifier? Java provides these modifiers for providing functionalities other than Access Modifiers, SYNCHRONIZED used to indicate that a method can be accessed by only one thread at a time. 80. What is BlockingQueue, how it is different than other collection classes? BlockingQueue is a Queue implementation available in java.util.concurrent package. It's one of the concurrent Collection class added on Java 1.5, main difference between BlockingQueue and other collection classes is that apart from storage, it also provides flow control. It can be used in inter thread communication and also provides built-in thread-safety by using happens-before guarantee. You can use BlockingQueue to solve Producer Consumer problem, which is what is needed in most of concurrent applications. 81. Synchronized thread error public class Bees Bees, public static void main(string[] args) try new Bees().go(); catch (Exception e) // We own the monitor on System.out.println("thrown to main"); synchronized void go() throws InterruptedException Thread t1 = new Thread(); // We DON T own the monitor thread T1, t1.start(); System.out.print("1 "); t1.wait(5000); //IllegalMonitorStateException thrown since we don t //own the object s monitor System.out.print("2 "); What is the result? A) The program prints 1 then 2 after 5 seconds B) The program prints: 1 thrown to main C) The program prints: 1 2 thrown to main D) The program prints:1 then t1 waits for its notification. So the first trick into working this one out is to work out what type of Exception is being thrown, because it s not an InterruptedException! Turns out it s an IllegalMonitorStateException, which is thrown when the current thread does not own the object s monitor. But what does that mean, since we re in a synchronized block, so shouldn t we own the current monitor? We own the monitor on Bees, and not the thread t1. 33

34 82. Synchronized? A. A static method cannot be synchroniz*d. B. If a class has synchronized code, multiple threads can still access the nonsynchronized code. C. Variables can be protected from concurrent access problems by marking them with the synchronizedkeyword. D. When a thread sleeps, it releases its locks. Correct Answer: Option B Explanation: B is correct because multiple threads are allowed to enter nonsynchronized code, even within a class that has some synchronized methods. A is incorrect because static methods can be synchronized; they synchronize on the lock on the instance of class java. lang.class that represents the class type. C is incorrect because only methodsâ not variablesâ can be marked synchronized. D is incorrect because a sleeping thread still maintains its locks. 83. When to synchronize? public class SyncTest public static void main (String [] args) Thread t = new Thread() Foo f = new Foo(); public void run() f.increase(20); ; t.start(); class Foo private int data = 23; public void increase(int amt) int x = data; data = x + amt; 34

35 and assuming that data must be protected from corruption, whatâ if anythingâ can you add to the preceding code to ensure the integrity of data? A. Synchronize the run method. B. Wrap a synchronize(this) around the call to f.increase(). C. The existing code will cause a runtime exception. D. Synchronize the increase() method Correct Answer: Option D Explanation: Option D is correct because synchronizing the code that actually does the increase will protect the code from being accessed by more than one thread at a time. Option A is incorrect because synchronizing the run() method would stop other threads from running the run() method (a bad idea) but still would not prevent other threads with other runnables from accessing the increase() method. Option B is incorrect for virtually the same reason as Aâ synchronizing the code that calls the increase()method does not prevent other code from calling the increase() method. 84. Synchronized methods? public class Test public static void main(string[] args) final StringBuffer a = new StringBuffer(); final StringBuffer b = new StringBuffer(); new Thread() public void run() System.out.print(a. append("a")); synchronized(b) System.out.print(b. append("b"));.start(); new Thread() public void run() System.out.print(b. append("c")); synchronized(a) System.out.print(a. append("d"));.start(); A. ACCBAD B. ABBCAD C. CDDACB D. Indeterminate output 35

36 Correct Answer: Option D Explanation: It gives different output while executing the same compiled code at different times. C:\>javac Test.java C:\>java Test ABBCAD C:\>java Test ACADCB C:\>java Test ACBCBAD C:\>java Test ABBCAD C:\>java Test ACBCBAD C:\>java Test ACBCBAD C:\>java Test ABBCAD 85. Thread execution order when synchronized? class Test116 static final StringBuffer sb1 = new StringBuffer(); static final StringBuffer sb2 = new StringBuffer(); public static void main(string args[]) new Thread() public void run() synchronized(sb1) sb1.append("a"); sb2.append("b");.start(); new Thread() public void run() synchronized(sb1) sb1.append("c"); sb2.append("d");.start(); /* Line 28 */ System.out.println (sb1 + " " + sb2); 36

37 A. main() will finish before starting threads. B. main() will finish in the middle of one thread. C. main() will finish after one thread. D. Cannot be determined. Correct Answer: Option D Explanation: Can you guarantee the order in which threads are going to run? No you can't. So how do you know what the output will be? The output cannot be determined. add this code after line 28: try Thread. sleep(5000); catch(interruptedexception e) and you have some chance of predicting the outcome. 86. Write a Program to solve Producer Consumer problem in Java? inter thread communication code or not. This is the very minimum requirement for a Java developer e.g. by using concurrent collections like blocking queue, by using wait and notify and by using other synchronizers of Java 5 e.g. semaphores. Producer Consumer Pattern simple development. you can Code Producer and Consumer independently and Concurrently, they just need to know shared object. 37 Producer doesn't need to know about who is consumer or how many consumers are there. Same is true ith Consumer. Producer and Consumer can work with different speed. There is no risk of Consumer consuming half-baked item. In fact by monitoring consumer speed one can introduce more consumer for better utilization. Separating producer and Consumer functionality result in more clean, readable and manageable code. Since we have replaced BlockingQueue with Vector we need to implement blocking using wait and notify and that's why we have introduced produce(int i) and consume() method. If you see I have kept consumer thread little slow by allowing it to sleep for 50 Milli second to give an opportunity to producer to fill the queue, which helps to understand that Producer thread is also waiting when Queue is full. import java.util.vector; import java.util.logging.level; import java.util.logging.logger; /** * Java program to solve Producer Consumer problem using wait and notify * method in Java. Producer Consumer is also a popular concurrency design pattern. * Javin Paul

38 */ public class ProducerConsumerSolution public static void main(string args[]) Vector sharedqueue = new Vector(); int size = 4; Thread prodthread = new Thread(new Producer(sharedQueue, size), "Producer"); Thread consthread = new Thread(new Consumer(sharedQueue, size), "Consumer"); prodthread.start(); consthread.start(); class Producer implements Runnable private final Vector sharedqueue; private final int SIZE; public Producer(Vector sharedqueue, int size) this.sharedqueue = sharedqueue; this.size = public void run() for (int i = 0; i < 7; i++) System.out.println("Produced: " + i); try produce(i); catch (InterruptedException ex) Logger.getLogger(Producer.class.getName()).log(Level.SEVERE, null, ex); private void produce(int i) throws InterruptedException //wait if queue is full while (sharedqueue.size() == SIZE) SYNCHRONIZED (sharedqueue) System.out.println("Queue is full " + Thread.currentThread().getName() + " is waiting, size: " + sharedqueue.size()); sharedqueue.wait(); //producing element and notify consumers SYNCHRONIZED (sharedqueue) sharedqueue.add(i); sharedqueue.notifyall(); class Consumer implements Runnable private final Vector sharedqueue; private final int SIZE; 38

39 public Consumer(Vector sharedqueue, int size) this.sharedqueue = sharedqueue; this.size = public void run() while (true) try System.out.println("Consumed: " + consume()); Thread.sleep(50); catch (InterruptedException ex) Logger.getLogger(Consumer.class.getName()).log(Level.SEVERE, null, ex); private int consume() throws InterruptedException //wait if queue is empty while (sharedqueue.isempty()) SYNCHRONIZED (sharedqueue) System.out.println("Queue is empty " + Thread.currentThread().getName() + " is waiting, size: " + sharedqueue.size()); sharedqueue.wait(); //Otherwise consume element and notify waiting producer SYNCHRONIZED (sharedqueue) sharedqueue.notifyall(); return (Integer) sharedqueue.remove(0); Output: Produced: 0 Queue is empty Consumer is waiting, size: 0 Produced: 1 Consumed: 0 Produced: 2 Produced: 3 Produced: 4 Produced: 5 Queue is full Producer is waiting, size: 4 Consumed: 1 Produced: 6 Queue is full Producer is waiting, size: 4 Consumed: 2 39

40 Consumed: 3 Consumed: 4 Consumed: 5 Consumed: 6 Queue is empty Consumer is waiting, size: Synchronized code? public class Q126 implements Runnable private int x; private int y; public static void main(string [] args) Q126 that = new Q126(); (new Thread(that)).start( ); /* Line 8 */ (new Thread(that)).start( ); /* Line 9 */ public synchronized void run( ) /* Line 11 */ for (;;) /* Line 13 */ x++; y++; System.out.println("x = " + x + "y = " + y); A. An error at line 11 causes compilation to fail B. Errors at lines 8 and 9 cause compilation to fail. C. The program prints pairs of values for x and y that might not always be the same on the same line (for example, "x=2, y=1") D. The program prints pairs of values for x and y that are always the same on the same line (for example, "x=1, y=1". In addition, each value appears once (for example, "x=1, y=1" followed by "x=2, y=2") Correct Answer: Option D Explanation: The synchronized code is the key to answering this question. Because x and y are both incremented 40

41 inside the synchronized method they are always incremented together. Also keep in mind that the two threads share the same reference to the Q126 object. Also note that because of the infinite loop at line 13, only one thread ever gets to execute. 88. Why wait and notify methods are declared in Object class? owned by object not thread that's why it make sense to keep those method on java.lang.object class. 89. Checking a Thread is alive or not check a thread is alive or not by extending Thread class and using currentthread() method. public class TwoThreadAlive extends Thread public void run() for (int i = 0; i < 10; i++) printmsg(); public void printmsg() Thread t = Thread.currentThread(); String name = t.getname(); System.out.println("name=" + name); public static void main(string[] args) TwoThreadAlive tt = new TwoThreadAlive(); tt.setname("thread"); System.out.println("before start(), tt.isalive()=" + tt.isalive()); tt.start(); System.out.println("just after start(), tt.isalive()=" + tt.isalive()); for (int i = 0; i < 10; i++) tt.printmsg(); System.out.println("The end of main(), tt.isalive()=" + tt.isalive()); Result: The above code sample will produce the following result. before start(),tt.isalive()=false just after start(), tt.isalive()=true name=main name=main name=main name=main name=main name=thread name=thread name=thread 41

42 42 name=thread name=thread name=thread name=thread name=main name=main The end of main().tt.isalive()=false 90. Monitoring a thread's status extending Thread class and using currentthread.getname() method. class MyThread extends Thread boolean waiting= true; boolean ready= false; MyThread() public void run() String thrdname = Thread.currentThread().getName(); System.out.println(thrdName + " starting."); while(waiting) System.out.println("waiting:"+waiting); System.out.println("waiting..."); startwait(); try Thread.sleep(1000); catch(exception exc) System.out.println(thrdName + " interrupted."); System.out.println(thrdName + " terminating."); SYNCHRONIZED void startwait() try while(!ready) wait(); catch(interruptedexception exc) System.out.println("wait() interrupted"); SYNCHRONIZED void notice() ready = true; notify(); public class Main public static void main(string args[]) throws Exception MyThread thrd = new MyThread(); thrd.setname("mythread #1"); showthreadstatus(thrd); thrd.start(); Thread.sleep(50); showthreadstatus(thrd); thrd.waiting = false; Thread.sleep(50); showthreadstatus(thrd); thrd.notice(); Thread.sleep(50); showthreadstatus(thrd); while(thrd.isalive()) System.out.println("alive");

43 showthreadstatus(thrd); static void showthreadstatus(thread thrd) System.out.println(thrd.getName()+" Alive:="+thrd.isAlive()+" State:=" + thrd.getstate() ); Result: The above code sample will produce the following result. main Alive=true State:=running 91. How to check a thread has stopped or not? 43 checking with isalive() method. public class Main public static void main(string[] argv) throws Exception Thread thread = new MyThread(); thread.start(); if (thread.isalive()) System.out.println("Thread has not finished"); else System.out.println("Finished"); long delaymillis = 5000; thread.join(delaymillis); if (thread.isalive()) System.out.println("thread has not finished"); else System.out.println("Finished"); thread.join(); class MyThread extends Thread boolean stop = false; public void run() while (true) if (stop) return; Result: The above code sample will produce the following result. Thread has not finished Finished 92. How to get the priorities of running threads? use setpriority() method public class SimplePriorities extends Thread private int countdown = 5; private volatile double d = 0; public SimplePriorities(int priority) setpriority(priority); start();

44 public String tostring() return super.tostring() + ": " + countdown; public void run() while(true) for(int i = 1; i < ; i++) d = d + (Math.PI + Math.E) / (double)i; System.out.println(this); if(--countdown == return; public static void main(string[] args) new SimplePriorities(Thread.MAX_PRIORITY); for(int i = 0; i < 5; i++) new SimplePriorities(Thread.MIN_PRIORITY); Result: The above code sample will produce the following result. Thread[Thread-0,10,main]: 5 Thread[Thread-0,10,main]: 4 Thread[Thread-0,10,main]: 3 Thread[Thread-0,10,main]: 2 Thread[Thread-0,10,main]: 1 Thread[Thread-1,1,main]: 5 Thread[Thread-1,1,main]: 4 Thread[Thread-1,1,main]: 3 Thread[Thread-1,1,main]: 2 Thread[Thread-1,1,main]: 1 Thread[Thread-2,1,main]: 5 Thread[Thread-2,1,main]: 4 Thread[Thread-2,1,main]: 3 Thread[Thread-2,1,main]: 2 Thread[Thread-2,1,main]: What s the difference between notify() and notifyall()? notify() is used to unblock one waiting thread; notifyall() is used to unblock all of them. Using notify() is preferable (for efficiency) when only one blocked thread can benefit from the change (for example, when freeing a buffer back into a pool). notifyall() is necessary (for correctness) if multiple threads should resume 94. How do you solve producer consumer problem in Java? producer consumer pattern. There are two ways to solve this problem in Java, One by using wait and notify method and other by using BlockingQueue 44

45 threadsafety and blocking nature of BlockingQueue and how that helps, while writing concurrent code. You can also expect many follow-up questions including, what happen, if you have multiple producer or multiple consumer, what will happen if producer is faster than consumer thread or vice-versa. 95. What is difference between submit () and execute () method of Executor and ExecutorService in Java? ExecutorService INTERFACE submit () return a result in form of Future object, execute () doesn't return result. By the way, both are used to submit task to thread pool in Java but one is defined in Executor INTERFACE, while other is added into ExecutorService INTERFACE. This multithreading interview question is also asked at first round of Java interviews. 96. What is ReadWriteLock in Java? What is benefit of using ReadWriteLock in Java? Java concurrency questions. ReadWriteLock is again based upon lock striping by providing separate lock for reading and writing operations. Reading operation can be done without locking if there is no writer and that can hugely improve performance of any application. ReadWriteLock leverage this idea and provide policies to allow maximum concurrency level. Java Concurrency API also provides an implementation of this concept as ReentrantReadWriteLock. Depending upon Interviewer and experience of candidate, you can even expect to provide your own implementation of ReadWriteLock, so be preparing for that as well. 97. What are differences between wait and sleep method in java? wait release the lock, Wait is used for inter-thread communication sleep doesn t release any lock, while sleep is used to introduce pause on execution. 98. Write code to implement blocking queue in Java? This is relatively tough java multi-threading interview question which servers many purpose, it checks whether candidate can actually write Java code using thread or not, it sees how good candidate is on understanding concurrent scenarios and you can ask lot of follow-up question based upon his code. If he uses wait() and notify() method to implement blocking queue, 99. Write a program, which will result in deadlock? How will you fix deadlock in Java? deadlock is quite common while writing multi-threaded concurrent program many candidates not able to write deadlock free code and they simply struggle. Just ask them you have n resources and n thread and to complete an operation you require all resources. Here n can be replace with 2 for simplest case and higher number to make question more intimidating What is race condition? How will you find and solve race condition? Another multi-threading question in Java, which appear mostly on senior level interviews. "Concurrency practices in Java'" How will you take thread dump in Java? How will you analyze Thread dump? In UNIX you can use kill -3 and then thread dump will print on log on 45

46 windows you can use "CTRL+Break". Rather simple and focus thread interview question but can get tricky if he ask how you analyze it. Thread dump can be useful to analyze deadlock situations as well How will you awake a blocked thread in java? blocking can result on many ways, if thread is blocked on IO then I don't think there is a way to interrupt the thread, if thread is blocked due to result of calling wait (), sleep () or join () method you can interrupt the thread and it will awake by throwing InterruptedException What is Busy Spinning? Why you will use Busy Spinning as wait strategy? This is really an advanced concurrency interview questions in Java and only asked to experienced and senior Java developers, with lots of concurrent coding experience under belt. By the way concept of busy spinning is not new, but it's usage with multi core processor has risen recently. It's a wait strategy, where one thread wait for a condition to become true, but instead of calling wait or sleep method and releasing CPU, it just spin. This is particularly useful if condition is going to be true quite quickly i.e. in millisecond or microsecond. Advantage of not releasing CPU is that, all cached data and instruction are remained unaffected, which may be lost, had this thread is suspended on one core and brought back to another thread. If you can answer this question, that rest assure of a good impression What are some common problems you have faced in multi-threading environment? How did you resolve it? Memory-interference, race conditions, deadlock, live lock starvation 46

47 Mutex vs Semaphore Java multi threads example to show you how to use Semaphore and Mutex to limit the number of threads to access resources. Mutex Only one thread to access a resource at once. Example, when a client is accessing a file, no one else should have access the same file at the same time. Semaphores Restrict the number of threads that can access a resource. Example, limit max 10 connections to access a file simultaneously. Consider the standard producer-consumer problem. producer thread will collect the data and writes it to the buffer. consumer thread will process the collected data from the buffer. Objective is, both the threads should not run at the same time. Using Mutex: A mutex provides mutual exclusion, either producer or consumer can have the key (mutex) and proceed with their work. As long as the buffer is filled by producer, the consumer needs to wait, and vice versa. Strictly speaking, a mutex is locking mechanism used to synchronize access to a resource. Only one task (can be a thread or process based on OS abstraction) can acquire the mutex. Mutex is the Semaphore with an access count of 1. // protect access to shared data private Object lock = new Object(); Create a Runnable object as the body of your thread: public class Worker implements Runnable public void run() // body of thread Then, use a Thread object to execute the run method in a new thread: Worker w = new Worker(); Thread t = new Thread(w); t.start(); 105. Synchronized blocks 47 Rather than having standalone method calls to lock and unlock a Java monitor, Java instead uses the synchronized keyword to identify regions of code that are critical sections. Simple example: a shared counter (synchronized blocks in bold): public class SharedCounter private Object lock = new Object(); private int count; public SharedCounter()

48 this.count = 0; public void increment() synchronized (lock) count++; public int get() synchronized (lock) return count; 106. The wait and notifyall methods wait until a condition involving shared data becomes true, and notify other threads that shared data has changed (possibly enabling a condition that other threads are waiting for) Because each Java monitors is both a mutex and a condition variable, the wait operation does not need to specify a lock object explicitly the monitor's internal lock is automatically released and then reacquired. Example: adding a waitthreshold method to the SharedCounter class: public void waitthreshold(int value) throws InterruptedException synchronized (lock) while (count < value) lock.wait(); Note that we also have to change the increment method: public void increment() synchronized (lock) count++; // shared data has changed: // notify other thread(s) that may // be waiting lock.notifyall(); Note that we have declared the waitthreshold method to throw InterruptedException. While a thread is waiting on a monitor, it may be "interrupted" by another thread. If a thread is interrupted in this way, its call to wait does not return normally, but instead throws InterruptedException. This mechanism can be used to "cancel" potentially long-running operations involving waiting on the state of shared data. In practical terms, it means that every time we call the wait method we must either handle InterruptedException using try/catch, or declare the method as throwing InterruptedException. 48

49 107. Reason Why Wait, Notify and NotifyAll are in Object Class. 1. Wait and notify is not just normal methods or synchronization utility, more than that they are communication mechanism between two threads in Java. And Object class is correct place to make them available for every object if this mechanism is not available via any java keyword like synchronized. Remember synchronized and wait notify are two different area and don t confuse that they are same or related. Synchronized is to provide mutual exclusion and ensuring thread safety of Java class like race condition while wait and notify are communication mechanism between two thread. 2. Locks are made available on per Object basis, which is another reason wait and notify is declared in Object class rather then Thread class. 3. In Java in order to enter critical section of code, Threads needs lock and they wait for lock, they don't know which threads holds lock instead they just know the lock is hold by some thread and they should wait for lock instead of knowing which thread is inside the synchronized block and asking them to release lock. this analogy fits with wait and notify being on object class rather than thread in Java Java monitors are recursive One peculiarity of Java monitors is that they are recursive: it is legal for a thread to re-acquire a monitor that it has already locked. You can think of each Java monitor as having an internal counter that keeps track of how many times the thread currently holding the lock has entered a synchronized block using that monitor. The monitor is only released (allowing other threads to access it) when the count reaches 0. In theory, recursive locks allow a method which involves synchronization to invoke another method which synchronizes on the same lock without worrying about self-deadlock. As a contrast, note that pthreads mutex locks are not recursive: if a thread in a pthreads program calls pthread_mutex_lock on a mutex twice without an intevening call to pthread_mutex_unlock, the thread will instantly deadlock itself. In practice, it is best to avoid having methods which use synchronization call each other directly. Instead, each method which uses synchronization should call helper methods which do not use synchronization. One way to think about this is that all helper methods that directly access shared data have "the monitor must be locked" as a precondition. Then the "front-end" methods that provide high-level operations on the data can acquire the monitor, call the helper methods, and then release the monitor: public void highleveloperation() synchronized (lock)... code... lowlevelhelper();... code... /* * Precondition: the lock must have been acquired already. */ private void lowlevelhelper()... operations that directly use/modify shared data... Synchronized Methods Java allows entire methods to be marked as synchronized. For example, in our SharedCounter class, we could omit the lock field and object, and instead mark the methods accessing shared data as 49

50 synchronized: public class StupidCounter private int count; public StupidCounter() this.count = 0; public synchronized void increment() count++; this.notifyall(); public synchronized int get() return count; public synchronized void waitthreshold(int value) throws InterruptedException while (count < value) this.wait(); You'll notice that there are no longer any explicit synchronized blocks. Instead, each method which is marked with the synchronized keyword implicitly treats its body as if it were contained inside a synchronized block. The question is then "what monitor is locked and unlocked"? The answer is that the object on which the synchronized method is called is locked and unlocked. We can see this because the waitthreshold method makes the call this.wait(); to wait on its condition, implying that "this" is the lock associated with the condition. This is why synchronized methods are a bad idea. They make the mechanism used to synchronize access to the shared data, which is a private implementation detail of the class, and expose it to the world. The main danger is that there is nothing preventing users of the shared counter object from performing synchronization. For example: StupidCounter c = new StupidCounter();... code... // trivially deadlock all threads which are using the counter synchronized (c) while (true) Thread.sleep(1000); So, always use explicit lock objects to protect your class's shared data. Semaphore: A semaphore is a generalized mutex. In lieu of single buffer, we can split the 4 KB buffer into four 1 KB buffers (identical resources). A semaphore can be associated with these four buffers. The consumer and producer can work on different 50

51 buffers at the same time. Semaphore is signaling mechanism ( I am done, you can carry on kind of signal). For example, if you are listening songs (assume it as one task) on your mobile and at the same time your friend called you, an interrupt will be triggered upon which an interrupt service routine (ISR) will signal the call processing task to wakeup. MutexTest.java package com.mkyong; import java.util.concurrent.semaphore; public class SemaphoreTest // max 1 people static Semaphore semaphore = new Semaphore(1); static class MyLockerThread extends Thread String name = ""; MyLockerThread(String name) this.name = name; public void run() try System.out.println(name + " : acquiring lock..."); System.out.println(name + " : available Semaphore permits now: " + semaphore.availablepermits()); semaphore.acquire(); System.out.println(name + " : got the permit!"); try for (int i = 1; i <= 5; i++) finally System.out.println(name + " : is performing operation " + i + ", available Semaphore permits : " + semaphore.availablepermits()); // sleep 1 second Thread.sleep(1000); " // calling release() after a successful acquire() System.out.println(name + " : releasing lock..."); semaphore.release(); System.out.println(name + " : available Semaphore permits now: + semaphore.availablepermits()); catch (InterruptedException e) e.printstacktrace(); 51

52 public static void main(string[] args) System.out.println("Total available Semaphore permits : " + semaphore.availablepermits()); MyLockerThread t1 = new MyLockerThread("A"); t1.start(); MyLockerThread t2 = new MyLockerThread("B"); t2.start(); MyLockerThread t3 = new MyLockerThread("C"); t3.start(); MyLockerThread t4 = new MyLockerThread("D"); t4.start(); MyLockerThread t5 = new MyLockerThread("E"); t5.start(); MyLockerThread t6 = new MyLockerThread("F"); t6.start(); Total available Semaphore permits : 1 A : acquiring lock... B : acquiring lock... A : available Semaphore permits now: 1 C : acquiring lock... B : available Semaphore permits now: 1 C : available Semaphore permits now: 0 A : got the permit! D : acquiring lock... E : acquiring lock... A : is performing operation 1, available Semaphore permits : 0 E : available Semaphore permits now: 0 D : available Semaphore permits now: 0 F : acquiring lock... F : available Semaphore permits now: 0 A : is performing operation 2, available Semaphore permits : 0 A : is performing operation 3, available Semaphore permits : 0 A : is performing operation 4, available Semaphore permits : 0 A : is performing operation 5, available Semaphore permits : 0 A : releasing lock... A : available Semaphore permits now: 1 B : got the permit! B : is performing operation 1, available Semaphore permits : 0 B : is performing operation 2, available Semaphore permits : 0 B : is performing operation 3, available Semaphore permits : 0 B : is performing operation 4, available Semaphore permits : 0 B : is performing operation 5, available Semaphore permits : 0 B : releasing lock... B : available Semaphore permits now: 1 C : got the permit! C : is performing operation 1, available Semaphore permits : 0 C : is performing operation 2, available Semaphore permits : 0 C : is performing operation 3, available Semaphore permits : 0 C : is performing operation 4, available Semaphore permits : 0 C : is performing operation 5, available Semaphore permits : 0 C : releasing lock... 52

53 C : available Semaphore permits now: 1 E : got the permit! E : is performing operation 1, available Semaphore permits : 0 E : is performing operation 2, available Semaphore permits : 0 E : is performing operation 3, available Semaphore permits : 0 E : is performing operation 4, available Semaphore permits : 0 E : is performing operation 5, available Semaphore permits : 0 E : releasing lock... E : available Semaphore permits now: 1 D : got the permit! D : is performing operation 1, available Semaphore permits : 0 D : is performing operation 2, available Semaphore permits : 0 D : is performing operation 3, available Semaphore permits : 0 D : is performing operation 4, available Semaphore permits : 0 D : is performing operation 5, available Semaphore permits : 0 D : releasing lock... D : available Semaphore permits now: 1 F : got the permit! F : is performing operation 1, available Semaphore permits : 0 F : is performing operation 2, available Semaphore permits : 0 F : is performing operation 3, available Semaphore permits : 0 F : is performing operation 4, available Semaphore permits : 0 F : is performing operation 5, available Semaphore permits : 0 F : releasing lock... F : available Semaphore permits now: 1 53 General Questions: 109. Can a thread acquire more than one lock (Mutex)? Yes, it is possible that a thread will be in need of more than one resource, hence the locks. If any lock is not available the thread will wait (block) on the lock Can a mutex be locked more than once? A mutex is a lock. Only one state (locked/unlocked) is associated with it. However, a recursive mutex can be locked more than once (POSIX complaint systems), in which a count is associated with it, yet retains only one state (locked/unlocked). The programmer must unlock the mutex as many number times as it was locked What will happen if a non-recursive mutex is locked more than once. Deadlock. If a thread which had already locked a mutex, tries to lock the mutex again, it will enter into the waiting list of that mutex, which results in deadlock. It is because no other thread can unlock the mutex. An operating system implementer can exercise care in identifying the owner of mutex and return if it is already locked by same thread to prevent deadlocks Are binary semaphore and mutex same? A programmer can prefer mutex rather than creating a semaphore with count Can we acquire mutex/semaphore in an Interrupt Service Routine? An ISR will run asynchronously in the context of current running thread. The ISR are meant be short, the call to mutex/semaphore may block the current running thread. However, an ISR can signal a semaphore or unlock a mutex Is it necessary that a thread must block always when resource is not available? Not necessarily.

54 For example POSIX pthread_mutex_trylock() API. When the mutex is not available the function will return immediately where as the API pthread_mutex_lock() will block the thread till resource is available Let's first discuss about Memory Barrier which are the base for our further discussions. There are two type of memory barrier instructions in JMM read barriers A read barrier invalidates the local memory (cache, registers, etc) and then reads the contents from the main memory, so that changes made by other threads becomes visible to the current Thread. write barrier. A write barrier flushes out the contents of the processor's local memory to the main memory, so that changes made by the current Thread becomes visible to the other threads How do you ensure that N thread can access N resources without deadlock if you acquire resources in a particular order and release resources in reverse order you can prevent deadlock What is difference between CyclicBarrier and CountDownLatch in Java can reuse CyclicBarrier even if Barrier is broken but you can not reuse CountDownLatch in Java What is the Stack Size: Each thread in the VM get s a stack. The stack size will limit the number of threads that you can have, too big of a stack size and you will run out of memory as each thread is allocated more memory than it needs. -Xss determines the size of the stack: Xss1024k. If the stack space is too small, eventually you will see an exception class java.lang.stackoverflowerror Daemon Thread in Java? Daemon threads in Java are like a service providers for other threads or objects running in the same process as the daemon thread. Daemon threads are used for background supporting tasks and are only needed while normal threads are executing. If normal threads are not running and remaining threads are daemon threads then the interpreter exits Which method is used to create the daemon thread? setdaemon method is used to create a daemon thread Can a lock be acquired on a class? Yes, a lock can be acquired on a class. This lock is acquired on the class Class object What state does a thread enter when it terminates its processing? enters the dead state What is difference between calling start() and run() method of Thread? start() method calls the run() method eventually then why not just call the run() method? Well the 54

55 difference is, start method also starts a new thread. If you call the run method directly then it will run on same thread not on different thread, which is what original intention would be What are the ways in which a thread can enter the waiting state? A thread can enter the waiting state by invoking its sleep() method, by blocking on IO, 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 How does multi-threading take place on a computer with a single CPU? 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 What invokes a thread's run() method? After a thread is started, via its start() method of the Thread class, the JVM invokes the thread's run() method when the thread is initially executed What is the difference between yielding and sleeping? 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 How can a dead thread be restarted? A dead thread cannot be restarted What is difference between Executor.submit () and Executer.execute () method? Executor.submit () returns an object of Future, which can be used to find result from worker thread) 130. Difference between fail-fast Iterator vs fail-safe Iterator in Java - Collections fail-fast Iterator As name suggest fail-fast Iterators fail as soon as they realized that structure of Collection has been changed since iteration has begun. Structural changes means adding, removing or updating any element from collection while one thread is Iterating over that collection. fail-fast behavior is implemented by keeping a modification count and if iteration thread realizes the change in modification counts it throws ConcurrentModificationException. fail-safe Iterator doesn't throw any Exception if Collection is modified structurally while one thread is Iterating over it because they work on clone of Collection instead of original collection and that s why they are called as fail-safe iterator. Iterator of CopyOnWriteArrayList is an example of fail-safe Iterator also iterator written by ConcurrentHashMap keyset is also fail-safe iterator and never throws ConcurrentModificationException in Java 131. Write a Java program to prevent deadlock in Java? 55

56 Deadlock happens if four conditions is true e.g. mutual exclusion, no waiting, circular wait and no preemption. If you can break any of this condition than you can create Java programs, which are deadlock proof. One easy way to avoid deadlock is by imposing an ordering on acquisition and release of locks How do you ensure that N thread can access N resources without deadlock f you acquire resources in a particular order and release resources in reverse order you can prevent deadlock. See how to avoid deadlock in Java for a sample code example is it possible for Thread 2 to print x=0? Yes, It's possible that thread T2 may print x=0.why? because without any instruction to compiler e.g. SYNCHRONIZED or volatile, bexit=true might come before x=1 in compiler reordering. Also x=1 might not become visible in Thread 2, so Thread 2 will load x=0. Now, how do you fix it? When I asked this question to couple of programmers they answer differently, one suggest to make both thread SYNCHRONIZED on a common mutex, another one said make both variable volatile. Both are correct, as it will prevent reordering and guarantee visibility. But best answer is you just need to make bexit as volatile, then Thread 2 can only print x=1. x does not need to be volatile because x cannot be reordered to come after bexit=true when bexit is volatile What is Busy Spinning? Why Should You Use It in Java? busy spinning is a waiting strategy, in which a thread just wait in a loop, without releasing the CPU for going to sleep. This is a very advanced and specialized waiting strategy used in the high-frequency trading application when wait time between two messages is very minimal. By not releasing the CPU or suspending the thread, your thread retains all the cached data and instruction, which may be lost if the thread was suspended and resumed back in a different core of CPU. This question is quite popular in high-frequency low latency programming domain, where programmers are trying for extremely low latency in the range of micro to milliseconds Is ++ operator is thread-safe in Java? 56

JAVA - MULTITHREADING

JAVA - MULTITHREADING JAVA - MULTITHREADING http://www.tutorialspoint.com/java/java_multithreading.htm Copyright tutorialspoint.com Java is amultithreaded programming language which means we can develop mult it hreaded program

More information

Threads Questions Important Questions

Threads Questions Important Questions Threads Questions Important Questions https://dzone.com/articles/threads-top-80-interview https://www.journaldev.com/1162/java-multithreading-concurrency-interviewquestions-answers https://www.javatpoint.com/java-multithreading-interview-questions

More information

Software Practice 1 - Multithreading

Software Practice 1 - Multithreading Software Practice 1 - Multithreading What is the thread Life cycle of thread How to create thread Thread method Lab practice Prof. Joonwon Lee T.A. Jaehyun Song Jongseok Kim T.A. Sujin Oh Junseong Lee

More information

7. MULTITHREDED PROGRAMMING

7. MULTITHREDED PROGRAMMING 7. MULTITHREDED PROGRAMMING What is thread? A thread is a single sequential flow of control within a program. Thread is a path of the execution in a program. Muti-Threading: Executing more than one thread

More information

Multitasking Multitasking allows several activities to occur concurrently on the computer. A distinction is usually made between: Process-based multit

Multitasking Multitasking allows several activities to occur concurrently on the computer. A distinction is usually made between: Process-based multit Threads Multitasking Multitasking allows several activities to occur concurrently on the computer. A distinction is usually made between: Process-based multitasking Thread-based multitasking Multitasking

More information

UNIT V CONCURRENT PROGRAMMING

UNIT V CONCURRENT PROGRAMMING UNIT V CONCURRENT PROGRAMMING Multi-Threading: Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run concurrently. Each part of such

More information

1 Shyam sir JAVA Notes

1 Shyam sir JAVA Notes 1 Shyam sir JAVA Notes 1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write

More information

Computation Abstractions. Processes vs. Threads. So, What Is a Thread? CMSC 433 Programming Language Technologies and Paradigms Spring 2007

Computation Abstractions. Processes vs. Threads. So, What Is a Thread? CMSC 433 Programming Language Technologies and Paradigms Spring 2007 CMSC 433 Programming Language Technologies and Paradigms Spring 2007 Threads and Synchronization May 8, 2007 Computation Abstractions t1 t1 t4 t2 t1 t2 t5 t3 p1 p2 p3 p4 CPU 1 CPU 2 A computer Processes

More information

27/04/2012. We re going to build Multithreading Application. Objectives. MultiThreading. Multithreading Applications. What are Threads?

27/04/2012. We re going to build Multithreading Application. Objectives. MultiThreading. Multithreading Applications. What are Threads? Objectives MultiThreading What are Threads? Interrupting threads Thread properties By Võ Văn Hải Faculty of Information Technologies Summer 2012 Threads priorities Synchronization Callables and Futures

More information

MultiThreading 07/01/2013. Session objectives. Introduction. Introduction. Advanced Java Programming Course

MultiThreading 07/01/2013. Session objectives. Introduction. Introduction. Advanced Java Programming Course Advanced Java Programming Course MultiThreading By Võ Văn Hải Faculty of Information Technologies Industrial University of Ho Chi Minh City Session objectives Introduction Creating thread Thread class

More information

Advanced Java Programming Course. MultiThreading. By Võ Văn Hải Faculty of Information Technologies Industrial University of Ho Chi Minh City

Advanced Java Programming Course. MultiThreading. By Võ Văn Hải Faculty of Information Technologies Industrial University of Ho Chi Minh City Advanced Java Programming Course MultiThreading By Võ Văn Hải Faculty of Information Technologies Industrial University of Ho Chi Minh City Session objectives Introduction Creating thread Thread class

More information

Avoiding magic numbers

Avoiding magic numbers Avoiding magic numbers Variables takes on a small set of values Use descriptive names instead of literal values Java enumerations Using in a switch statement 2 Magic numbers Where did the value come from?

More information

Unit - IV Multi-Threading

Unit - IV Multi-Threading Unit - IV Multi-Threading 1 Uni Processing In the early days of computer only one program will occupy the memory. The second program must be in waiting. The second program will be entered whenever first

More information

Quiz on Tuesday April 13. CS 361 Concurrent programming Drexel University Fall 2004 Lecture 4. Java facts and questions. Things to try in Java

Quiz on Tuesday April 13. CS 361 Concurrent programming Drexel University Fall 2004 Lecture 4. Java facts and questions. Things to try in Java CS 361 Concurrent programming Drexel University Fall 2004 Lecture 4 Bruce Char and Vera Zaychik. All rights reserved by the author. Permission is given to students enrolled in CS361 Fall 2004 to reproduce

More information

CS 251 Intermediate Programming More on classes

CS 251 Intermediate Programming More on classes CS 251 Intermediate Programming More on classes Brooke Chenoweth University of New Mexico Spring 2018 Empty Class public class EmptyClass { Has inherited methods and fields from parent (in this case, Object)

More information

15CS45 : OBJECT ORIENTED CONCEPTS

15CS45 : OBJECT ORIENTED CONCEPTS 15CS45 : OBJECT ORIENTED CONCEPTS QUESTION BANK: What do you know about Java? What are the supported platforms by Java Programming Language? List any five features of Java? Why is Java Architectural Neutral?

More information

JAVA and J2EE UNIT - 4 Multithreaded Programming And Event Handling

JAVA and J2EE UNIT - 4 Multithreaded Programming And Event Handling JAVA and J2EE UNIT - 4 Multithreaded Programming And Event Handling Multithreaded Programming Topics Multi Threaded Programming What are threads? How to make the classes threadable; Extending threads;

More information

Compaq Interview Questions And Answers

Compaq Interview Questions And Answers Part A: Q1. What are the difference between java and C++? Java adopts byte code whereas C++ does not C++ supports destructor whereas java does not support. Multiple inheritance possible in C++ but not

More information

B2.52-R3: INTRODUCTION TO OBJECT ORIENTATED PROGRAMMING THROUGH JAVA

B2.52-R3: INTRODUCTION TO OBJECT ORIENTATED PROGRAMMING THROUGH JAVA B2.52-R3: INTRODUCTION TO OBJECT ORIENTATED PROGRAMMING THROUGH JAVA NOTE: 1. There are TWO PARTS in this Module/Paper. PART ONE contains FOUR questions and PART TWO contains FIVE questions. 2. PART ONE

More information

Object Oriented Programming (II-Year CSE II-Sem-R09)

Object Oriented Programming (II-Year CSE II-Sem-R09) (II-Year CSE II-Sem-R09) Unit-VI Prepared By: A.SHARATH KUMAR M.Tech Asst. Professor JAWAHARLAL NEHRU TECHNOLOGICAL UNIVERSITY, HYDERABAD. (Kukatpally, Hyderabad) Multithreading A thread is a single sequential

More information

CMSC 433 Programming Language Technologies and Paradigms. Concurrency

CMSC 433 Programming Language Technologies and Paradigms. Concurrency CMSC 433 Programming Language Technologies and Paradigms Concurrency What is Concurrency? Simple definition Sequential programs have one thread of control Concurrent programs have many Concurrency vs.

More information

What is a thread anyway?

What is a thread anyway? Concurrency in Java What is a thread anyway? Smallest sequence of instructions that can be managed independently by a scheduler There can be multiple threads within a process Threads can execute concurrently

More information

Note: Each loop has 5 iterations in the ThreeLoopTest program.

Note: Each loop has 5 iterations in the ThreeLoopTest program. Lecture 23 Multithreading Introduction Multithreading is the ability to do multiple things at once with in the same application. It provides finer granularity of concurrency. A thread sometimes called

More information

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS PAUL L. BAILEY Abstract. This documents amalgamates various descriptions found on the internet, mostly from Oracle or Wikipedia. Very little of this

More information

Java s Implementation of Concurrency, and how to use it in our applications.

Java s Implementation of Concurrency, and how to use it in our applications. Java s Implementation of Concurrency, and how to use it in our applications. 1 An application running on a single CPU often appears to perform many tasks at the same time. For example, a streaming audio/video

More information

Multithreaded Programming Part II. CSE 219 Stony Brook University, Department of Computer Science

Multithreaded Programming Part II. CSE 219 Stony Brook University, Department of Computer Science Multithreaded Programming Part II CSE 219 Stony Brook University, Thread Scheduling In a Java application, main is a thread on its own Once multiple threads are made Runnable the thread scheduler of the

More information

Multithreaded Programming

Multithreaded Programming Multithreaded Programming Multithreaded programming basics Concurrency is the ability to run multiple parts of the program in parallel. In Concurrent programming, there are two units of execution: Processes

More information

Unit 5 - Exception Handling & Multithreaded

Unit 5 - Exception Handling & Multithreaded Exceptions Handling An exception (or exceptional event) is a problem that arises during the execution of a program. When an Exception occurs the normal flow of the program is disrupted and the program/application

More information

CMSC 132: Object-Oriented Programming II. Threads in Java

CMSC 132: Object-Oriented Programming II. Threads in Java CMSC 132: Object-Oriented Programming II Threads in Java 1 Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read & write files

More information

Java Threads. COMP 585 Noteset #2 1

Java Threads. COMP 585 Noteset #2 1 Java Threads The topic of threads overlaps the boundary between software development and operation systems. Words like process, task, and thread may mean different things depending on the author and the

More information

Network Programming COSC 1176/1179. Lecture 6 Concurrent Programming (2)

Network Programming COSC 1176/1179. Lecture 6 Concurrent Programming (2) Network Programming COSC 1176/1179 Lecture 6 Concurrent Programming (2) Threads Recall from last week Every line of Java code is part of a thread There can be one or more threads running in parallel Each

More information

UNIT IV MULTITHREADING AND GENERIC PROGRAMMING

UNIT IV MULTITHREADING AND GENERIC PROGRAMMING UNIT IV MULTITHREADING AND GENERIC PROGRAMMING Differences between multithreading and multitasking, thread life cycle, creating threads, creating threads, synchronizing threads, Inter-thread communication,

More information

Chapter 32 Multithreading and Parallel Programming

Chapter 32 Multithreading and Parallel Programming Chapter 32 Multithreading and Parallel Programming 1 Objectives To get an overview of multithreading ( 32.2). To develop task classes by implementing the Runnable interface ( 32.3). To create threads to

More information

Core Java Interview Questions and Answers.

Core Java Interview Questions and Answers. Core Java Interview Questions and Answers. Q: What is the difference between an Interface and an Abstract class? A: An abstract class can have instance methods that implement a default behavior. An Interface

More information

JAVA CONCURRENCY FRAMEWORK. Kaushik Kanetkar

JAVA CONCURRENCY FRAMEWORK. Kaushik Kanetkar JAVA CONCURRENCY FRAMEWORK Kaushik Kanetkar Old days One CPU, executing one single program at a time No overlap of work/processes Lots of slack time CPU not completely utilized What is Concurrency Concurrency

More information

Concurrent Programming using Threads

Concurrent Programming using Threads Concurrent Programming using Threads Threads are a control mechanism that enable you to write concurrent programs. You can think of a thread in an object-oriented language as a special kind of system object

More information

CST242 Concurrency Page 1

CST242 Concurrency Page 1 CST242 Concurrency Page 1 1 2 3 4 5 6 7 9 Concurrency CST242 Concurrent Processing (Page 1) Only computers with multiple processors can truly execute multiple instructions concurrently On single-processor

More information

Unit III Rupali Sherekar 2017

Unit III Rupali Sherekar 2017 Unit III Exceptions An exception is an abnormal condition that arises in a code sequence at run time. In other words, an exception is a run-time error. In computer languages that do not support exception

More information

Unit 4. Thread class & Runnable Interface. Inter Thread Communication

Unit 4. Thread class & Runnable Interface. Inter Thread Communication Unit 4 Thread class & Runnable Interface. Inter Thread Communication 1 Multithreaded Programming Java provides built-in support for multithreaded programming. A multithreaded program contains two or more

More information

Chair of Software Engineering. Java and C# in depth. Carlo A. Furia, Marco Piccioni, Bertrand Meyer. Java: concurrency

Chair of Software Engineering. Java and C# in depth. Carlo A. Furia, Marco Piccioni, Bertrand Meyer. Java: concurrency Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer Java: concurrency Outline Java threads thread implementation sleep, interrupt, and join threads that return values Thread synchronization

More information

04-Java Multithreading

04-Java Multithreading 04-Java Multithreading Join Google+ community http://goo.gl/u7qvs You can ask all your doubts, questions and queries by posting on this G+ community during/after webinar http://openandroidlearning.org

More information

CS 159: Parallel Processing

CS 159: Parallel Processing Outline: Concurrency using Java CS 159: Parallel Processing Spring 2007 Processes vs Threads Thread basics Synchronization Locks Examples Avoiding problems Immutable objects Atomic operations High"level

More information

What is Serialization?

What is Serialization? Serialization 1 Topics What is Serialization? What is preserved when an object is serialized? Transient keyword Process of serialization Process of deserialization Version control Changing the default

More information

Programmazione Avanzata e Paradigmi Ingegneria e Scienze Informatiche - UNIBO a.a 2013/2014 Lecturer: Alessandro Ricci

Programmazione Avanzata e Paradigmi Ingegneria e Scienze Informatiche - UNIBO a.a 2013/2014 Lecturer: Alessandro Ricci v1.0 20130323 Programmazione Avanzata e Paradigmi Ingegneria e Scienze Informatiche - UNIBO a.a 2013/2014 Lecturer: Alessandro Ricci [module lab 2.1] CONCURRENT PROGRAMMING IN JAVA: INTRODUCTION 1 CONCURRENT

More information

Java Lectures. Enhancements in Java 1.5

Java Lectures. Enhancements in Java 1.5 1 Enhancements in Java 1.5 2 Generics Enhancement to the type system: a type or method can operate on objects of various types with compile-time type safety, compile-time type safety to the Collections

More information

20 Most Important Java Programming Interview Questions. Powered by

20 Most Important Java Programming Interview Questions. Powered by 20 Most Important Java Programming Interview Questions Powered by 1. What's the difference between an interface and an abstract class? An abstract class is a class that is only partially implemented by

More information

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS Chapter 1 : Chapter-wise Java Multiple Choice Questions and Answers Interview MCQs Java Programming questions and answers with explanation for interview, competitive examination and entrance test. Fully

More information

CIS233J Java Programming II. Threads

CIS233J Java Programming II. Threads CIS233J Java Programming II Threads Introduction The purpose of this document is to introduce the basic concepts about threads (also know as concurrency.) Definition of a Thread A thread is a single sequential

More information

Object Oriented Programming. Week 10 Part 1 Threads

Object Oriented Programming. Week 10 Part 1 Threads Object Oriented Programming Week 10 Part 1 Threads Lecture Concurrency, Multitasking, Process and Threads Thread Priority and State Java Multithreading Extending the Thread Class Defining a Class that

More information

Module - 4 Multi-Threaded Programming

Module - 4 Multi-Threaded Programming Terminologies Module - 4 Multi-Threaded Programming Process: A program under execution is called as process. Thread: A smallest component of a process that can be executed independently. OR A thread is

More information

Basics of. Multithreading in Java

Basics of. Multithreading in Java Basics of programming 3 Multithreading in Java Thread basics Motivation in most cases sequential (single threaded) applications are not adequate it s easier to decompose tasks into separate instruction

More information

COP 3330 Final Exam Review

COP 3330 Final Exam Review COP 3330 Final Exam Review I. The Basics (Chapters 2, 5, 6) a. comments b. identifiers, reserved words c. white space d. compilers vs. interpreters e. syntax, semantics f. errors i. syntax ii. run-time

More information

COURSE 11 PROGRAMMING III OOP. JAVA LANGUAGE

COURSE 11 PROGRAMMING III OOP. JAVA LANGUAGE COURSE 11 PROGRAMMING III OOP. JAVA LANGUAGE PREVIOUS COURSE CONTENT Input/Output Streams Text Files Byte Files RandomAcessFile Exceptions Serialization NIO COURSE CONTENT Threads Threads lifecycle Thread

More information

The Sun s Java Certification and its Possible Role in the Joint Teaching Material

The Sun s Java Certification and its Possible Role in the Joint Teaching Material The Sun s Java Certification and its Possible Role in the Joint Teaching Material Nataša Ibrajter Faculty of Science Department of Mathematics and Informatics Novi Sad 1 Contents Kinds of Sun Certified

More information

Page 1

Page 1 Java 1. Core java a. Core Java Programming Introduction of Java Introduction to Java; features of Java Comparison with C and C++ Download and install JDK/JRE (Environment variables set up) The JDK Directory

More information

Advanced Programming Methods. Lecture 6 - Concurrency in Java (1)

Advanced Programming Methods. Lecture 6 - Concurrency in Java (1) Advanced Programming Methods Lecture 6 - Concurrency in Java (1) Overview Introduction Java threads Java.util.concurrent References NOTE: The slides are based on the following free tutorials. You may want

More information

Multi-threading in Java. Jeff HUANG

Multi-threading in Java. Jeff HUANG Multi-threading in Java Jeff HUANG Software Engineering Group @HKUST Do you use them? 2 Do u know their internals? 3 Let s see File DB How can they service so many clients simultaneously? l 4 Multi-threading

More information

PESIT Bangalore South Campus

PESIT Bangalore South Campus PESIT Bangalore South Campus 15CS45 : OBJECT ORIENTED CONCEPTS Faculty : Prof. Sajeevan K, Prof. Hanumanth Pujar Course Description: No of Sessions: 56 This course introduces computer programming using

More information

Synchronized Methods of Old Versions of Java

Synchronized Methods of Old Versions of Java Administrivia Assignment #4 is out Due Thursday April 8, 10:00pm no late assignments will be accepted Sign up in labs next week for a demo time In case you hadn t noticed Classes end Thursday April 15

More information

CS 2112 Lecture 20 Synchronization 5 April 2012 Lecturer: Andrew Myers

CS 2112 Lecture 20 Synchronization 5 April 2012 Lecturer: Andrew Myers CS 2112 Lecture 20 Synchronization 5 April 2012 Lecturer: Andrew Myers 1 Critical sections and atomicity We have been seeing that sharing mutable objects between different threads is tricky We need some

More information

Multithread Computing

Multithread Computing Multithread Computing About This Lecture Purpose To learn multithread programming in Java What You Will Learn ¾ Benefits of multithreading ¾ Class Thread and interface Runnable ¾ Thread methods and thread

More information

Advanced Programming Concurrency

Advanced Programming Concurrency Advanced Programming Concurrency Concurrent Programming Until now, a program was a sequence of operations, executing one after another. In a concurrent program, several sequences of operations may execute

More information

Casting -Allows a narrowing assignment by asking the Java compiler to "trust us"

Casting -Allows a narrowing assignment by asking the Java compiler to trust us Primitives Integral types: int, short, long, char, byte Floating point types: double, float Boolean types: boolean -passed by value (copied when returned or passed as actual parameters) Arithmetic Operators:

More information

Amity School of Engineering

Amity School of Engineering Amity School of Engineering B.Tech., CSE(5 th Semester) Java Programming Topic: Multithreading ANIL SAROLIYA 1 Multitasking and Multithreading Multitasking refers to a computer's ability to perform multiple

More information

By: Abhishek Khare (SVIM - INDORE M.P)

By: Abhishek Khare (SVIM - INDORE M.P) By: Abhishek Khare (SVIM - INDORE M.P) MCA 405 Elective I (A) Java Programming & Technology UNIT-2 Interface,Multithreading,Exception Handling Interfaces : defining an interface, implementing & applying

More information

Parallel Programming Practice

Parallel Programming Practice Parallel Programming Practice Threads and Tasks Susanne Cech Previtali Thomas Gross Last update: 2009-10-29, 09:12 Thread objects java.lang.thread Each thread is associated with an instance of the class

More information

Threads and Java Memory Model

Threads and Java Memory Model Threads and Java Memory Model Oleg Šelajev @shelajev oleg@zeroturnaround.com October 6, 2014 Agenda Threads Basic synchronization Java Memory Model Concurrency Concurrency - several computations are executing

More information

IBS Software Services Technical Interview Questions. Q1. What is the difference between declaration and definition?

IBS Software Services Technical Interview Questions. Q1. What is the difference between declaration and definition? IBS Software Services Technical Interview Questions Q1. What is the difference between declaration and definition? The declaration tells the compiler that at some later point we plan to present the definition

More information

The New Java Technology Memory Model

The New Java Technology Memory Model The New Java Technology Memory Model java.sun.com/javaone/sf Jeremy Manson and William Pugh http://www.cs.umd.edu/~pugh 1 Audience Assume you are familiar with basics of Java technology-based threads (

More information

The Java Memory Model

The Java Memory Model The Java Memory Model What is it and why would I want one? Jörg Domaschka. ART Group, Institute for Distributed Systems Ulm University, Germany December 14, 2009 public class WhatDoIPrint{ static int x

More information

CISC 4700 L01 Network & Client-Server Programming Spring Cowell Chapter 15: Writing Threaded Applications

CISC 4700 L01 Network & Client-Server Programming Spring Cowell Chapter 15: Writing Threaded Applications CISC 4700 L01 Network & Client-Server Programming Spring 2016 Cowell Chapter 15: Writing Threaded Applications Idea: application does simultaneous activities. Example: web browsers download text and graphics

More information

Performance Throughput Utilization of system resources

Performance Throughput Utilization of system resources Concurrency 1. Why concurrent programming?... 2 2. Evolution... 2 3. Definitions... 3 4. Concurrent languages... 5 5. Problems with concurrency... 6 6. Process Interactions... 7 7. Low-level Concurrency

More information

Threads. Definitions. Process Creation. Process. Thread Example. Thread. From Volume II

Threads. Definitions. Process Creation. Process. Thread Example. Thread. From Volume II Definitions A glossary Threads From Volume II Copyright 1998-2002 Delroy A. Brinkerhoff. All Rights Reserved. Threads Slide 1 of 30 PMultitasking: (concurrent ramming, multiramming) the illusion of running

More information

COMP31212: Concurrency A Review of Java Concurrency. Giles Reger

COMP31212: Concurrency A Review of Java Concurrency. Giles Reger COMP31212: Concurrency A Review of Java Concurrency Giles Reger Outline What are Java Threads? In Java, concurrency is achieved by Threads A Java Thread object is just an object on the heap, like any other

More information

Le L c e t c ur u e e 7 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Multithreading

Le L c e t c ur u e e 7 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Multithreading Course Name: Advanced Java Lecture 7 Topics to be covered Multithreading Thread--An Introduction Thread A thread is defined as the path of execution of a program. It is a sequence of instructions that

More information

Parallel Programming Practice

Parallel Programming Practice Parallel Programming Practice Threads and Tasks Susanne Cech Previtali Thomas Gross Last update: 2009-10-29, 09:12 Thread objects java.lang.thread Each thread is associated with an instance of the class

More information

THREADS & CONCURRENCY

THREADS & CONCURRENCY 27/04/2018 Sorry for the delay in getting slides for today 2 Another reason for the delay: Yesterday: 63 posts on the course Piazza yesterday. A7: If you received 100 for correctness (perhaps minus a late

More information

Pace University. Fundamental Concepts of CS121 1

Pace University. Fundamental Concepts of CS121 1 Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction

More information

Overview. Processes vs. Threads. Computation Abstractions. CMSC 433, Fall Michael Hicks 1

Overview. Processes vs. Threads. Computation Abstractions. CMSC 433, Fall Michael Hicks 1 CMSC 433 Programming Language Technologies and Paradigms Spring 2003 Threads and Synchronization April 1, 2003 Overview What are threads? Thread scheduling, data races, and synchronization Thread mechanisms

More information

Contents. 6-1 Copyright (c) N. Afshartous

Contents. 6-1 Copyright (c) N. Afshartous Contents 1. Classes and Objects 2. Inheritance 3. Interfaces 4. Exceptions and Error Handling 5. Intro to Concurrency 6. Concurrency in Java 7. Graphics and Animation 8. Applets 6-1 Copyright (c) 1999-2004

More information

Inheritance and Interfaces

Inheritance and Interfaces Inheritance and Interfaces Object Orientated Programming in Java Benjamin Kenwright Outline Review What is Inheritance? Why we need Inheritance? Syntax, Formatting,.. What is an Interface? Today s Practical

More information

Concurrency in Object Oriented Programs 1. Object-Oriented Software Development COMP4001 CSE UNSW Sydney Lecturer: John Potter

Concurrency in Object Oriented Programs 1. Object-Oriented Software Development COMP4001 CSE UNSW Sydney Lecturer: John Potter Concurrency in Object Oriented Programs 1 Object-Oriented Software Development COMP4001 CSE UNSW Sydney Lecturer: John Potter Outline Concurrency: the Future of Computing Java Concurrency Thread Safety

More information

Lecture 7 Java SE Multithreading

Lecture 7 Java SE Multithreading Lecture 7 Java SE Multithreading presentation Java Programming Software App Development Cristian Toma D.I.C.E/D.E.I.C Department of Economic Informatics & Cybernetics www.dice.ase.ro Cristian Toma Business

More information

Core Java - SCJP. Q2Technologies, Rajajinagar. Course content

Core Java - SCJP. Q2Technologies, Rajajinagar. Course content Core Java - SCJP Course content NOTE: For exam objectives refer to the SCJP 1.6 objectives. 1. Declarations and Access Control Java Refresher Identifiers & JavaBeans Legal Identifiers. Sun's Java Code

More information

Administrivia. Events this week Drop-In Resume and Cover Letter Editing Date: Tues., Mar 23 Time: 12:30 2:30 pm Location: Rm 255, ICICS/CS

Administrivia. Events this week Drop-In Resume and Cover Letter Editing Date: Tues., Mar 23 Time: 12:30 2:30 pm Location: Rm 255, ICICS/CS Department of Computer Science Undergraduate Events Events this week Drop-In Resume and Cover Letter Editing Date: Tues., Mar 23 Time: 12:30 2:30 pm Location: Rm 255, ICICS/CS ICICS/KPMG Seminar Presentation:

More information

Modern Programming Languages. Lecture Java Programming Language. An Introduction

Modern Programming Languages. Lecture Java Programming Language. An Introduction Modern Programming Languages Lecture 27-30 Java Programming Language An Introduction 107 Java was developed at Sun in the early 1990s and is based on C++. It looks very similar to C++ but it is significantly

More information

Java for Programmers Course (equivalent to SL 275) 36 Contact Hours

Java for Programmers Course (equivalent to SL 275) 36 Contact Hours Java for Programmers Course (equivalent to SL 275) 36 Contact Hours Course Overview This course teaches programmers the skills necessary to create Java programming system applications and satisfies the

More information

CPS221 Lecture: Threads

CPS221 Lecture: Threads Objectives CPS221 Lecture: Threads 1. To introduce threads in the context of processes 2. To introduce UML Activity Diagrams last revised 9/5/12 Materials: 1. Diagram showing state of memory for a process

More information

Some Interview Question-Answers on Java JAVA. dfghjklzxcvbnmqwertyuiopasdfghjklzx 1/10/2013. cvbnmqwertyuiopasdfghjklzxcvbnmq.

Some Interview Question-Answers on Java JAVA. dfghjklzxcvbnmqwertyuiopasdfghjklzx 1/10/2013. cvbnmqwertyuiopasdfghjklzxcvbnmq. qwertyuiopasdfghjklzxcvbnmqwertyui opasdfghjklzxcvbnmqwertyuiopasdfgh jklzxcvbnmqwertyuiopasdfghjklzxcvb nmqwertyuiopasdfghjklzxcvbnmqwer tyuiopasdfghjklzxcvbnmqwertyuiopas Some Interview Question-Answers

More information

Java Threads and intrinsic locks

Java Threads and intrinsic locks Java Threads and intrinsic locks 1. Java and OOP background fundamentals 1.1. Objects, methods and data One significant advantage of OOP (object oriented programming) is data encapsulation. Each object

More information

Overview. CMSC 330: Organization of Programming Languages. Concurrency. Multiprocessors. Processes vs. Threads. Computation Abstractions

Overview. CMSC 330: Organization of Programming Languages. Concurrency. Multiprocessors. Processes vs. Threads. Computation Abstractions CMSC 330: Organization of Programming Languages Multithreaded Programming Patterns in Java CMSC 330 2 Multiprocessors Description Multiple processing units (multiprocessor) From single microprocessor to

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

Thread Safety. Review. Today o Confinement o Threadsafe datatypes Required reading. Concurrency Wrapper Collections

Thread Safety. Review. Today o Confinement o Threadsafe datatypes Required reading. Concurrency Wrapper Collections Thread Safety Today o Confinement o Threadsafe datatypes Required reading Concurrency Wrapper Collections Optional reading The material in this lecture and the next lecture is inspired by an excellent

More information

Software Development & Education Center. Java Platform, Standard Edition 7 (JSE 7)

Software Development & Education Center. Java Platform, Standard Edition 7 (JSE 7) Software Development & Education Center Java Platform, Standard Edition 7 (JSE 7) Detailed Curriculum Getting Started What Is the Java Technology? Primary Goals of the Java Technology The Java Virtual

More information

Overview of Java Threads (Part 2)

Overview of Java Threads (Part 2) Overview of Java Threads (Part 2) Douglas C. Schmidt d.schmidt@vanderbilt.edu www.dre.vanderbilt.edu/~schmidt Institute for Software Integrated Systems Vanderbilt University Nashville, Tennessee, USA Learning

More information

Handling Multithreading Approach Using Java Nikita Goel, Vijaya Laxmi, Ankur Saxena Amity University Sector-125, Noida UP India

Handling Multithreading Approach Using Java Nikita Goel, Vijaya Laxmi, Ankur Saxena Amity University Sector-125, Noida UP India RESEARCH ARTICLE Handling Multithreading Approach Using Java Nikita Goel, Vijaya Laxmi, Ankur Saxena Amity University Sector-125, Noida UP-201303 - India OPEN ACCESS ABSTRACT This paper contains information

More information

G Programming Languages Spring 2010 Lecture 13. Robert Grimm, New York University

G Programming Languages Spring 2010 Lecture 13. Robert Grimm, New York University G22.2110-001 Programming Languages Spring 2010 Lecture 13 Robert Grimm, New York University 1 Review Last week Exceptions 2 Outline Concurrency Discussion of Final Sources for today s lecture: PLP, 12

More information

Need for synchronization: If threads comprise parts of our software systems, then they must communicate.

Need for synchronization: If threads comprise parts of our software systems, then they must communicate. Thread communication and synchronization There are two main aspects to Outline for Lecture 19 multithreaded programming in Java: I. Thread synchronization. thread lifecycle, and thread synchronization.

More information

THREADS AND CONCURRENCY

THREADS AND CONCURRENCY THREADS AND CONCURRENCY Lecture 22 CS2110 Spring 2013 Graphs summary 2 Dijkstra: given a vertex v, finds shortest path from v to x for each vertex x in the graph Key idea: maintain a 5-part invariant on

More information

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Weiss Chapter 1 terminology (parenthesized numbers are page numbers) Weiss Chapter 1 terminology (parenthesized numbers are page numbers) assignment operators In Java, used to alter the value of a variable. These operators include =, +=, -=, *=, and /=. (9) autoincrement

More information