Notes: not synchronized method is not thread safe, which means multiple thread can access the same method at the same time. Making the thread synchronized means only one thread can use the method at a time.
those trying to test this programs on your high end laptops, might see no matter u use a counter of 1000 or 5000 or even 10,000 to increment, you might still get the correct total of incremented value without even using SYNCHRONIZE keyword to sync the increment process between 2 threads. It just means your thread scheduler has a lot of resources available to be very efficient. In such cases, just increase the counter loop by a million (1,00,000) and then you will see the need of using the SYNCHRONIZE keyword as you will see an incorrect total. Hope it helps.
Another hint here: remove any "per iteration" console log. While in loop, let only the counting, otherwise writing to console will give enough time to threads so they behave almost "synchronized"
Try writing it as this Thread1.start(); Thread1.join(); Thread2.start(); Thread2.join(); Result: if you took for loop for 1000 or 1000000 each = 2000 or 2000000 respectively Without synchronised key word
champav basu... intha simple ga telchesav, thread safe synchronization yappati nundo doubt. simply superb. hyd lo unte kaludam we can have good biryani..
t1.start(); t1.join(); t2.start(); t2.join(); will fetch the same result without using the synchronized key word. BUT...WHAT YOU HAVE DONE FOR THE PURPOSE OF EXPLAINING ITS A PERFECT EXAMPLE.
In that case, its not multithreading because until t1 finish main thread can't create t2 thread so it will become sequential execution instead of multithreading .
all of you are correct. because in a multithreading application, there comes a time where another thread requires an object or value from another thread for processing. in that case, this comes in handy.
Synchronized block is used to lock an object for any shared resource. Scope of synchronized block is smaller than the method. A Java synchronized block doesn't allow more than one JVM, to provide access control to a shared resource.
This *synchronized* is a very big performance hit": *** mainThreadCall... Count: 2000000000 Done in: 125 milliseconds *** callingWithOneSeparateThread... Count: 2000000000 Done in: 129 milliseconds *** callingWithTwoThreads... (not synchronized method) Count: 1013362697 Done in: 67 milliseconds *** callingWithTwoThreadsAndSynchronizedMethod... Count: 2000000000 Done in: 67621 milliseconds Also on some conference I've seen an example where the "synchronized" did not help. I don't remember what was the case, but they had to do smething else. I think it was some I/O issue or with databases. Just a guess. Two synchronized threads are 540 times slower than one thread in my example (2,000,000,000 calls). But when there's less calls, it works fine (but still slower than in one thread).
But if after using Synchronized both the processes cant simultaneously access the integer and increment then why even using multi-threading then, wouldn't it take the same time as a single-threaded process ?
When u call join then it simply means main thread goes to sleep state and t1.join is running unless t1 not completely execute (dead) . When first thread is done his work then join wakeup the main thread and call next thread so it means our program has only one thread when we use join method . But we want running both thread parallel. Basically due to join delay our program so we don't use it in program generally....
Its like normal function called 2 times . Imagine that is a class vinayak{ private int counter=0; void increment(){ loop 1000 times {counter++;} } main class(){ vinayak.increment(); vinayak.increment(); } then the counter will stil be 2000. To avoid this we use threads for parallel process. many threads should not use the increment function at once. so to provide accessibility to one thread at a time.
The 2 threads that we are using can do stuff independently. They must only wait when using our synchronized method. In this example used for learning it is useless, it's true (the whole work is only +1 ~ lol). But imagine that instead of "+1" the thread had to do some other function/method. Then both threads can work at the same time and only have to wait for each other to finish, before using our synchronized method! Let's say thread 1 counts to 10 million and the other also. Both threads can count to 10 million independently, but then they have to wait before using the final method to save their work, so no data is lost. Saving their work (the threads work) can happen very fast, but their work not. So for example if we have 1 thread, you need to count to 20 million, then save. With 2 threads you can only count to 10 million twice at the same time, then save ( and add the numbers together and get 20 million). You save about half the time with 2 threads, because the waiting is very small compared to the work they do. I hope this is more clear now :)
anikeat bansal 1)Throws keyword is used to declare an exception.Exception can be handled by the calling method or it can be catches by that method. 2)It would work with this example.Because the time taken by the machine to perform this operation is so tiny.But how can you definitey tell how much a function will take to execute .If you wait any less than that you are running into trouble of thread collision and if u wait more..you are wasting time...And it also create hassle for the user/programmer who will call the function . However u can call thread.sleep() inside of the synchronized function but that will not open the lock when one thread is at sleep. There is a separate function called obj.wait() which an be used for that purpose .
Hi navin, I have one question in this concept of threading. My question is like let us have three threads t1, t2,t3. t1 shud print 1, t2 shud print 2, t3 shud print 3 , again t1 shud print 4, t2 shud 5 , t3 shud print 6 and so on like this . class Hi extends Thread { public synchronized void run(){ for(int i=1;i
thanks you for explain the concept very Cleary. I have one doubt , can we add volatile keyword to the count variable also and will it work simillar, If not can you please explain why?
Notes: not synchronized method is not thread safe, which means multiple thread can access the same method at the same time. Making the thread synchronized means only one thread can use the method at a time.
So if you want a method that can be used by one thread at a time
-then make that method synchronized()
@@andrejtrozic509 i was asked this question on an interview..its very imp
those trying to test this programs on your high end laptops, might see no matter u use a counter of 1000 or 5000 or even 10,000 to increment, you might still get the correct total of incremented value without even using SYNCHRONIZE keyword to sync the increment process between 2 threads. It just means your thread scheduler has a lot of resources available to be very efficient. In such cases, just increase the counter loop by a million (1,00,000) and then you will see the need of using the SYNCHRONIZE keyword as you will see an incorrect total. Hope it helps.
thanks mate
Thanks :)
Another hint here: remove any "per iteration" console log. While in loop, let only the counting, otherwise writing to console will give enough time to threads so they behave almost "synchronized"
Try writing it as this
Thread1.start();
Thread1.join();
Thread2.start();
Thread2.join();
Result: if you took for loop for 1000 or 1000000 each
= 2000 or 2000000 respectively
Without synchronised key word
@@sidharthbisoi1492simply adding synchronized diminishes the need for thread.join. however both things do the same
Very clear and simple example, thank you!
you cleared my doubt I did not skip any ad! Modern Guru Dakshina (and I learned If we don't skip first ad YT shows a second one)
champav basu... intha simple ga telchesav, thread safe synchronization yappati nundo doubt. simply superb. hyd lo unte kaludam we can have good biryani..
That is a gem of an explanation, thank you Sir!
Best Java Teacher in UA-cam 💯
t1.start();
t1.join();
t2.start();
t2.join();
will fetch the same result without using the synchronized key word.
BUT...WHAT YOU HAVE DONE FOR THE PURPOSE OF EXPLAINING ITS A PERFECT EXAMPLE.
your videos are very good. perfect point-to-point explanation such as mechanical students are also getting interested.
Bucky Roberts from India .
Amazing tutorials sir!
Godlike explanation, CLEAR AND SIMPLE !
if u use
t1.start ();
t1.join ();
t2.start ();
t2.join ();
then there is no need of synchronised method
btw u r a good teacher
In that case, its not multithreading because until t1 finish main thread can't create t2 thread so it will become sequential execution instead of multithreading .
In that case its not parallel processing .
all of you are correct. because in a multithreading application, there comes a time where another thread requires an object or value from another thread for processing. in that case, this comes in handy.
An amateur is asking this :
What's the Point of thread concept then???
Crisp and clear explanation!!
YOU are most talented navin.. best and simple way to understand that how u elaborate the concepts..
Awesome and very clear explanation and easy to understand
great sir very clear explanation
one of the best multithreading explanation on UA-cam
@Telusko
We need teachers like you in college : )
Synchronized block is used to lock an object for any shared resource.
Scope of synchronized block is smaller than the method.
A Java synchronized block doesn't allow more than one JVM, to provide access control to a shared resource.
thank u so much sir . such a beautiful explanation
Sir you are Legend for CS Students.
This *synchronized* is a very big performance hit":
*** mainThreadCall...
Count: 2000000000 Done in: 125 milliseconds
*** callingWithOneSeparateThread...
Count: 2000000000 Done in: 129 milliseconds
*** callingWithTwoThreads... (not synchronized method)
Count: 1013362697 Done in: 67 milliseconds
*** callingWithTwoThreadsAndSynchronizedMethod...
Count: 2000000000 Done in: 67621 milliseconds
Also on some conference I've seen an example where the "synchronized" did not help. I don't remember what was the case, but they had to do smething else. I think it was some I/O issue or with databases. Just a guess.
Two synchronized threads are 540 times slower than one thread in my example (2,000,000,000 calls). But when there's less calls, it works fine (but still slower than in one thread).
Great video, thank you! One of the best Java instructors
Excellent video, makes understanding very simple and easy!!
What an explaination sir .Just Wow.
Naveen,
You are an awesome teacher!!
explanation was crystal clear. Thanks a ton!
Thank you so much for creating such a useful video series ....it's been so useful for me...
Thank you for explaining it comprehensively.
awesome explanation with example
Excellent video, thanks so much, you made it easy and simple to understand :)
wow! crystal clear explanation.THANK YOU!
best channel ever
You saved me so much time...
Great example brother
Awesomeee.... so concise and perfect explanation
Thank you sir really it was helped me to understand this concept clearly
absolute best !!!!!telusko🔥🔥🔥🔥
Crystal clear!!!much appreciated!
Excellent explanation sir
Brilliant explanation, thanks for sharing!
this saved so much of my time! thank you so much!
Top class teaching ..👏👏👍
Well explained and to the point thank you so much for the amazing video!
Its really great. kudos to navin reddy
Damn cool explanation over this confusing topic....
Well explained sir.
Ahhhh Bossss! What an explanation!
But if after using Synchronized both the processes cant simultaneously access the integer and increment then why even using multi-threading then, wouldn't it take the same time as a single-threaded process ?
i learnt three things
1. Synchronized keyword
2. join method
3. Thread safe class
thaaaaaaanks very much & I hope you'll explain the Thread pool
thankyou so much for great explaination
Thanks a lot sir. You have very good explanation
Good Explanation.. Thanks
Great explanation....!!! Thank you.
I can't control the laugh. When both intelligent are adding the same value! :)
Thanks! great explanation on this topic!
Great video, nice explanation
The ways of your explanation is awesome...😊
nice explanation sir
@5:24 join() still presented for both right then why it's not giving 2000
Thank you very much for this very informative and clear video. It helped me a lot :D
good explanation. Thanks for the tutorial!
nicely explained good example. thanx..
Sir, I have a doubt
when use threads like this
t1.start();
t1.join();
t2.start();
t2.join();
we get 2000 without "synchronized " keyword
When u call join then it simply means main thread goes to sleep state and t1.join is running unless t1 not completely execute (dead) .
When first thread is done his work then join wakeup the main thread and call next thread so it means our program has only one thread when we use join method . But we want running both thread parallel.
Basically due to join delay our program so we don't use it in program generally....
Its like normal function called 2 times .
Imagine that is a
class vinayak{
private int counter=0;
void increment(){
loop 1000 times {counter++;}
}
main class(){
vinayak.increment();
vinayak.increment();
}
then the counter will stil be 2000. To avoid this we use threads for parallel process.
many threads should not use the increment function at once. so to provide accessibility to one thread at a time.
What happens when you call an unsynchronized method inside a synchronized method? Will the output be consistent?
Thanks for this question.
Because of this question, i tried calling unsynchronized method inside a synchronized method.
The output is consistent.
Thank You. Nicely explained
excellent video
I have query if we are making this method synchronized ( thread safe)then what is the use of using thread???? Please answer this..
The 2 threads that we are using can do stuff independently. They must only wait when using our synchronized method. In this example used for learning it is useless, it's true (the whole work is only +1 ~ lol). But imagine that instead of "+1" the thread had to do some other function/method. Then both threads can work at the same time and only have to wait for each other to finish, before using our synchronized method! Let's say thread 1 counts to 10 million and the other also. Both threads can count to 10 million independently, but then they have to wait before using the final method to save their work, so no data is lost. Saving their work (the threads work) can happen very fast, but their work not.
So for example if we have 1 thread, you need to count to 20 million, then save. With 2 threads you can only count to 10 million twice at the same time, then save ( and add the numbers together and get 20 million). You save about half the time with 2 threads, because the waiting is very small compared to the work they do.
I hope this is more clear now :)
Awesome tutorials
thank u soo much sir nice explanation...
It is a very good video. It helped me a lot.
I just love this intro !
very clear . thank you sir.
Can you make a video about hibernate? and lambda? thank youuuu
Good job sir
A question, why you didn’t use implements or extends ?
Thank you for the amazing video
Because he didn't make new classes for custom threads, he used the classes Thread and Runnable themselves, a month late but well...
Nice explained......
what is the benefit of assigning priority to a thread??
Our aim for using multithreading was parallel computing, but here we are using a single thread at a time. So how are we achieving that?
sir how we can refer to a non-final variable inside an inner class defined in a different method
Same.
Local variable c is accessed from within inner class;needs to be declared final..
Very helpful video
is there any difference if i run the same code in java 8? I did the same code without join() and i got 2000 everytime as the count
thank you, all the best!
Thanks! it helped me!
package com.advance;
class counter implements Runnable {
int count = 0;
public void incriment() {
count++;
}
public void run(){
counter obj=new counter();
obj.incriment();
}
}
public class SyncDemo {
public static void main(String[] args) throws Exception {
// write your code here
counter obj1 = new counter();
Thread t1=new Thread(obj1);
for(int i=1;i
Thank you very much.
Now I understand!
why we are using throws exception with join() ?
what if i use Thread.sleep() after t1.start() in place of synchronized?
anikeat bansal
1)Throws keyword is used to declare an exception.Exception can be handled by the calling method or it can be catches by that method.
2)It would work with this example.Because the time taken by the machine to perform this operation is so tiny.But how can you definitey tell how much a function will take to execute .If you wait any less than that you are running into trouble of thread collision and if u wait more..you are wasting time...And it also create hassle for the user/programmer who will call the function .
However u can call thread.sleep() inside of the synchronized function but that will not open the lock when one thread is at sleep.
There is a separate function called obj.wait() which an be used for that purpose .
Pretty clear 👍🏿👍🏿
by using join() on t1 and t2 are not we stopping main to access the increment method before the two finish? Is Synchronized still required?
Well explained
Sir can you please make a video on thread pool and thread group.
but sir u are giving the join method in t1 and t2 so it means t1 will work separately and also t2 then why the count is coming as weird
if only 1 thread is working at a time then why use thread concept??
Thankss u made it much easy..
Hi navin, I have one question in this concept of threading. My question is like let us have three threads t1, t2,t3. t1 shud print 1, t2 shud print 2, t3 shud print 3 , again t1 shud print 4, t2 shud 5 , t3 shud print 6 and so on like this .
class Hi extends Thread
{
public synchronized void run(){
for(int i=1;i
Thank you so much!!! It helped alot!!
Sir I getting an error on forloop at c what should I do .I am also updated jdk 7 to 8
thanks you for explain the concept very Cleary. I have one doubt , can we add volatile keyword to the count variable also and will it work simillar, If not can you please explain why?
can we put the count variable synchronized instead??