Rlog

Java 에서 thread.Interrupted 메소드를 사용해야 하는 이유 본문

Java

Java 에서 thread.Interrupted 메소드를 사용해야 하는 이유

dev_roach 2022. 7. 20. 23:28
728x90

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