Skip to content

Commit e9bb3ee

Browse files
authored
fix: dispose native objects once and keep them while a call still uses them (#520)
Dispose and close take the handle atomically, so repeated or concurrent calls do nothing, and release the native object only once no native method on another thread still uses it. Methods of a disposed object throw an IllegalStateException naming its class.
1 parent ef6174a commit e9bb3ee

41 files changed

Lines changed: 1297 additions & 419 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎docs/guide/get-started.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -462,6 +462,8 @@ peerConnection.close();
462462
factory.dispose();
463463
```
464464

465+
`dispose()` and `close()` may be called from any thread and more than once: only the first call frees anything, later ones do nothing. Once an object is disposed, its methods throw an `IllegalStateException` (a closed connection still reports its state). A method that another thread is running at that moment keeps the native object until it returns, and what the dispose frees is freed then.
466+
465467
## Next Steps
466468

467469
Now that you have a basic understanding of webrtc-java, you can explore more advanced features:

‎webrtc-jni/src/main/cpp/dependencies/jni-voithos/include/JavaUtils.h‎

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -17,27 +17,28 @@
1717
#include <vector>
1818

1919

20+
// Return from a native method whose native object is gone, with an
21+
// IllegalStateException thrown unless an exception is pending already. The
22+
// handle is a raw pointer or a lease, which names its object's class.
2023
#define CHECK_HANDLE(handle) \
2124
do { \
22-
if (handle == NULL) { \
23-
JNIEnv * env = AttachCurrentThread(); \
24-
env->Throw(jni::JavaNullPointerException(env, "Object handle is null")); \
25+
if (!(handle)) { \
26+
ThrowNullHandle(handle); \
2527
return; \
2628
} \
2729
} while(0)
2830

2931
#define CHECK_HANDLEV(handle, retValue) \
3032
do { \
31-
if (handle == NULL) { \
32-
JNIEnv * env = AttachCurrentThread(); \
33-
env->Throw(jni::JavaNullPointerException(env, "Object handle is null")); \
33+
if (!(handle)) { \
34+
ThrowNullHandle(handle); \
3435
return retValue; \
3536
} \
3637
} while(0)
3738

3839
#define CHECK_HANDLE_DEFAULT(handle, retValue) \
3940
do { \
40-
if (handle == NULL) { \
41+
if (!(handle)) { \
4142
return retValue; \
4243
} \
4344
} while(0)
@@ -53,6 +54,16 @@ void ThrowCxxJavaException(JNIEnv * env);
5354
void SetJavaVM(JavaVM * vm);
5455
JavaVM * GetJavaVM();
5556
JNIEnv * AttachCurrentThread();
57+
58+
// Throws the IllegalStateException of a missing native object for
59+
// CHECK_HANDLE on a raw pointer. A lease has an overload of its own, found by
60+
// argument-dependent lookup, that names the object's class.
61+
template<typename T>
62+
void ThrowNullHandle(T *)
63+
{
64+
ThrowJavaException(AttachCurrentThread(), "java/lang/IllegalStateException", "Native object is disposed");
65+
}
66+
5667
bool ExceptionCheck(JNIEnv * env);
5768
jclass FindClass(JNIEnv * env, const char * name);
5869
jmethodID GetMethod(JNIEnv * env, jclass cls, const char * name, const char * sig);
Lines changed: 144 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,144 @@
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_NATIVE_HANDLE_H_
18+
#define JNI_WEBRTC_NATIVE_HANDLE_H_
19+
20+
#include <jni.h>
21+
22+
#include <functional>
23+
24+
namespace jni
25+
{
26+
// The life of the native object behind NativeObject.nativeHandle, shared
27+
// by every thread that calls into it.
28+
//
29+
// A native method uses the object through a NativeLease, which marks the
30+
// handle in use for as long as the call runs. dispose() and close() take
31+
// the handle with Take(), which unbinds it in one step: of several threads
32+
// disposing the same object, one gets the handle, the others nothing, and
33+
// no call starts using it afterwards. The object's owning reference is then
34+
// given up with Release(): at once if no call uses the handle, otherwise by
35+
// the last of those calls when it returns. Nothing waits for another
36+
// thread, so a dispose from within a callback cannot deadlock with a call
37+
// that waits for that callback's thread.
38+
namespace NativeHandle
39+
{
40+
// Returns the bound handle of a NativeObject and marks it in use, or 0
41+
// when the object is null or no longer bound. A non-zero handle must be
42+
// given back with Unuse().
43+
jlong Use(JNIEnv * env, jobject object);
44+
45+
// Ends a use begun with Use(), and runs the releases that waited for it
46+
// if it was the last.
47+
void Unuse(JNIEnv * env, jlong handle) noexcept;
48+
49+
// Unbinds the handle of a NativeObject and returns it. Returns 0 when
50+
// the object is null or another thread has taken the handle before.
51+
jlong Take(JNIEnv * env, jobject object);
52+
53+
// Gives up what a taken handle owns. The release runs right away, with
54+
// deferred false, unless a call still uses the handle; then it runs on
55+
// the thread of the last such call, when that call returns, with
56+
// deferred true. A deferred release must not use the JNIEnv or the Java
57+
// object of the call that took the handle.
58+
void Release(JNIEnv * env, jlong handle, std::function<void(bool deferred)> release);
59+
60+
// Throws the IllegalStateException of a disposed object, unless an
61+
// exception is pending already.
62+
void ThrowDisposed(JNIEnv * env, jobject object) noexcept;
63+
64+
// Reports that a release left references to the native object behind:
65+
// as a java.lang.Error when it ran right away, as a warning in the log
66+
// when it was deferred, since the call it ran in is not the one to fail.
67+
void ReportNotDeleted(bool deferred) noexcept;
68+
}
69+
70+
// The native object of a NativeObject, kept from being released while the
71+
// lease lives. Converts to T *, which is null when the object has been
72+
// disposed: check it with CHECK_HANDLE, which then throws the object's
73+
// IllegalStateException.
74+
template <typename T>
75+
class NativeLease
76+
{
77+
public:
78+
NativeLease(JNIEnv * env, jobject object) :
79+
env(env),
80+
object(object),
81+
handle(NativeHandle::Use(env, object))
82+
{
83+
}
84+
85+
~NativeLease()
86+
{
87+
if (handle != 0) {
88+
NativeHandle::Unuse(env, handle);
89+
}
90+
}
91+
92+
NativeLease(const NativeLease &) = delete;
93+
NativeLease & operator=(const NativeLease &) = delete;
94+
95+
T * get() const
96+
{
97+
return reinterpret_cast<T *>(handle);
98+
}
99+
100+
operator T * () const
101+
{
102+
return get();
103+
}
104+
105+
T * operator->() const
106+
{
107+
return get();
108+
}
109+
110+
void throwDisposed() const
111+
{
112+
NativeHandle::ThrowDisposed(env, object);
113+
}
114+
115+
private:
116+
JNIEnv * env;
117+
jobject object;
118+
jlong handle;
119+
};
120+
121+
// Found by argument-dependent lookup from CHECK_HANDLE.
122+
template <typename T>
123+
void ThrowNullHandle(const NativeLease<T> & lease)
124+
{
125+
lease.throwDisposed();
126+
}
127+
128+
// NativeHandle::Take() for the native type the handle stands for. Null
129+
// when the object has been disposed already.
130+
template <typename T>
131+
T * TakeHandle(JNIEnv * env, jobject object)
132+
{
133+
return reinterpret_cast<T *>(NativeHandle::Take(env, object));
134+
}
135+
136+
// NativeHandle::Release() for a handle taken with TakeHandle().
137+
template <typename T>
138+
void ReleaseHandle(JNIEnv * env, T * object, std::function<void(bool deferred)> release)
139+
{
140+
NativeHandle::Release(env, reinterpret_cast<jlong>(object), std::move(release));
141+
}
142+
}
143+
144+
#endif

‎webrtc-jni/src/main/cpp/src/JNI_AudioConverter.cpp‎

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

1717
#include "JNI_AudioConverter.h"
18+
#include "NativeHandle.h"
1819
#include "api/audio/audio_processing.h"
1920
#include "media/audio/AudioConverter.h"
2021
#include "JavaUtils.h"
@@ -25,7 +26,7 @@
2526
JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_audio_AudioConverter_convertInternal
2627
(JNIEnv * env, jobject caller, jbyteArray src, jint nSrcSamples, jbyteArray dst, jint nDstSamples)
2728
{
28-
jni::AudioConverter * converter = GetHandle<jni::AudioConverter>(env, caller);
29+
jni::NativeLease<jni::AudioConverter> converter(env, caller);
2930
CHECK_HANDLE(converter);
3031

3132
if (src == nullptr || dst == nullptr) {
@@ -73,12 +74,15 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_audio_AudioConverter_convert
7374
JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_audio_AudioConverter_dispose
7475
(JNIEnv * env, jobject caller)
7576
{
76-
jni::AudioConverter * converter = GetHandle<jni::AudioConverter>(env, caller);
77-
CHECK_HANDLE(converter);
77+
jni::AudioConverter * converter = jni::TakeHandle<jni::AudioConverter>(env, caller);
7878

79-
SetHandle<std::nullptr_t>(env, caller, nullptr);
79+
if (converter == nullptr) {
80+
return;
81+
}
8082

81-
delete converter;
83+
jni::ReleaseHandle(env, converter, [converter](bool) {
84+
delete converter;
85+
});
8286
}
8387

8488
JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_audio_AudioConverter_initialize

0 commit comments

Comments
 (0)