Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions docs/guide/get-started.md
Original file line number Diff line number Diff line change
Expand Up @@ -481,6 +481,22 @@ factory.dispose();

`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.

#### Finding Objects That Were Never Disposed

An object that becomes unreachable without being disposed or closed leaks its native object. To find such objects, start the JVM with `-Dwebrtc.java.leak.detection=true`: each one is then reported, with its class, once the garbage collector finds it unreachable. Add `-Dwebrtc.java.leak.trace=true` to have the report tell where the object was created, at the cost of a stack trace per object.

```shell
java -Dwebrtc.java.leak.detection=true -Dwebrtc.java.leak.trace=true -jar app.jar
```

The reports are warnings through `Logging`, which writes nothing unless the application asks for it:

```java
Logging.logToDebug(Logging.Severity.WARNING);
```

Only objects that own a native object and have a `dispose()` or `close()` method are watched: not views such as the track of `RTCRtpSender.getTrack()`, which own nothing, and not reference-counted objects such as video frame buffers. The detector only reports; it never frees anything itself, since a native object may still be in use on a WebRTC thread. While it is off, which is the default, nothing is watched.

## Next Steps

Now that you have a basic understanding of webrtc-java, you can explore more advanced features:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,14 @@ T * GetHandle(JNIEnv * env, jobject obj)
return GetHandle<T>(env, obj, "nativeHandle");
}

// Told about every Java object whose "nativeHandle" field SetHandle() sets:
// bound is whether it is set to a native object or to none. Null, and then
// not called, unless something listens.
using NativeHandleHook = void (*)(JNIEnv * env, jobject obj, bool bound);

void SetNativeHandleHook(NativeHandleHook hook);
NativeHandleHook GetNativeHandleHook();

template<typename T>
void SetHandle(JNIEnv * env, jobject obj, const std::string & handleName, T * t,
const char * declaringClass = nullptr)
Expand All @@ -133,6 +141,12 @@ void SetHandle(JNIEnv * env, jobject obj, const std::string & handleName, T * t,
jlong handle = reinterpret_cast<jlong>(t);

env->SetLongField(obj, field, handle);

if (NativeHandleHook hook = GetNativeHandleHook()) {
if (handleName == "nativeHandle") {
hook(env, obj, handle != 0);
}
}
}

template<typename T>
Expand Down
17 changes: 17 additions & 0 deletions webrtc-jni/src/main/cpp/dependencies/jni-voithos/src/JavaUtils.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@
#include "JavaThreadEnv.h"
#include "JavaWrappedException.h"

#include <atomic>

#include <atomic>
#include <exception>
#include <ios>
Expand Down Expand Up @@ -154,6 +156,21 @@ jmethodID GetStaticMethod(JNIEnv * env, jclass cls, const char * name, const cha
return method;
}

namespace
{
std::atomic<NativeHandleHook> nativeHandleHook { nullptr };
}

void SetNativeHandleHook(NativeHandleHook hook)
{
nativeHandleHook.store(hook, std::memory_order_release);
}

NativeHandleHook GetNativeHandleHook()
{
return nativeHandleHook.load(std::memory_order_acquire);
}

jfieldID GetHandleField(JNIEnv * env, jobject obj, const std::string & fieldName,
const char * declaringClass)
{
Expand Down
21 changes: 21 additions & 0 deletions webrtc-jni/src/main/cpp/include/JNI_LeakDetector.h

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

35 changes: 35 additions & 0 deletions webrtc-jni/src/main/cpp/include/LeakDetection.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/*
* Copyright 2026 Alex Andres
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

#ifndef JNI_WEBRTC_LEAK_DETECTION_H_
#define JNI_WEBRTC_LEAK_DETECTION_H_

#include <jni.h>

namespace jni
{
// The native side of dev.onvoid.webrtc.internal.LeakDetector. While it is
// off, which is the default, none of this calls into Java.
namespace LeakDetection
{
// Tells the leak detector that the NativeObject no longer owns a native
// object: it has been disposed or closed, or it never owned one, such
// as a view of a track owned elsewhere. Keeps a pending exception.
void Released(JNIEnv * env, jobject object) noexcept;
}
}

#endif
121 changes: 121 additions & 0 deletions webrtc-jni/src/main/cpp/src/JNI_LeakDetector.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
/*
* Copyright 2026 Alex Andres
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

#include "JNI_LeakDetector.h"
#include "JNI_WebRTC.h"
#include "LeakDetection.h"
#include "JavaUtils.h"

#include <atomic>

namespace
{
// Set before enabled, which publishes them.
jclass nativeObjectClass = nullptr;
jmethodID boundMethod = nullptr;
jmethodID releasedMethod = nullptr;

std::atomic<bool> enabled { false };

void Notify(JNIEnv * env, jobject object, jmethodID method) noexcept
{
if (object == nullptr) {
return;
}

// The caller's exception, if any, stays: it is not this one's to report.
jthrowable pending = env->ExceptionOccurred();

if (pending != nullptr) {
env->ExceptionClear();
}

// Some objects with a field of the same name are no NativeObject.
if (env->IsInstanceOf(object, nativeObjectClass)) {
env->CallVoidMethod(object, method);

// Detection must not break what it watches.
if (env->ExceptionCheck()) {
env->ExceptionClear();
}
}

if (pending != nullptr) {
env->Throw(pending);
env->DeleteLocalRef(pending);
}
}

void OnNativeHandleSet(JNIEnv * env, jobject object, bool bound)
{
Notify(env, object, bound ? boundMethod : releasedMethod);
}
}

namespace jni
{
namespace LeakDetection
{
void Released(JNIEnv * env, jobject object) noexcept
{
if (enabled.load(std::memory_order_acquire)) {
Notify(env, object, releasedMethod);
}
}
}
}

JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_internal_LeakDetector_enableNative
(JNIEnv * env, jclass)
{
if (enabled.load()) {
return;
}

jclass cls = env->FindClass(PKG_INTERNAL "NativeObject");

if (cls == nullptr) {
return;
}

jmethodID bound = env->GetMethodID(cls, "nativeHandleBound", "()V");

if (bound == nullptr) {
env->DeleteLocalRef(cls);
return;
}

jmethodID released = env->GetMethodID(cls, "nativeHandleReleased", "()V");

if (released == nullptr) {
env->DeleteLocalRef(cls);
return;
}

nativeObjectClass = static_cast<jclass>(env->NewGlobalRef(cls));
env->DeleteLocalRef(cls);

if (nativeObjectClass == nullptr) {
return;
}

boundMethod = bound;
releasedMethod = released;

enabled.store(true, std::memory_order_release);

SetNativeHandleHook(&OnNativeHandleSet);
}
15 changes: 10 additions & 5 deletions webrtc-jni/src/main/cpp/src/NativeHandle.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
#include "JavaRef.h"
#include "JavaUtils.h"
#include "JNI_WebRTC.h"
#include "LeakDetection.h"

#include "rtc_base/logging.h"

Expand Down Expand Up @@ -216,14 +217,18 @@ namespace jni
return 0;
}

Stripe & stripe = StripeOf(handle);
std::lock_guard<std::mutex> lock(stripe.mutex);
{
Stripe & stripe = StripeOf(handle);
std::lock_guard<std::mutex> lock(stripe.mutex);

if (env->GetLongField(object, field) != handle) {
return 0;
if (env->GetLongField(object, field) != handle) {
return 0;
}

env->SetLongField(object, field, 0);
}

env->SetLongField(object, field, 0);
LeakDetection::Released(env, object);

return handle;
}
Expand Down
4 changes: 4 additions & 0 deletions webrtc-jni/src/main/cpp/src/media/MediaStreamTrackView.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
#include "JavaClasses.h"
#include "JavaUtils.h"
#include "JNI_WebRTC.h"
#include "LeakDetection.h"

#include <utility>

Expand All @@ -41,6 +42,9 @@ namespace jni

env->SetBooleanField(javaTrack, javaClass->view, JNI_TRUE);

// Owns nothing, so there is nothing to forget to dispose.
LeakDetection::Released(env, javaTrack);

return std::move(javaTrack);
}

Expand Down
Loading
Loading