interruptedexception java что это

Interrupted Exception

Недавно еще раз встретился с некорректной обработкой InterruptedException в java. InterruptedException — это checked exception генерируемый многими методами стандартной библиотеки, которые блокируют поток исполнения. К таким относятся: interruptible версии lock’ов, метод Thread.sleep(), некоторые операции над блокирующими очередями, некоторые операции над каналами и другие.

По своей сути, InterruptedException сигнализирует о том, что поток просят завершить его работу. При этом вас не просят немедленно завершить свою работу. Вас просят корректно завершить работу. На это может понадобится некоторое время.

Важно понимать, что interrupt адресуется не только вам (коду, который выполняется в потоке), но и владельцу потока. Другими словами, не только вы в этом потоке заинтересованы в том, чтобы определить что наступило прерывание.

Следующий код так же некорректен, потому что мы “маскируем” interrupt в исключительную ситуацию другого типа. Тем самым он не дает возможности вызывающей стороне зафиксировать ситуацию прерывания.

Корректный код будет выглядеть следующим образом.

Здесь мы ловим InterruptedException и выставляем флаг потока сигнализирующий о прерывании.

Внимательный читатель мог задать себе вопрос: “А зачем два способа сигнализации? Разве нельзя обойтись одним?”.

InterruptedException бывает неудобен по причине того, что это checked exception. Это значит что компилятор заставляет вас или обработать его по месту, или указать в своем контракте. В случае, если вы не можете указать InterruptedException в своем контракте (например, вы имплементируете интерфейс где в контракте InterruptedException не указан), флаг потока остается единственным способом передать вызывающей стороне информацию о прерывании.

InterruptedException позволяет прервать поток уже выполняющий блокирующий вызов. В случае, если метод уже выполняется, то существует только один способ прервать его выполнение без возврата какого-либо значения и не нарушая при этом его контракт, — сгенерировать исключительную ситуацию. В этом случае возвращаемое значение метода просто неопределено.

Источник

Interrupted Exception Class

Definition

Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.

Thrown when a thread is waiting, sleeping, or otherwise occupied, and the thread is interrupted, either before or during the activity.

Remarks

Portions of this page are modifications based on work created and shared by the Android Open Source Project and used according to terms described in the Creative Commons 2.5 Attribution License.

Constructors

Constructs an InterruptedException with no detail message.

A constructor used when creating managed representations of JNI objects; called by the runtime.

Constructs an InterruptedException with no detail message.

Fields

Properties

Returns the cause of this throwable or null if the cause is nonexistent or unknown.

(Inherited from Throwable) Class (Inherited from Throwable) Handle

The handle to the underlying Android instance.

(Inherited from Throwable) JniIdentityHashCode (Inherited from Throwable) JniPeerMembers LocalizedMessage

Creates a localized description of this throwable.

Returns the detail message string of this throwable.

(Inherited from Throwable) PeerReference (Inherited from Throwable) StackTrace (Inherited from Throwable) ThresholdClass

This API supports the Mono for Android infrastructure and is not intended to be used directly from your code.

This API supports the Mono for Android infrastructure and is not intended to be used directly from your code.

Читайте также:  профессия редактор какие бывают

Methods

Appends the specified exception to the exceptions that were suppressed in order to deliver this exception.

(Inherited from Throwable) Dispose() (Inherited from Throwable) Dispose(Boolean) (Inherited from Throwable) FillInStackTrace()

Fills in the execution stack trace.

Initializes the cause of this throwable to the specified value.

Prints this throwable and its backtrace to the standard error stream.

Prints this throwable and its backtrace to the standard error stream.

Prints this throwable and its backtrace to the standard error stream.

Sets the Handle property.

Sets the stack trace elements that will be returned by #getStackTrace() and printed by #printStackTrace() and related methods.

(Inherited from Throwable) ToString() (Inherited from Throwable) UnregisterFromRuntime() (Inherited from Throwable)

Explicit Interface Implementations

IJavaPeerable.Disposed() (Inherited from Throwable)
IJavaPeerable.DisposeUnlessReferenced() (Inherited from Throwable)
IJavaPeerable.Finalized() (Inherited from Throwable)
IJavaPeerable.JniManagedPeerState (Inherited from Throwable)
IJavaPeerable.SetJniIdentityHashCode(Int32) (Inherited from Throwable)
IJavaPeerable.SetJniManagedPeerState(JniManagedPeerStates) (Inherited from Throwable)
IJavaPeerable.SetPeerReference(JniObjectReference) (Inherited from Throwable)

