lin
2025-07-31 065ea569db06206874bbfa18eb25ff6121aec09b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
/*
 * Copyright (C) 2017 The Android Open Source Project
 *
 * 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.
 */
 
package art;
 
import java.lang.reflect.Method;
import java.util.concurrent.atomic.*;
import java.util.function.Function;
import java.util.stream.Stream;
import java.util.Arrays;
import java.util.Objects;
 
public class Monitors {
  public native static void setupMonitorEvents(
      Class<?> method_klass,
      Method monitor_contended_enter_event,
      Method monitor_contended_entered_event,
      Method monitor_wait_event,
      Method monitor_waited_event,
      Class<?> lock_klass,
      Thread thr);
  public native static void stopMonitorEvents();
 
  public static class NamedLock {
    public final String name;
    private volatile int calledNotify;
    public NamedLock(String name) {
      this.name = name;
      calledNotify = 0;
    }
 
    public String toString() {
      return String.format("NamedLock[%s]", name);
    }
 
    public final void DoWait() throws Exception {
      final int v = calledNotify;
      while (v == calledNotify) {
        wait();
      }
    }
 
    public final void DoWait(long t) throws Exception {
      final int v = calledNotify;
      final long target = System.currentTimeMillis() + (t / 2);
      while (v == calledNotify && (t < 0 || System.currentTimeMillis() < target)) {
        wait(t);
      }
    }
 
    public final void DoNotifyAll() throws Exception {
      calledNotify++;
      notifyAll();
    }
 
    public final void DoNotify() throws Exception {
      calledNotify++;
      notify();
    }
  }
 
  public static final class MonitorUsage {
    public final Object monitor;
    public final Thread owner;
    public final int entryCount;
    public final Thread[] waiters;
    public final Thread[] notifyWaiters;
 
    public MonitorUsage(
        Object monitor,
        Thread owner,
        int entryCount,
        Thread[] waiters,
        Thread[] notifyWaiters) {
      this.monitor = monitor;
      this.entryCount = entryCount;
      this.owner = owner;
      this.waiters = waiters;
      this.notifyWaiters = notifyWaiters;
    }
 
    private static String toNameList(Thread[] ts) {
      return Arrays.toString(Arrays.stream(ts).map((Thread t) -> t.getName()).toArray());
    }
 
    public String toString() {
      return String.format(
          "MonitorUsage{ monitor: %s, owner: %s, entryCount: %d, waiters: %s, notify_waiters: %s }",
          monitor,
          (owner != null) ? owner.getName() : "<NULL>",
          entryCount,
          toNameList(waiters),
          toNameList(notifyWaiters));
    }
  }
 
  public static native MonitorUsage getObjectMonitorUsage(Object monitor);
  public static native Object getCurrentContendedMonitor(Thread thr);
 
  public static class TestException extends Error {
    public TestException() { super(); }
    public TestException(String s) { super(s); }
    public TestException(String s, Throwable c) { super(s, c); }
  }
 
  public static class LockController {
    private static enum Action { HOLD, RELEASE, NOTIFY, NOTIFY_ALL, WAIT, TIMED_WAIT }
 
    public final NamedLock lock;
    public final long timeout;
    private final AtomicStampedReference<Action> action;
    private volatile Thread runner = null;
    private volatile boolean started = false;
    private volatile boolean held = false;
    private static final AtomicInteger cnt = new AtomicInteger(0);
    private volatile Throwable exe;
 
    public LockController(NamedLock lock) {
      this(lock, 10 * 1000);
    }
    public LockController(NamedLock lock, long timeout) {
      this.lock = lock;
      this.timeout = timeout;
      this.action = new AtomicStampedReference(Action.HOLD, 0);
      this.exe = null;
    }
 
    public boolean IsWorkerThread(Thread thd) {
      return Objects.equals(runner, thd);
    }
 
    public boolean IsLocked() {
      checkException();
      return held;
    }
 
    public void checkException() {
      if (exe != null) {
        throw new TestException("Exception thrown by other thread!", exe);
      }
    }
 
    private void setAction(Action a) {
      int stamp = action.getStamp();
      // Wait for it to be HOLD before updating.
      while (!action.compareAndSet(Action.HOLD, a, stamp, stamp + 1)) {
        stamp = action.getStamp();
      }
    }
 
    public synchronized void suspendWorker() throws Exception {
      checkException();
      if (runner == null) {
        throw new TestException("We don't have any runner holding  " + lock);
      }
      Suspension.suspend(runner);
    }
 
