Why we should use interrupt method in java
Why we should check thread was interrupted in multi-thread programming?
For Example, Can you expected result to this code?
When execute code, Thread start sleeping for 10000000 mils. And Main Thread is blocking by Other Thread. The application will not stop. So, we should kill sleeping Thread. In Java, we have two method to kill thread.
- call Interrupted()
- call stop() (it’s deprecated so we aren’t handle this)
What is Interrupt Thread?
Interrupt Method is raise an exception at interrupted thread. Why raise exception? Because, we should teardown(release resource) in interrupted thread. Look at the code below.
When the thread was interrupted, It doesn’t change the value of isActiveConnection to true. So, The other thread raise IllegalAccessException when they use this datasource. So, we should change the value is true.
Return Resources using Interrupted Exception
As i said before, interrupt method is raise exception at target thread. So we use this. Look at the code below.
We used try..catch expression for changing dataSource activeConnection status to false. This is why we use interrupt method when need to kill thread. How did if we used thread.stop method?
Use Thread.stop Method
This chapter we use stop method for kill thread. Look at the code below.
We just change interrupt method to stop method. Can you expect that result?
It’s not return resource (isActiveConnection). Because the stop method is just forcing kill thread. Not raise InterruptedException. So, we don’t use stop method in java.
Finally
This is why we should use interrupted method in java. Please do not use stop method. Stop method is deprecated in oracle java. If post is helpful to you, please subscribe me.
내 영문 블로그
https://medium.com/@dev0jsh/why-we-should-use-interrupt-method-in-java-61fffab0d231
'Java' 카테고리의 다른 글
Comparator 와 Comparable (2) | 2022.09.21 |
---|---|
JVM GC 정리 (1) | 2022.08.17 |
[Java] ByteArrayStream (0) | 2022.03.28 |
Jackson Databind 에서 is, get, set 을 이용하면 자동으로 값으로 인식하는 이유 (0) | 2022.03.22 |
[StackOverflow] 왜 자식생성자에서 super() 를 써야 하는가? (0) | 2022.02.03 |