Extension Methods

Performs an Android runtime-checked type conversion.

Источник

JavaLearnWeb

шпаргалки

InterruptedException: исключения в Java

InterruptedException — это checked exception генерируемый многими методами стандартной библиотеки, которые блокируют поток исполнения. К таким относятся: interruptible версии lock’ов, метод Thread.sleep(), некоторые операции над блокирующими очередями, некоторые операции над каналами и другие.

По сути, InterruptedException сигнализирует о том, что поток просят завершить его работу. При этом вас не просят немедленно завершить свою работу. Вас просят корректно завершить работу. На это может понадобится некоторое время. Прерывание потока осуществляется при помощи метода Thread.interrupt().

Существует два способа которыми JVM уведомляет поток о том, что его прерывают. Первый — это собственно InterruptedException. Второй — флаг потока INTERRUPT, который может быть получен при помощи метода Thread.isInterrupted(). Игнорирование второго метода сигнализирования о прерывании и является типичной ошибкой.

Если выдача InterruptedException означает, что метод является блокирующим, то вызов метода блокирования означает, что ваш метод также является блокирующим, и у вас должна быть стратегия для работы с InterruptedException. Зачастую наиболее простой стратегией является генерирование собственного InterruptedException, как показано в методах putTask() и getTask().

Выполняя это, вы также делаете ваш метод восприимчивым к прерыванию, и это для этого требуется всего-навсего добавить InterruptedException в вашу конструкцию throws.

Иногда необходимо произвести некоторую очистку, прежде чем распространить исключение. В этом случае вы можете перехватить InterruptedException, выполнить очистку, а затем повторно сгенерировать исключение.

InterruptedException позволяет прервать поток уже выполняющий блокирующий вызов. В случае, если метод уже выполняется, то существует только один способ прервать его выполнение без возврата какого-либо значения и не нарушая при этом его контракт, — сгенерировать исключительную ситуацию. В этом случае возвращаемое значение метода просто неопределено.

Источник

Обработка InterruptedException в Java

РЕДАКТИРОВАТЬ: Я хотел бы также знать, в каких сценариях используются эти два.

В чем разница между следующими способами обработки InterruptedException? Каков наилучший способ сделать это?

Прежде всего вы должны увидеть, throws InterruptedException что это такое: часть сигнатуры метода и возможный результат вызова метода, который вы вызываете. Итак, начнем с того, что следует признать тот факт, что an InterruptedException является вполне допустимым результатом вызова метода.

Теперь, если вызываемый вами метод выдает такое исключение, что должен делать ваш метод? Вы можете выяснить ответ, подумав о следующем:

Читайте также:  Что значит тэла в медицине

Кто-то прервал вашу тему. Что кто-то, вероятно, хочет отменить операцию, завершить программу изящно или что-то еще. Вы должны быть вежливы с этим человеком и возвращаться к своему методу без лишних слов.

К настоящему времени должно быть ясно, что просто делать throw new RuntimeException(e) это плохая идея. Это не очень вежливо к звонящему. Вы можете изобрести новое исключение во время выполнения, но основная причина (кто-то хочет, чтобы поток остановил выполнение) могла быть потеряна.

Другие примеры:

Как это случилось, я только что читал об этом сегодня утром по пути на работу в Java Concurrency In Practice от Брайана Гетца. В основном он говорит, что вы должны сделать одну из трех вещей

Что ты пытаешься сделать?

Во многих случаях имеет смысл перебрасывать исключение, заключенное в исключение RuntimeException, когда вы говорите: я не знаю, что здесь пошло не так, и не могу ничего сделать, чтобы это исправить, я просто хочу, чтобы оно вышло из текущего потока обработки и ударил любой обработчик исключений для всего приложения, который у меня есть, чтобы он мог его записать. Это не относится к InterruptedException, это просто поток, отвечающий на вызов interrupt () для него, он выдает InterruptedException, чтобы помочь своевременно отменить обработку потока.

