Java Multithreading Interview Questions

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
in this step we will start discussing about multi-threading what is the need for threads in Java and we would look at a lot of topics related to thread so you will look at how to create a thread how can you run a thread what are the different states that a thread can be in we would talk about thread priority executor service we will talk about callable and also we will talk about synchronization of threads before we move into threads there is something I would want to reiterate about generics there are three examples in the workspace one is genetics examples the other one is Generation X examples 2 and generics examples 3 there are a lot of jeddaks examples in this specific thing as well so you can try and spend some time with these generics examples so that you can understand genrich's much better so I would really recommend to spend at least 15 minutes with these examples try and read the comments which are there try and look at the examples and try and understand them perfectly that would really give you a good background on the generics let us now get back to the topic at hand which is multi-threading so what is it need for threads in Java so what is the need for threads in general if you look at your operating system your operating system basically has a number of processes running right so you have probably a Word document open you are playing a video in parallel you might be listening to music in parallel so your operating system should do multiple things in parallel so you have multiple processes running in parallel similar to that inside a java process inside a java program you want to do multiple things in parallel so you want to power follow multiple paths of execution multiple code you want to execute in parallel in those kinds of situations you would want to go with threads let's look at an example to understand why we need threads let's say we are developing a cricket statistics application you can kind of think of it like a bowling stir or a baseball statistics application so there are different departments in cricket bowling batting and fielding in baseball you would I guess called bowling ass pitching I think batting remains the same and fielding also remains the same so let us say I am developing a baseball application with the pitching the batting and fielding statistics kind of a thing I would want to download these statistics and merge and analyze let us say the current program whichever is present is doing it sequential II let us say the step one is to do the statistics for bowling and it takes 60 minutes step 2 is batting 60 minutes step 3 fielding and it takes 15 minutes to download and still the statistics and step 4 is to merge and analyze which is taking 25 minutes so to do the whole thing step by step we are wait we are taking a total of 160 minutes and let us say the requirement is that we should be able to run this program much much much faster let us say you want to run this program in half the time so threads can be one of the solutions to this problem threads because the downloading the bowling statistics independent of batting statistics and independent of down fielding statistics what we can try and do is kick off these in parallel so you can run this thread in parallel with this thread step one step two step three you can run them in parallel and then once all these steps are completed then I can start the merge and analyze thread this is typically how we do that right so example dot download and store batting statistics download and store bowling statistics filling statistics module nationalize this is serial so this is doing it sequential II we want to do that in parallel how do we do that so to be able to do that in parallel we need to be able to create threads so how do you create a thread there are two ways we can create threads one is extending the thread class so you would use inheritance and extend the thread class the other one is by implementing runnable interface so what we will do is will create the batting statistics thread extending the thread class and will create the bowling statistics thread implementing the runnable interface so let us go and see how the batting statistics thread can be done the basic way you can create a bad acoustics thread is by extending the thread class so we extends thread class and we are actually doing the defining the run method the most important thing is public void run so this is the signature you need to adhere to and you define inside this what you want to do as part of the batting statistics thread so here I am just having some dummy logic to loop up mm and print something in so that's how you extend a thread class and you create a thread so we are for the binding statistic thread we are exchanging the thread class and we are creating a thread how do you create a thread by implementing the runnable interface you can look at it here so it's basically implements runnable and you would define the same precise method so if you look at these two things batting statistics and bowling statistic threads there isn't a huge difference in there so it extends thread this one implements runnable but it's precisely the same method definition for ramp how do you run a thread in java running a thread in java it's a little different based on have you created the thread so if I created the thread you extending the thread class then I would run it differently compared to if I am implementing relabel interface let's quickly look at it earlier we saw that the batting statistics thread how did we create it we created it by extending threads class so we extended the thread class and created the batting statistics thread anything that is extending the thread class the way you would run it is just create the instance so I am creating babbling statistics thread is equal to jibe adding statistics thread and call start method the most important thing to remember is you are not calling the run method it is not the run method that you need to call you need to call the start method so here you are not invoking the run method you are calling the start method so that this can create a new thread and run in a separate thing the other kind of threads that we want to create are the ones created implementing the runnable interface we created the bowling statistics thread by implementing runnable so the way you would run bowling statistics thread is by creating a new thread and passing an instance of the bowling statistics thread so we create a bowling statistics thread we create an instance of the ball increased our districts thread and we pass it to a new thread and then we can call the start method on it so earlier we directly call this start method on the instance of the thread but when you implement the runnable interface it's there is one more step involved so you create an instance of the class which is implementing the runnable interface and you create an instance of the thread giving that instance to it so it's a new thread of new bowling statistics thread so that's what you do and you can then call this start method so this is how you would start a thread when it's created using the runnable interface when it is created implementing the runnable interface we looked at two things one is creating the batting statistics thread the other one is creating the bowling statistics thread and we have not understood how to kick off those two threads in parallel so you just need to have this code and call the start and here you create an instance of the class implementing the interface and use new thread and pass the instance we created and on the thread object called the start method now that we learn that we will now focus on the different states of a thread we will now focus on the different state for thread so what are the different states that a thread object can be in thread states are new runnable running blocked or terminated so those are the different states that a specific thread can be so let us say consider this piece of code so line one is batting thread is equal to new batting statistics thread and we say are starting the batting thread here and here bowling we are using the we are implementing the runnable interface so bowling statistics the way we are creating it is little different but on line five we start the batting thread so a thread is in new state when an object of the thread is created but start method is not yet called in the line one we are creating a new instance of the thread in the line two we are invoking this start method on the thread so at the completion of line one execution the batting surd is six thread is in a new state because the start method is not yet called on it so that is called a new state another example would be the bulding statistics thread so we are creating the thread here and before we start the thread so just after creating the line four I have just after executing line for the thread would be in a rough in a new state so that's the new state basically when the thread is created the instance of the thread is ready but you have not really called the start method on it the next two states that we would discuss a runnable and running once you kick off this start on a thread it can be in any of these four states so either the thread is right now running then it is called running state the thread is ready to run it is not waiting for anything but it's still not running then it is in a runnable state the thread is waiting for some IO to complete I am waiting for some resource or some other operation to complete so then I am in a blog or a waiting State if I have completed execution then I am in a terminated or a dead State so these are the five different states so if you actually run this program batteries realistics and the polling statistics thread together you would see that sometimes batting statistics run thread is running sometimes bounding statistics thread is running because they have equal priority what the CPU does I mean the way the CPU is allocated is CPU is allocated for some time to this some time to this some time to this and some time to this so when the batting thread is running then the bowling thread would be in the runnable state but it is not running because it is not the current thread which is running and when the bowling thread is running then the bowling thread is running state if the bowling thread is running then the batting's thread is in a weight kind of a state then that because the batting's thread is not really waiting for anything then it's in a state called runnable if the batting thread is waiting because it is waiting for some download to happen or some IO then it is called it's in a blocked State and when the batting state a thread completes execution then it goes into a state called the terminated State what is priority of a thread priority of this thread is very important in the sense that if a thread has higher priority then the scheduler might allocate more CPU to that thread so by default the priority which is assigned to a Java thread is 5 if I am NOT setting any priority then by default it gets a priority 5 but you can actually increase or decrease the priority so the range is 1 to 10 and if two threads are waiting then the scheduler ideally picks the thread with the highest priority to run the way you can set priority on the thread is by thread dot set priority so there is a max priority min priority constants that you can use to set the priority and they said so 10 is highest priority 1 is the least priority that you can assign to a thread the next thing that we want to talk about is the executor service what is executor service executor service is one of the newer interfaces which is present in Java and it's a cool new way of exiting tasks in the background so as you can kind of think of an executor service very similarly very similar to a thread Poole you have a spool of threads and you want to pick one of them and execute them here we see an example of an executor service we are creating a new thread executor so executors use single thread executors and we are assigning it to an executor service and then we can create a new thread I am creating a new thread by using the runnable interface I am implementing the runnable interface and creating a new thread and I can use the executed service to execute this thread and once this this thread would now be kicked off in parallel this executor service would kick off a new thread and it would complete execution so what are the different ways of creating executor services if I just want to create one thread then I can use executors dot new single thread executors if I would want to create a fixed thread pool then I would actually use the new fixed thread pool and how many threads that you would want to create if you want to use the scheduling feature I mean if you want to delay execution or things like that then you can create a new scheduled thread pool so here you can actually give some delay or execute certain threads periodically the great thing about an executor service is when you use an executor service to execute a task you can also check if the task has completed or not the way we do that is use something called a future so once you have an executor service one and submit a new runnable thing you can get the future as the output and once the task has completed then the future get method would return null the great thing about the executor service it's this new feature called callable with a column earlier or the only way threads can return a value is buying storing some value in a file or something of that kind but with callable what we are able to do is we are able to return a result from the thread so now you can say this is the result from the thread and I can take that value and print it here so if you look at it here future from callable I am calling a thread so I am creating a thread and the thread can actually result result back the syntax is a little disciplined instead of runnable we have caller bill interface and instead of run method we have a call method and we can return the result here and you can use the get method on the future to get the result from the caller ball what is synchronization of threads and why synchronization of threads needed let us look at a simple problem so you have this method so this is the method a very simple method so we have we are setting a value into cell 1 cell 2 and cell 3 and we are adding them and written it back but we have sleep for some time in between so in each of this we are actually sleeping for some time in between let us say this method is called in two different threads so if this method is called in two different threads then really funny things can happen so what could happen is the thread one has completed setting cell 1 cell 2 and cell 3 the threat and the execution has shifted to thread 2 and what the thread 2 did is it came in and it said the value for cell 1 so we have value for cell 1 which is set by the thread 2 and the value for cell - and cell 3 which is said by thread 1 so what would happen when thread 1 executes cell 1 plus L 2 s plus L 3 it will use this cell 1 value which was said by thread 2 so whatever value which thread 1 said that was overridden because can these threads are executing concurrently they are overriding the values which are said by one another and this is a very bad scenario because the thread 1 it thinks it asset the value properly and it tries to sum them up but actually the value which was set in cell 1 is the value which is currently in cell 1 is the value which is said by thread 2 and this can result in errors and a lot of bugs the way you can prevent multiple threads from executing the same method is by using this synchronized keyword so when I put a synchronized keyword on a method then what would happen only one thread can be executing this so once a thread is executing if thread 1 is executing in this specific code then thread 2 will not be able to do anything so thread 2 will come here see this method is synchronized okay I cannot run it it will wait wait wait until thread and completes execution in this example we are using synchronized keyword on a method so we are putting a synchronized keyword before the method so this would be a synchronized method and if I have ten synchronized methods in a class then only one thread can at a time be executing any of those methods all the other threads which want to execute any other method which is synchronized have to wait so within a class there can only be one thread that's executing any of the synchronized code in that particular class there is another concept called a synchronized block typically we use synchronized before method so synchronized word synchronize example or you can also have specific code in the method to be synchronized so let us say there is a hundred lines of code and I want only five lines of code to be synchronized I can use synchronize this around this specific thing how can a static method be synchronized yes you can synchronize a static method as well however the synchronized synchronization on the static methods is more at a class level it's not really at a instance level let's say I have two threads thread two and three three and I would want thread for to start only after thread three completed execution thread two three three and I want thread for to start only after three three completed execution so I am kicking off thread 3 and clicking of thread two and I am calling thread three join what basically happens here is what I call thread 3 Jorge join this code would wait for thread 3 to complete and only after the thread 3 is completed we would kick off the thread 4 so join is basically to wait for a specific thread to complete execution you can also use a timeline so here I am saying I would want to wait for 200 milliseconds or the end of execution of thread for let's say the thread for did not complete execution I mean the thread for did not complete execution by 2,000 milliseconds then it would the execution would proceed to the next line there are a lot of important methods in thread shields take a few of them and look at them in here thread yield method so healed is one of the static methods in the thread class yield is basically a thread saying okay I have enough execution time so please select another thread for execution so what would happen is when a thread called yield method then the state of the test would go from running to runnable however if there are no threads no other threads which are of higher priority then the scheduler might pick the same thread for running again the other method is thread sleep method this sleep method makes the thread goes in to go into a sleep board or a wait mode for a specified number of specified amount of time typically you specify the amount of time in milliseconds what is a deadlock a deadlock is the situation when two threads mutually are waiting for each other so if thread 1 is waiting for thread 2 and thread 2 is waiting for thread 1 then this situation is called a deadlock because they would keep waiting forever it can be even bigger kind of a cycle so thread 1 is waiting for thread 2 thread 2 is waiting for 3 3 3 3 is waiting for thread 1 so that's a bigger cycle but it's still a deadlock so what are the important methods in Java for inter thread communication the important methods are wait notify and notify all the weight and the notify methods are usually used in combination what happens is if I call it weight method on the thread then until the notify method is called on it it would keep waiting so when I call a weight method then it is basically saying I'll wait for another thread to notify me until I start execution so this is how you do a thread dot weight and notify is how it's shown in here if more than one thread is waiting for an object you can also use notify all to notify all the threads which are waiting so let's now look at a program where we would use most of the things that we discussed previously until then we have been discussing things theoretically let's kind of try and run a program which would make it interest more interesting for us I have a class called calculator and if you see this calculator extends thread and there is a run method in here there and inside a synchronized block I am also doing a notify and inside the main method what we are doing is we are creating an instance of the thread and doing a thread dot start and we are waiting on the thread so we are calling a thread dot wait as well what would happen is the main method would start waiting for the thread to give it a notify signal so you would see that in here you are seeing that when I run the program the main method wait for the entire execution of the run in the calculator and then wait for the notify once the notify is called the main method stop waiting and it would start executing this code let us see what would happen if this line was not there so let's say I comment out the whole block from here to here what would is the sum that would be printed I mean when I add up all these integers from zero to nine nine nine nine the result should be this but here I am NOT doing a wait for that specific thread you would see what is the main method printing it is printing 0 why because it is not waiting for the other thread to complete execution I really want the main method to wait until the other thread completes execution until the calculator threads executes so I would want to wait for the thread I would want to have a notify and only then complete execution so if you run this enough you are actually waiting so main is actually waiting for the thread to complete execution that's by thread dot wait and then you can print the result of the sum so that's in thread red cup I mean that is how you can have multiple threads communicate with each other so you have a thread called main from which you are clicking of another thread called calculator and you are trying to communicate between them by using the weight and then notify we discuss a lot of examples about threads executor service and the methods inside threads in this specific video what I recommend you to do is to take a look at the tread examples class so as an exercise I would recommend you to take it the thread examples class and you can look at all the things which are present in here and you can try and run the program and try and understand trends and how the output is getting generated so I would really recommend you to do that because it would really give you good understanding of what happens behind the thread so thread examples thread wait and notify are two things two classes that you can look at at the end of this video thanks a lot for watching until the next step bye-bye
Info
Channel: in28minutes Cloud, DevOps and Microservices
Views: 260,455
Rating: 4.6779323 out of 5
Keywords: in28minutes tutorial, Rao, java interview questions, Multithreading Interview Questions, java, Karanam, java multithreading, interview, in28minutes, Java Multithreading Interview Questions, Ranga, multithreading interview question in java, rithus, java interview questions and answers, java multithreading interview questions, java interview questions and answers for experienced
Id: AfVbJDr-8ic
Channel Id: undefined
Length: 24min 55sec (1495 seconds)
Published: Sun Sep 18 2016
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.