Skip to content

Commit 9d59bf3

Browse files
j2objc-copybaracopybara-github
authored andcommitted
Fix a data race found by tsan in Thread.java, interrupted should be accessed behind a lock. This also has the nice side effect of making the wasInterrupted changes in NSObject+JavaObject atomic.
PiperOrigin-RevId: 748771858
1 parent bf47a55 commit 9d59bf3

File tree

2 files changed

+7
-5
lines changed

2 files changed

+7
-5
lines changed

jre_emul/Classes/NSObject+JavaObject.m

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -123,14 +123,14 @@ static void doWait(id obj, long long timeout) {
123123
}
124124
JavaLangThread *javaThread = JavaLangThread_currentThread();
125125
int result = OBJC_SYNC_SUCCESS;
126-
if (!javaThread->interrupted_) {
126+
if (![javaThread isInterrupted]) {
127127
assert(javaThread->blocker_ == nil);
128128
javaThread->blocker_ = obj;
129129
result = objc_sync_wait(obj, timeout);
130130
javaThread->blocker_ = nil;
131131
}
132-
jboolean wasInterrupted = javaThread->interrupted_;
133-
javaThread->interrupted_ = false;
132+
// Check if the thread was interrupted after the wait and also clears the interrupted bit.
133+
jboolean wasInterrupted = [JavaLangThread interrupted];
134134
if (wasInterrupted) {
135135
@throw AUTORELEASE([[JavaLangInterruptedException alloc] init]);
136136
}

jre_emul/Classes/java/lang/Thread.java

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ public class Thread implements Runnable {
6565
private int priority = NORM_PRIORITY;
6666
private volatile UncaughtExceptionHandler uncaughtExceptionHandler;
6767
private boolean isDaemon;
68-
boolean interrupted;
68+
private boolean interrupted;
6969
private ClassLoader contextClassLoader;
7070
ThreadLocal.ThreadLocalMap threadLocals = null;
7171
ThreadLocal.ThreadLocalMap inheritableThreadLocals = null;
@@ -688,7 +688,9 @@ public static native boolean interrupted() /*-[
688688
* @see Thread#interrupted
689689
*/
690690
public boolean isInterrupted() {
691-
return interrupted;
691+
synchronized (nativeThread) {
692+
return interrupted;
693+
}
692694
}
693695

694696
/**

0 commit comments

Comments
 (0)