Поэтому распространяйте InterruptedException или используйте его разумно (имея в виду место, где он должен был выполнить то, что предполагалось) и сбросьте флаг прерывания. Обратите внимание, что флаг прерывания очищается при возникновении исключения InterruptedException; разработчики библиотеки Jdk предполагают, что перехват исключения сводится к его обработке, поэтому по умолчанию флаг очищается.

Так что, безусловно, первый способ лучше, второй опубликованный пример в вопросе бесполезен, если только вы не ожидаете, что поток действительно прервется, и прерывание приведет к ошибке.

Короче говоря, если вы просто выбросите InterruptedException, вы соответствуете намерению по умолчанию, что ваш поток должен завершиться. Если вы не можете добавить InterruptedException в свой список бросков, я поместил бы его в RuntimeException.

Если вы знаете, что есть рациональная очистка, то сделайте это. Если вы знаете более глубокую причину прерывания, вы можете взять на себя более полную обработку.

Итак, в итоге ваш выбор для обработки должен следовать этому списку:

Источник

Java Exception Handling – InterruptedException

Moving along through our detailed Java Exception Handling series, today we’ll be going over the InterruptedException. An InterruptedException is thrown when a thread that is sleeping, waiting, or is occupied is interrupted.

The Technical Rundown

All Java errors implement the java.lang.Throwable interface, or are extended from another inherited class therein. The full exception hierarchy of this error is:

Full Code Sample

Below is the full code sample we’ll be using in this article. It can be copied and pasted if you’d like to play with the code yourself and see how everything works.

When Should You Use It?

Since the InterruptedException is thrown when an active or sleeping thread is interrupted, this is typically only relevant when working with multithreaded applications. That is to say, since a single-threaded application would immediately halt all execution if the main thread was interrupted, you’ll actually be catching and responding to InterruptedExceptions only when there’s at least one additional thread in which to process the interruption.

Читайте также:  при какой температуре выделяется формальдегид

With that, let’s jump right into our example code. To make things easier to track and log we’ve created the InterruptableThread class, which extends the base Thread class:

Nothing particularly fancy going on here. The constructor expects a single String name argument and passes that along to the base Thread constructor that also accepts a single String parameter for the name property. Otherwise, we implement the run method, since Thread implements the Runnable interface, which provides the abstract void run() method that will be executed when the thread starts. Within run() we output some messages to the log and call the sleep(2000) method to pause execution of this thread for two seconds. Otherwise, we catch any exceptions and that’s it.

For actually testing InterruptableThread instances we’ve also created the InterruptableThreadTest class. Since working with many default-valued parameters in Java can be annoying, rather than using multiple constructor overloads we’ve opted for a builder pattern, which we deeply dug into in a previous article. The linked article will explain a great deal more about the builder pattern if you’re curious, but the basic purpose is to simplify the process of changing many mutable (editable) properties, without the need to explicitly specify or modify any particular properties. We can alter only the properties we care about using chained method calls, while all other properties remain untouched.

The InterruptableThreadTesterBuilder class implements the builder pattern for the underlying InterruptableThreadTest class:

With the builder setup we can set the modified properties of InterruptableThreadTest in the primary constructor, then actually perform our logic and processing:

Here we create a secondary InterruptableThread and then start() it immediately. We also use the modified properties to determine if the main Thread should be slept, for how long, and if the secondary InterruptableThread should be interrupted.

In this first example we’re not interrupting the secondary thread and we’re not sleeping the main thread. Executing this test produces the following output:

Everything works as expected. The secondary thread is started, sleeps for two seconds, then completes. However, let’s try interrupting the secondary thread and see what happens:

In this case, you’ll recall that the InterruptableThreadTest constructor checks the shouldSleepMain property to determine if the main thread should also sleep, which occurs immediately after the secondary thread is started:

Thus, let’s run another test where we sleep the main thread for 2500 milliseconds (which is 500 milliseconds longer than the secondary thread is sleeping):

Executing this test no longer throws an InterruptedException and shows both threads sleeping their expected durations:

Check out all the amazing features Airbrake-Java has to offer and see for yourself why so many of the world’s best engineering teams are using Airbrake to revolutionize their exception handling practices! Try Airbrake free for 30 days.

Monitor Your App Free for 30 Days

Discover the power of Airbrake by starting a free 30-day trial of Airbrake. Quick sign-up, no credit card required. Get started.

Источник

Сказочный портал