    public Object getWorkerContendedMonitor() throws Exception {
      checkException();
      if (runner == null) {
        return null;
      }
      return getCurrentContendedMonitor(runner);
    }
 
    public synchronized void DoLock() {
      if (IsLocked()) {
        throw new Error("lock is already acquired or being acquired.");
      }
      if (runner != null) {
        throw new Error("Already have thread!");
      }
      runner = new Thread(() -> {
        started = true;
        try {
          synchronized (lock) {
            held = true;
            int[] stamp_h = new int[] { -1 };
            Action cur_action = Action.HOLD;
            try {
              while (true) {
                cur_action = action.get(stamp_h);
                int stamp = stamp_h[0];
                if (cur_action == Action.RELEASE) {
                  // The other thread will deal with reseting action.
                  break;
                }
                try {
                  switch (cur_action) {
                    case HOLD:
                      Thread.yield();
                      break;
                    case NOTIFY:
                      lock.DoNotify();
                      break;
                    case NOTIFY_ALL:
                      lock.DoNotifyAll();
                      break;
                    case TIMED_WAIT:
                      lock.DoWait(timeout);
                      break;
                    case WAIT:
                      lock.DoWait();
                      break;
                    default:
                      throw new Error("Unknown action " + action);
                  }
                } finally {
                  // reset action back to hold if it isn't something else.
                  action.compareAndSet(cur_action, Action.HOLD, stamp, stamp+1);
                }
              }
            } catch (Exception e) {
              throw new TestException("Got an error while performing action " + cur_action, e);
            }
          }
        } finally {
          held = false;
          started = false;
        }
      }, "Locker thread " + cnt.getAndIncrement() + " for " + lock);
      // Make sure we can get any exceptions this throws.
      runner.setUncaughtExceptionHandler((t, e) -> { exe = e; });
      runner.start();
    }
 
    public void waitForLockToBeHeld() throws Exception {
      while (true) {
        if (IsLocked() && Objects.equals(runner, Monitors.getObjectMonitorUsage(lock).owner)) {
          return;
        }
      }
    }
 
    public synchronized void waitForNotifySleep() throws Exception {
      if (runner == null) {
        throw new Error("No thread trying to lock!");
      }
      do {
        checkException();
      } while (!started ||
          !Arrays.asList(Monitors.getObjectMonitorUsage(lock).notifyWaiters).contains(runner));
    }
 
    public synchronized void waitForContendedSleep() throws Exception {
      if (runner == null) {
        throw new Error("No thread trying to lock!");
      }
      do {
        checkException();
      } while (!started ||
          runner.getState() != Thread.State.BLOCKED ||
          !Arrays.asList(Monitors.getObjectMonitorUsage(lock).waiters).contains(runner));
    }
 
    public synchronized void DoNotify() {
      if (!IsLocked()) {
        throw new Error("Not locked");
      }
      setAction(Action.NOTIFY);
    }
 
    public synchronized void DoNotifyAll() {
      if (!IsLocked()) {
        throw new Error("Not locked");
      }
      setAction(Action.NOTIFY_ALL);
    }
 
    public synchronized void DoTimedWait() throws Exception {
      if (!IsLocked()) {
        throw new Error("Not locked");
      }
      setAction(Action.TIMED_WAIT);
    }
 
    public synchronized void DoWait() throws Exception {
      if (!IsLocked()) {
        throw new Error("Not locked");
      }
      setAction(Action.WAIT);
    }
 
    public synchronized void interruptWorker() throws Exception {
      if (!IsLocked()) {
        throw new Error("Not locked");
      }
      runner.interrupt();
    }
 
    public synchronized void waitForActionToFinish() throws Exception {
      checkException();
      while (action.getReference() != Action.HOLD) { checkException(); }
    }
 
    public synchronized void DoUnlock() throws Exception {
      Error throwing = null;
      if (!IsLocked()) {
        // We might just be racing some exception that was thrown by the worker thread. Cache the
        // exception, we will throw one from the worker before this one.
        throwing = new Error("Not locked!");
      }
      setAction(Action.RELEASE);
      Thread run = runner;
      runner = null;
      while (held) {}
      run.join();
      action.set(Action.HOLD, 0);
      // Make sure to throw any exception that occurred since it might not have unlocked due to our
      // request.
      checkException();
      DoCleanup();
      if (throwing != null) {
        throw throwing;
      }
    }
 
    public synchronized void DoCleanup() throws Exception {
      if (runner != null) {
        Thread run = runner;
        runner = null;
        while (held) {}
        run.join();
      }
      action.set(Action.HOLD, 0);
      exe = null;
    }
  }
}