Skip to content

Commit 3348f00

Browse files
committed
fix: call network thread observers on a callback thread
From M155 the network thread is also the worker thread. DTLS transport and data channel send observers ran on it, so a WebRTC call from them that needs the worker thread deadlocked. They now run in order on a shared JVM-attached thread.
1 parent 3d00e74 commit 3348f00

10 files changed

Lines changed: 359 additions & 49 deletions

File tree

‎docs/guide/data/data-channels.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -203,7 +203,7 @@ dataChannel.sendAsync(binaryChannelBuffer, new RTCDataChannelSendObserver() {
203203
});
204204
```
205205

206-
The observer is called exactly once, normally on the native network thread, and with a failure if the operation is discarded while the channel shuts down. Success means the message was queued locally, not that the peer received it. Do not block in the callbacks or call other WebRTC methods from them synchronously; dispatch further work to an executor of your own. Without an observer, `sendAsync` logs failures and reports nothing to the caller.
206+
The observer is called exactly once, with a failure if the operation is discarded while the channel shuts down. Success means the message was queued locally, not that the peer received it. Callbacks run on a native callback thread shared with other send and DTLS transport observers; they may call other WebRTC methods, but should not block, so dispatch long work to an executor of your own. Without an observer, `sendAsync` logs failures and reports nothing to the caller.
207207

208208
### Receiving Data
209209

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/*
2+
* Copyright 2026 Alex Andres
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
#ifndef JNI_WEBRTC_API_JAVA_CALLBACK_THREAD_H_
18+
#define JNI_WEBRTC_API_JAVA_CALLBACK_THREAD_H_
19+
20+
#include "absl/functional/any_invocable.h"
21+
22+
#include <jni.h>
23+
24+
namespace jni
25+
{
26+
// The thread that runs the Java observers WebRTC notifies on its network
27+
// thread.
28+
//
29+
// The network thread is also WebRTC's worker thread, and many peer
30+
// connection calls block the signaling thread on the worker thread. An
31+
// observer making such a call on the network thread would wait for itself
32+
// and deadlock every connection of its factory, and a slow one would stall
33+
// their media. So these observers are queued and called here instead, one
34+
// at a time and in the order they were posted.
35+
//
36+
// The thread starts on first use and is attached to the JVM as a daemon,
37+
// so that it never holds up the JVM's exit.
38+
class JavaCallbackThread
39+
{
40+
public:
41+
static void Post(absl::AnyInvocable<void(JNIEnv *) &&> callback);
42+
};
43+
}
44+
45+
#endif

‎webrtc-jni/src/main/cpp/include/api/RTCDtlsTransportObserver.h‎

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -24,14 +24,20 @@
2424

2525
#include <jni.h>
2626
#include <memory>
27+
#include <mutex>
2728

2829
namespace jni
2930
{
31+
// WebRTC notifies this observer on its network thread; the Java observer is
32+
// called on the JavaCallbackThread instead.
3033
class RTCDtlsTransportObserver : public webrtc::DtlsTransportObserverInterface
3134
{
3235
public:
3336
explicit RTCDtlsTransportObserver(JNIEnv * env, const JavaGlobalRef<jobject> & observer);
34-
~RTCDtlsTransportObserver() = default;
37+
38+
// Waits for a Java call in progress, so the Java observer hears
39+
// nothing more once this returns.
40+
~RTCDtlsTransportObserver();
3541

3642
// DtlsTransportObserverInterface implementation.
3743
void OnStateChange(webrtc::DtlsTransportInformation info) override;
@@ -47,10 +53,21 @@ namespace jni
4753
jmethodID onError;
4854
};
4955

50-
private:
51-
JavaGlobalRef<jobject> observer;
56+
// Shared with the queued calls, which may outlive this observer.
57+
struct Target
58+
{
59+
Target(const JavaGlobalRef<jobject> & observer,
60+
std::shared_ptr<JavaRTCDtlsTransportObserverClass> javaClass);
5261

53-
const std::shared_ptr<JavaRTCDtlsTransportObserverClass> javaClass;
62+
// Recursive, so that a Java observer may unregister itself.
63+
std::recursive_mutex mutex;
64+
bool active;
65+
const JavaGlobalRef<jobject> observer;
66+
const std::shared_ptr<JavaRTCDtlsTransportObserverClass> javaClass;
67+
};
68+
69+
private:
70+
const std::shared_ptr<Target> target;
5471
};
5572
}
5673

Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
/*
2+
* Copyright 2026 Alex Andres
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
#include "api/JavaCallbackThread.h"
18+
#include "JavaContext.h"
19+
20+
#include "rtc_base/logging.h"
21+
22+
#include <condition_variable>
23+
#include <deque>
24+
#include <mutex>
25+
#include <thread>
26+
#include <utility>
27+
28+
namespace jni
29+
{
30+
namespace
31+
{
32+
struct Queue
33+
{
34+
std::mutex mutex;
35+
std::condition_variable condition;
36+
std::deque<absl::AnyInvocable<void(JNIEnv *) &&>> callbacks;
37+
};
38+
39+
void Run(Queue * queue)
40+
{
41+
JavaVM * vm = javaContext->getVM();
42+
JNIEnv * env = nullptr;
43+
44+
JavaVMAttachArgs args;
45+
args.version = JNI_VERSION_1_6;
46+
args.name = const_cast<char *>("WebRTC-Callbacks");
47+
args.group = nullptr;
48+
49+
if (vm->AttachCurrentThreadAsDaemon(reinterpret_cast<void **>(&env), &args) != JNI_OK) {
50+
env = nullptr;
51+
52+
RTC_LOG(LS_ERROR) << "The Java callback thread cannot attach to the JVM, observers will not be called";
53+
}
54+
55+
while (true) {
56+
absl::AnyInvocable<void(JNIEnv *) &&> callback;
57+
58+
{
59+
std::unique_lock<std::mutex> lock(queue->mutex);
60+
61+
queue->condition.wait(lock, [queue] {
62+
return !queue->callbacks.empty();
63+
});
64+
65+
callback = std::move(queue->callbacks.front());
66+
queue->callbacks.pop_front();
67+
}
68+
69+
if (env != nullptr) {
70+
try {
71+
std::move(callback)(env);
72+
}
73+
catch (...) {
74+
RTC_LOG(LS_ERROR) << "A Java callback failed with a native exception";
75+
}
76+
}
77+
}
78+
}
79+
80+
Queue & GetQueue()
81+
{
82+
// Never destroyed: its thread waits on it for as long as the
83+
// process runs.
84+
static Queue * queue = [] {
85+
Queue * created = new Queue();
86+
87+
std::thread(Run, created).detach();
88+
89+
return created;
90+
}();
91+
92+
return *queue;
93+
}
94+
}
95+
96+
void JavaCallbackThread::Post(absl::AnyInvocable<void(JNIEnv *) &&> callback)
97+
{
98+
Queue & queue = GetQueue();
99+
100+
{
101+
std::lock_guard<std::mutex> lock(queue.mutex);
102+
103+
queue.callbacks.push_back(std::move(callback));
104+
}
105+
106+
queue.condition.notify_one();
107+
}
108+
}

‎webrtc-jni/src/main/cpp/src/api/RTCDataChannelSendObserver.cpp‎

Lines changed: 28 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,14 @@
11
#include "api/RTCDataChannelSendObserver.h"
2+
#include "api/JavaCallbackThread.h"
23
#include "api/WebRTCUtils.h"
34
#include "JavaString.h"
45
#include "JNI_WebRTC.h"
56

7+
#include "rtc_base/logging.h"
8+
9+
#include <optional>
10+
#include <string>
11+
612
namespace jni
713
{
814
RTCDataChannelSendObserver::RTCDataChannelSendObserver(JNIEnv * env, jobject observer) :
@@ -43,21 +49,30 @@ namespace jni
4349
if (!callback.get()) {
4450
return;
4551
}
46-
JNIEnv * env = AttachCurrentThread();
47-
if (env == nullptr) {
48-
return;
49-
}
50-
if (error == nullptr) {
51-
env->CallVoidMethod(callback.get(), javaClass->onSuccess);
52-
}
53-
else {
54-
JavaLocalRef<jstring> message(env, env->NewStringUTF(error));
55-
if (!env->ExceptionCheck()) {
56-
env->CallVoidMethod(callback.get(), javaClass->onFailure, message.get());
52+
try {
53+
std::optional<std::string> message;
54+
if (error != nullptr) {
55+
message = error;
5756
}
57+
// WebRTC completes sends on its network thread, where the Java observer must not run.
58+
JavaCallbackThread::Post([callback = std::move(callback), javaClass = javaClass,
59+
message = std::move(message)](JNIEnv * env) {
60+
if (!message) {
61+
env->CallVoidMethod(callback.get(), javaClass->onSuccess);
62+
}
63+
else {
64+
JavaLocalRef<jstring> jMessage(env, env->NewStringUTF(message->c_str()));
65+
if (!env->ExceptionCheck()) {
66+
env->CallVoidMethod(callback.get(), javaClass->onFailure, jMessage.get());
67+
}
68+
}
69+
// A Java exception must not escape into the next callback.
70+
ReportPendingException(env);
71+
});
72+
}
73+
catch (...) {
74+
RTC_LOG(LS_ERROR) << "Could not report a data channel send result";
5875
}
59-
// A Java exception must not escape into WebRTC's network task or a destructor.
60-
ReportPendingException(env);
6176
}
6277

6378
RTCDataChannelSendObserver::JavaSendObserverClass::JavaSendObserverClass(JNIEnv * env)

‎webrtc-jni/src/main/cpp/src/api/RTCDtlsTransportObserver.cpp‎

Lines changed: 44 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
*/
1616

1717
#include "api/RTCDtlsTransportObserver.h"
18+
#include "api/JavaCallbackThread.h"
1819
#include "api/WebRTCUtils.h"
1920
#include "JavaEnums.h"
2021
#include "JavaRef.h"
@@ -25,49 +26,67 @@
2526
namespace jni
2627
{
2728
RTCDtlsTransportObserver::RTCDtlsTransportObserver(JNIEnv * env, const JavaGlobalRef<jobject> & observer) :
29+
target(std::make_shared<Target>(observer, JavaClasses::get<JavaRTCDtlsTransportObserverClass>(env)))
30+
{
31+
}
32+
33+
RTCDtlsTransportObserver::Target::Target(const JavaGlobalRef<jobject> & observer,
34+
std::shared_ptr<JavaRTCDtlsTransportObserverClass> javaClass) :
35+
active(true),
2836
observer(observer),
29-
javaClass(JavaClasses::get<JavaRTCDtlsTransportObserverClass>(env))
37+
javaClass(std::move(javaClass))
3038
{
3139
}
3240

41+
RTCDtlsTransportObserver::~RTCDtlsTransportObserver()
42+
{
43+
std::lock_guard<std::recursive_mutex> lock(target->mutex);
44+
45+
target->active = false;
46+
}
47+
3348
void RTCDtlsTransportObserver::OnStateChange(webrtc::DtlsTransportInformation info)
3449
{
35-
JNIEnv * env = AttachCurrentThread();
50+
JavaCallbackThread::Post([target = target, state = info.state()](JNIEnv * env) {
51+
std::lock_guard<std::recursive_mutex> lock(target->mutex);
3652

37-
if (env == nullptr) {
38-
return;
39-
}
53+
if (!target->active) {
54+
return;
55+
}
4056

41-
try {
42-
auto state = JavaEnums::toJava(env, info.state());
57+
try {
58+
auto jState = JavaEnums::toJava(env, state);
4359

44-
env->CallVoidMethod(observer, javaClass->onStateChange, state.get());
45-
}
46-
catch (...) {
47-
ThrowCxxJavaException(env);
48-
}
60+
env->CallVoidMethod(target->observer, target->javaClass->onStateChange, jState.get());
61+
}
62+
catch (...) {
63+
ThrowCxxJavaException(env);
64+
}
4965

50-
ReportPendingException(env);
66+
ReportPendingException(env);
67+
});
5168
}
5269

5370
void RTCDtlsTransportObserver::OnError(webrtc::RTCError error)
5471
{
55-
JNIEnv * env = AttachCurrentThread();
72+
JavaCallbackThread::Post([target = target, message = RTCErrorToString(error)](JNIEnv * env) {
73+
std::lock_guard<std::recursive_mutex> lock(target->mutex);
5674

57-
if (env == nullptr) {
58-
return;
59-
}
75+
if (!target->active) {
76+
return;
77+
}
6078

61-
try {
62-
JavaLocalRef<jstring> errorMessage = JavaString::toJava(env, RTCErrorToString(error));
79+
try {
80+
JavaLocalRef<jstring> errorMessage = JavaString::toJava(env, message);
6381

64-
env->CallVoidMethod(observer, javaClass->onError, errorMessage.get());
65-
}
66-
catch (...) {
67-
ThrowCxxJavaException(env);
68-
}
82+
env->CallVoidMethod(target->observer, target->javaClass->onError, errorMessage.get());
83+
}
84+
catch (...) {
85+
ThrowCxxJavaException(env);
86+
}
6987

70-
ReportPendingException(env);
88+
ReportPendingException(env);
89+
});
7190
}
7291

7392
RTCDtlsTransportObserver::JavaRTCDtlsTransportObserverClass::JavaRTCDtlsTransportObserverClass(JNIEnv * env)

‎webrtc/src/main/java/dev/onvoid/webrtc/RTCDataChannel.java‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -249,15 +249,15 @@ public void sendAsync(RTCDataChannelBuffer buffer) {
249249
* returns, without changing its position or limit.
250250
* <p>
251251
* The observer is called once when the operation completes or is discarded
252-
* during channel shutdown. It normally runs on the native network thread;
253-
* a discarded operation can report failure on the thread that destroys it.
254-
* The callback may run before this method returns. It must not block or
255-
* call other WebRTC methods synchronously. Dispatch further work to an
256-
* application executor. No callback is guaranteed during JVM shutdown.
252+
* during channel shutdown. It runs on a native callback thread that all
253+
* send and DTLS transport observers share, in the order the results arrive,
254+
* and may run before this method returns. It may call other WebRTC methods,
255+
* but should not block, since that holds up the other observers. No
256+
* callback is guaranteed during JVM shutdown.
257257
* <p>
258258
* Invalid arguments and failures preparing the native operation are thrown
259259
* on the calling thread. If preparation fails, the observer is not called.
260-
* Exceptions thrown by the observer are printed and cleared on its native
260+
* Exceptions thrown by the observer are printed and cleared on the callback
261261
* thread; they do not propagate to the sender.
262262
*
263263
* @param buffer The buffer to be queued for transmission.

0 commit comments

Comments
 (0)