Skip to content

Commit

Permalink
Fix memory leak in HeadlessJsTaskContext
Browse files Browse the repository at this point in the history
Reviewed By: foghina, AaaChiuuu

Differential Revision: D4068078

fbshipit-source-id: a45ad83e9ecd8455558968089d80f94ec104c2ef
  • Loading branch information
ayc1 authored and Facebook Github Bot committed Oct 25, 2016
1 parent 6ddf8a8 commit 3af104f
Showing 1 changed file with 8 additions and 4 deletions.
Expand Up @@ -2,6 +2,7 @@

package com.facebook.react.jstasks;

import java.lang.ref.WeakReference;
import java.util.Set;
import java.util.WeakHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
Expand Down Expand Up @@ -41,7 +42,7 @@ public static HeadlessJsTaskContext getInstance(ReactContext context) {
return helper;
}

private final ReactContext mReactContext;
private final WeakReference<ReactContext> mReactContext;
private final Set<HeadlessJsTaskEventListener> mHeadlessJsTaskEventListeners =
new CopyOnWriteArraySet<>();
private final AtomicInteger mLastTaskId = new AtomicInteger(0);
Expand All @@ -50,7 +51,7 @@ public static HeadlessJsTaskContext getInstance(ReactContext context) {
private final SparseArray<Runnable> mTaskTimeouts = new SparseArray<>();

private HeadlessJsTaskContext(ReactContext reactContext) {
mReactContext = reactContext;
mReactContext = new WeakReference<ReactContext>(reactContext);
}

/**
Expand Down Expand Up @@ -82,14 +83,17 @@ public boolean hasActiveTasks() {
*/
public synchronized int startTask(final HeadlessJsTaskConfig taskConfig) {
UiThreadUtil.assertOnUiThread();
if (mReactContext.getLifecycleState() == LifecycleState.RESUMED &&
ReactContext reactContext = Assertions.assertNotNull(
mReactContext.get(),
"Tried to start a task on a react context that has already been destroyed");
if (reactContext.getLifecycleState() == LifecycleState.RESUMED &&
!taskConfig.isAllowedInForeground()) {
throw new IllegalStateException(
"Tried to start task " + taskConfig.getTaskKey() +
" while in foreground, but this is not allowed.");
}
final int taskId = mLastTaskId.incrementAndGet();
mReactContext.getJSModule(AppRegistry.class)
reactContext.getJSModule(AppRegistry.class)
.startHeadlessTask(taskId, taskConfig.getTaskKey(), taskConfig.getData());
if (taskConfig.getTimeout() > 0) {
scheduleTaskTimeout(taskId, taskConfig.getTimeout());
Expand Down

0 comments on commit 3af104f

Please sign in to comment.