| 1 |
/* |
| 2 |
* Copyright (c) 2016-present, RxJava Contributors. |
| 3 |
* |
| 4 |
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in |
| 5 |
* compliance with the License. You may obtain a copy of the License at |
| 6 |
* |
| 7 |
* http://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
* |
| 9 |
* Unless required by applicable law or agreed to in writing, software distributed under the License is |
| 10 |
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See |
| 11 |
* the License for the specific language governing permissions and limitations under the License. |
| 12 |
*/ |
| 13 |
|
| 14 |
package io.reactivex.rxjava3.internal.util; |
| 15 |
|
| 16 |
import java.util.concurrent.CountDownLatch; |
| 17 |
|
| 18 |
import io.reactivex.rxjava3.disposables.Disposable; |
| 19 |
import io.reactivex.rxjava3.internal.schedulers.NonBlockingThread; |
| 20 |
import io.reactivex.rxjava3.plugins.RxJavaPlugins; |
| 21 |
|
| 22 |
/** |
| 23 |
* Utility methods for helping common blocking operations. |
| 24 |
*/ |
| 25 |
public final class BlockingHelper { |
| 26 |
/** Utility class. */ |
| 27 |
private BlockingHelper() { |
| 28 |
throw new IllegalStateException("No instances!"); |
| 29 |
} |
| 30 |
|
| 31 |
public static void awaitForComplete(CountDownLatch latch, Disposable subscription) { |
| 32 |
if (latch.getCount() == 0) { |
| 33 |
// Synchronous observable completes before awaiting for it. |
| 34 |
// Skip await so InterruptedException will never be thrown. |
| 35 |
return; |
| 36 |
} |
| 37 |
// block until the subscription completes and then return |
| 38 |
try { |
| 39 |
verifyNonBlocking(); |
| 40 |
latch.await(); |
| 41 |
} catch (InterruptedException e) { |
| 42 |
subscription.dispose(); |
| 43 |
// set the interrupted flag again so callers can still get it |
| 44 |
// for more information see https://github.com/ReactiveX/RxJava/pull/147#issuecomment-13624780 |
| 45 |
Thread.currentThread().interrupt(); |
| 46 |
// using Runtime so it is not checked |
| 47 |
throw new IllegalStateException("Interrupted while waiting for subscription to complete.", e); |
| 48 |
} |
| 49 |
} |
| 50 |
|
| 51 |
/** |
| 52 |
* Checks if the {@code failOnNonBlockingScheduler} plugin setting is enabled and the current |
| 53 |
* thread is a Scheduler sensitive to blocking operators. |
| 54 |
* @throws IllegalStateException if the {@code failOnNonBlockingScheduler} and the current thread is sensitive to blocking |
| 55 |
*/ |
| 56 |
public static void verifyNonBlocking() { |
| 57 |
if (RxJavaPlugins.isFailOnNonBlockingScheduler() |
| 58 |
&& (Thread.currentThread() instanceof NonBlockingThread |
| 59 |
|| RxJavaPlugins.onBeforeBlocking())) { |
| 60 |
throw new IllegalStateException("Attempt to block on a Scheduler " + Thread.currentThread().getName() + " that doesn't support blocking operators as they may lead to deadlock"); |
| 61 |
} |
| 62 |
} |
| 63 |
} |