Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/mobile
Path: blob/master/src/hotspot/share/runtime/handshake.cpp
40951 views
1
/*
2
* Copyright (c) 2017, 2021, Oracle and/or its affiliates. All rights reserved.
3
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4
*
5
* This code is free software; you can redistribute it and/or modify it
6
* under the terms of the GNU General Public License version 2 only, as
7
* published by the Free Software Foundation.
8
*
9
* This code is distributed in the hope that it will be useful, but WITHOUT
10
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12
* version 2 for more details (a copy is included in the LICENSE file that
13
* accompanied this code).
14
*
15
* You should have received a copy of the GNU General Public License version
16
* 2 along with this work; if not, write to the Free Software Foundation,
17
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18
*
19
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20
* or visit www.oracle.com if you need additional information or have any
21
* questions.
22
*
23
*/
24
25
#include "precompiled.hpp"
26
#include "jvm_io.h"
27
#include "logging/log.hpp"
28
#include "logging/logStream.hpp"
29
#include "memory/resourceArea.hpp"
30
#include "runtime/atomic.hpp"
31
#include "runtime/handshake.hpp"
32
#include "runtime/interfaceSupport.inline.hpp"
33
#include "runtime/os.hpp"
34
#include "runtime/osThread.hpp"
35
#include "runtime/stackWatermarkSet.hpp"
36
#include "runtime/task.hpp"
37
#include "runtime/thread.hpp"
38
#include "runtime/threadSMR.hpp"
39
#include "runtime/vmThread.hpp"
40
#include "utilities/formatBuffer.hpp"
41
#include "utilities/filterQueue.inline.hpp"
42
#include "utilities/globalDefinitions.hpp"
43
#include "utilities/preserveException.hpp"
44
45
class HandshakeOperation : public CHeapObj<mtThread> {
46
friend class HandshakeState;
47
protected:
48
HandshakeClosure* _handshake_cl;
49
// Keeps track of emitted and completed handshake operations.
50
// Once it reaches zero all handshake operations have been performed.
51
int32_t _pending_threads;
52
JavaThread* _target;
53
Thread* _requester;
54
55
// Must use AsyncHandshakeOperation when using AsyncHandshakeClosure.
56
HandshakeOperation(AsyncHandshakeClosure* cl, JavaThread* target, Thread* requester) :
57
_handshake_cl(cl),
58
_pending_threads(1),
59
_target(target),
60
_requester(requester) {}
61
62
public:
63
HandshakeOperation(HandshakeClosure* cl, JavaThread* target, Thread* requester) :
64
_handshake_cl(cl),
65
_pending_threads(1),
66
_target(target),
67
_requester(requester) {}
68
virtual ~HandshakeOperation() {}
69
void prepare(JavaThread* current_target, Thread* executing_thread);
70
void do_handshake(JavaThread* thread);
71
bool is_completed() {
72
int32_t val = Atomic::load(&_pending_threads);
73
assert(val >= 0, "_pending_threads=%d cannot be negative", val);
74
return val == 0;
75
}
76
void add_target_count(int count) { Atomic::add(&_pending_threads, count); }
77
int32_t pending_threads() { return Atomic::load(&_pending_threads); }
78
const char* name() { return _handshake_cl->name(); }
79
bool is_async() { return _handshake_cl->is_async(); }
80
};
81
82
class AsyncHandshakeOperation : public HandshakeOperation {
83
private:
84
jlong _start_time_ns;
85
public:
86
AsyncHandshakeOperation(AsyncHandshakeClosure* cl, JavaThread* target, jlong start_ns)
87
: HandshakeOperation(cl, target, NULL), _start_time_ns(start_ns) {}
88
virtual ~AsyncHandshakeOperation() { delete _handshake_cl; }
89
jlong start_time() const { return _start_time_ns; }
90
};
91
92
// Performing handshakes requires a custom yielding strategy because without it
93
// there is a clear performance regression vs plain spinning. We keep track of
94
// when we last saw progress by looking at why each targeted thread has not yet
95
// completed its handshake. After spinning for a while with no progress we will
96
// yield, but as long as there is progress, we keep spinning. Thus we avoid
97
// yielding when there is potential work to be done or the handshake is close
98
// to being finished.
99
class HandshakeSpinYield : public StackObj {
100
private:
101
jlong _start_time_ns;
102
jlong _last_spin_start_ns;
103
jlong _spin_time_ns;
104
105
int _result_count[2][HandshakeState::_number_states];
106
int _prev_result_pos;
107
108
int current_result_pos() { return (_prev_result_pos + 1) & 0x1; }
109
110
void wait_raw(jlong now) {
111
// We start with fine-grained nanosleeping until a millisecond has
112
// passed, at which point we resort to plain naked_short_sleep.
113
if (now - _start_time_ns < NANOSECS_PER_MILLISEC) {
114
os::naked_short_nanosleep(10 * (NANOUNITS / MICROUNITS));
115
} else {
116
os::naked_short_sleep(1);
117
}
118
}
119
120
void wait_blocked(JavaThread* self, jlong now) {
121
ThreadBlockInVM tbivm(self);
122
wait_raw(now);
123
}
124
125
bool state_changed() {
126
for (int i = 0; i < HandshakeState::_number_states; i++) {
127
if (_result_count[0][i] != _result_count[1][i]) {
128
return true;
129
}
130
}
131
return false;
132
}
133
134
void reset_state() {
135
_prev_result_pos++;
136
for (int i = 0; i < HandshakeState::_number_states; i++) {
137
_result_count[current_result_pos()][i] = 0;
138
}
139
}
140
141
public:
142
HandshakeSpinYield(jlong start_time) :
143
_start_time_ns(start_time), _last_spin_start_ns(start_time),
144
_spin_time_ns(0), _result_count(), _prev_result_pos(0) {
145
146
const jlong max_spin_time_ns = 100 /* us */ * (NANOUNITS / MICROUNITS);
147
int free_cpus = os::active_processor_count() - 1;
148
_spin_time_ns = (5 /* us */ * (NANOUNITS / MICROUNITS)) * free_cpus; // zero on UP
149
_spin_time_ns = _spin_time_ns > max_spin_time_ns ? max_spin_time_ns : _spin_time_ns;
150
}
151
152
void add_result(HandshakeState::ProcessResult pr) {
153
_result_count[current_result_pos()][pr]++;
154
}
155
156
void process() {
157
jlong now = os::javaTimeNanos();
158
if (state_changed()) {
159
reset_state();
160
// We spin for x amount of time since last state change.
161
_last_spin_start_ns = now;
162
return;
163
}
164
jlong wait_target = _last_spin_start_ns + _spin_time_ns;
165
if (wait_target < now) {
166
// On UP this is always true.
167
Thread* self = Thread::current();
168
if (self->is_Java_thread()) {
169
wait_blocked(self->as_Java_thread(), now);
170
} else {
171
wait_raw(now);
172
}
173
_last_spin_start_ns = os::javaTimeNanos();
174
}
175
reset_state();
176
}
177
};
178
179
static void handle_timeout(HandshakeOperation* op, JavaThread* target) {
180
JavaThreadIteratorWithHandle jtiwh;
181
182
log_error(handshake)("Handshake timeout: %s(" INTPTR_FORMAT "), pending threads: " INT32_FORMAT,
183
op->name(), p2i(op), op->pending_threads());
184
185
if (target == NULL) {
186
for ( ; JavaThread* thr = jtiwh.next(); ) {
187
if (thr->handshake_state()->operation_pending(op)) {
188
log_error(handshake)("JavaThread " INTPTR_FORMAT " has not cleared handshake op: " INTPTR_FORMAT, p2i(thr), p2i(op));
189
// Remember the last one found for more diagnostics below.
190
target = thr;
191
}
192
}
193
} else {
194
log_error(handshake)("JavaThread " INTPTR_FORMAT " has not cleared handshake op: " INTPTR_FORMAT, p2i(target), p2i(op));
195
}
196
197
if (target != NULL) {
198
if (os::signal_thread(target, SIGILL, "cannot be handshaked")) {
199
// Give target a chance to report the error and terminate the VM.
200
os::naked_sleep(3000);
201
}
202
} else {
203
log_error(handshake)("No thread with an unfinished handshake op(" INTPTR_FORMAT ") found.", p2i(op));
204
}
205
fatal("Handshake timeout");
206
}
207
208
static void check_handshake_timeout(jlong start_time, HandshakeOperation* op, JavaThread* target = NULL) {
209
// Check if handshake operation has timed out
210
jlong timeout_ns = millis_to_nanos(HandshakeTimeout);
211
if (timeout_ns > 0) {
212
if (os::javaTimeNanos() >= (start_time + timeout_ns)) {
213
handle_timeout(op, target);
214
}
215
}
216
}
217
218
static void log_handshake_info(jlong start_time_ns, const char* name, int targets, int emitted_handshakes_executed, const char* extra = NULL) {
219
if (log_is_enabled(Info, handshake)) {
220
jlong completion_time = os::javaTimeNanos() - start_time_ns;
221
log_info(handshake)("Handshake \"%s\", Targeted threads: %d, Executed by requesting thread: %d, Total completion time: " JLONG_FORMAT " ns%s%s",
222
name, targets,
223
emitted_handshakes_executed,
224
completion_time,
225
extra != NULL ? ", " : "",
226
extra != NULL ? extra : "");
227
}
228
}
229
230
class VM_HandshakeAllThreads: public VM_Operation {
231
HandshakeOperation* const _op;
232
public:
233
VM_HandshakeAllThreads(HandshakeOperation* op) : _op(op) {}
234
235
bool evaluate_at_safepoint() const { return false; }
236
237
void doit() {
238
jlong start_time_ns = os::javaTimeNanos();
239
240
JavaThreadIteratorWithHandle jtiwh;
241
int number_of_threads_issued = 0;
242
for (JavaThread* thr = jtiwh.next(); thr != NULL; thr = jtiwh.next()) {
243
thr->handshake_state()->add_operation(_op);
244
number_of_threads_issued++;
245
}
246
247
if (number_of_threads_issued < 1) {
248
log_handshake_info(start_time_ns, _op->name(), 0, 0, "no threads alive");
249
return;
250
}
251
// _op was created with a count == 1 so don't double count.
252
_op->add_target_count(number_of_threads_issued - 1);
253
254
log_trace(handshake)("Threads signaled, begin processing blocked threads by VMThread");
255
HandshakeSpinYield hsy(start_time_ns);
256
// Keeps count on how many of own emitted handshakes
257
// this thread execute.
258
int emitted_handshakes_executed = 0;
259
do {
260
// Check if handshake operation has timed out
261
check_handshake_timeout(start_time_ns, _op);
262
263
// Have VM thread perform the handshake operation for blocked threads.
264
// Observing a blocked state may of course be transient but the processing is guarded
265
// by mutexes and we optimistically begin by working on the blocked threads
266
jtiwh.rewind();
267
for (JavaThread* thr = jtiwh.next(); thr != NULL; thr = jtiwh.next()) {
268
// A new thread on the ThreadsList will not have an operation,
269
// hence it is skipped in handshake_try_process.
270
HandshakeState::ProcessResult pr = thr->handshake_state()->try_process(_op);
271
hsy.add_result(pr);
272
if (pr == HandshakeState::_succeeded) {
273
emitted_handshakes_executed++;
274
}
275
}
276
hsy.process();
277
} while (!_op->is_completed());
278
279
// This pairs up with the release store in do_handshake(). It prevents future
280
// loads from floating above the load of _pending_threads in is_completed()
281
// and thus prevents reading stale data modified in the handshake closure
282
// by the Handshakee.
283
OrderAccess::acquire();
284
285
log_handshake_info(start_time_ns, _op->name(), number_of_threads_issued, emitted_handshakes_executed);
286
}
287
288
VMOp_Type type() const { return VMOp_HandshakeAllThreads; }
289
};
290
291
void HandshakeOperation::prepare(JavaThread* current_target, Thread* executing_thread) {
292
if (current_target->is_terminated()) {
293
// Will never execute any handshakes on this thread.
294
return;
295
}
296
if (current_target != executing_thread) {
297
// Only when the target is not executing the handshake itself.
298
StackWatermarkSet::start_processing(current_target, StackWatermarkKind::gc);
299
}
300
if (_requester != NULL && _requester != executing_thread && _requester->is_Java_thread()) {
301
// The handshake closure may contain oop Handles from the _requester.
302
// We must make sure we can use them.
303
StackWatermarkSet::start_processing(_requester->as_Java_thread(), StackWatermarkKind::gc);
304
}
305
}
306
307
void HandshakeOperation::do_handshake(JavaThread* thread) {
308
jlong start_time_ns = 0;
309
if (log_is_enabled(Debug, handshake, task)) {
310
start_time_ns = os::javaTimeNanos();
311
}
312
313
// Only actually execute the operation for non terminated threads.
314
if (!thread->is_terminated()) {
315
NoSafepointVerifier nsv;
316
_handshake_cl->do_thread(thread);
317
}
318
319
if (start_time_ns != 0) {
320
jlong completion_time = os::javaTimeNanos() - start_time_ns;
321
log_debug(handshake, task)("Operation: %s for thread " PTR_FORMAT ", is_vm_thread: %s, completed in " JLONG_FORMAT " ns",
322
name(), p2i(thread), BOOL_TO_STR(Thread::current()->is_VM_thread()), completion_time);
323
}
324
325
// Inform VMThread/Handshaker that we have completed the operation.
326
// When this is executed by the Handshakee we need a release store
327
// here to make sure memory operations executed in the handshake
328
// closure are visible to the VMThread/Handshaker after it reads
329
// that the operation has completed.
330
Atomic::dec(&_pending_threads, memory_order_release);
331
332
// It is no longer safe to refer to 'this' as the VMThread/Handshaker may have destroyed this operation
333
}
334
335
void Handshake::execute(HandshakeClosure* hs_cl) {
336
HandshakeOperation cto(hs_cl, NULL, Thread::current());
337
VM_HandshakeAllThreads handshake(&cto);
338
VMThread::execute(&handshake);
339
}
340
341
void Handshake::execute(HandshakeClosure* hs_cl, JavaThread* target) {
342
JavaThread* self = JavaThread::current();
343
HandshakeOperation op(hs_cl, target, Thread::current());
344
345
jlong start_time_ns = os::javaTimeNanos();
346
347
ThreadsListHandle tlh;
348
if (tlh.includes(target)) {
349
target->handshake_state()->add_operation(&op);
350
} else {
351
char buf[128];
352
jio_snprintf(buf, sizeof(buf), "(thread= " INTPTR_FORMAT " dead)", p2i(target));
353
log_handshake_info(start_time_ns, op.name(), 0, 0, buf);
354
return;
355
}
356
357
// Keeps count on how many of own emitted handshakes
358
// this thread execute.
359
int emitted_handshakes_executed = 0;
360
HandshakeSpinYield hsy(start_time_ns);
361
while (!op.is_completed()) {
362
HandshakeState::ProcessResult pr = target->handshake_state()->try_process(&op);
363
if (pr == HandshakeState::_succeeded) {
364
emitted_handshakes_executed++;
365
}
366
if (op.is_completed()) {
367
break;
368
}
369
370
// Check if handshake operation has timed out
371
check_handshake_timeout(start_time_ns, &op, target);
372
373
hsy.add_result(pr);
374
// Check for pending handshakes to avoid possible deadlocks where our
375
// target is trying to handshake us.
376
if (SafepointMechanism::should_process(self)) {
377
ThreadBlockInVM tbivm(self);
378
}
379
hsy.process();
380
}
381
382
// This pairs up with the release store in do_handshake(). It prevents future
383
// loads from floating above the load of _pending_threads in is_completed()
384
// and thus prevents reading stale data modified in the handshake closure
385
// by the Handshakee.
386
OrderAccess::acquire();
387
388
log_handshake_info(start_time_ns, op.name(), 1, emitted_handshakes_executed);
389
}
390
391
void Handshake::execute(AsyncHandshakeClosure* hs_cl, JavaThread* target) {
392
jlong start_time_ns = os::javaTimeNanos();
393
AsyncHandshakeOperation* op = new AsyncHandshakeOperation(hs_cl, target, start_time_ns);
394
395
ThreadsListHandle tlh;
396
if (tlh.includes(target)) {
397
target->handshake_state()->add_operation(op);
398
} else {
399
log_handshake_info(start_time_ns, op->name(), 0, 0, "(thread dead)");
400
delete op;
401
}
402
}
403
404
HandshakeState::HandshakeState(JavaThread* target) :
405
_handshakee(target),
406
_queue(),
407
_lock(Monitor::leaf, "HandshakeState", Mutex::_allow_vm_block_flag, Monitor::_safepoint_check_never),
408
_active_handshaker(),
409
_suspended(false),
410
_async_suspend_handshake(false)
411
{
412
}
413
414
void HandshakeState::add_operation(HandshakeOperation* op) {
415
// Adds are done lock free and so is arming.
416
_queue.push(op);
417
SafepointMechanism::arm_local_poll_release(_handshakee);
418
}
419
420
bool HandshakeState::operation_pending(HandshakeOperation* op) {
421
MutexLocker ml(&_lock, Mutex::_no_safepoint_check_flag);
422
class MatchOp {
423
HandshakeOperation* _op;
424
public:
425
MatchOp(HandshakeOperation* op) : _op(op) {}
426
bool operator()(HandshakeOperation* op) {
427
return op == _op;
428
}
429
};
430
MatchOp mo(op);
431
return _queue.contains(mo);
432
}
433
434
HandshakeOperation* HandshakeState::pop_for_self() {
435
assert(_handshakee == Thread::current(), "Must be called by self");
436
assert(_lock.owned_by_self(), "Lock must be held");
437
return _queue.pop();
438
};
439
440
static bool non_self_queue_filter(HandshakeOperation* op) {
441
return !op->is_async();
442
}
443
444
bool HandshakeState::have_non_self_executable_operation() {
445
assert(_handshakee != Thread::current(), "Must not be called by self");
446
assert(_lock.owned_by_self(), "Lock must be held");
447
return _queue.contains(non_self_queue_filter);
448
}
449
450
HandshakeOperation* HandshakeState::pop() {
451
assert(_handshakee != Thread::current(), "Must not be called by self");
452
assert(_lock.owned_by_self(), "Lock must be held");
453
return _queue.pop(non_self_queue_filter);
454
};
455
456
bool HandshakeState::process_by_self() {
457
assert(Thread::current() == _handshakee, "should call from _handshakee");
458
assert(!_handshakee->is_terminated(), "should not be a terminated thread");
459
assert(_handshakee->thread_state() != _thread_blocked, "should not be in a blocked state");
460
assert(_handshakee->thread_state() != _thread_in_native, "should not be in native");
461
ThreadInVMForHandshake tivm(_handshakee);
462
{
463
// Handshakes cannot safely safepoint.
464
// The exception to this rule is the asynchronous suspension handshake.
465
// It by-passes the NSV by manually doing the transition.
466
NoSafepointVerifier nsv;
467
return process_self_inner();
468
}
469
}
470
471
bool HandshakeState::process_self_inner() {
472
while (should_process()) {
473
MutexLocker ml(&_lock, Mutex::_no_safepoint_check_flag);
474
HandshakeOperation* op = pop_for_self();
475
if (op != NULL) {
476
assert(op->_target == NULL || op->_target == Thread::current(), "Wrong thread");
477
bool async = op->is_async();
478
log_trace(handshake)("Proc handshake %s " INTPTR_FORMAT " on " INTPTR_FORMAT " by self",
479
async ? "asynchronous" : "synchronous", p2i(op), p2i(_handshakee));
480
op->prepare(_handshakee, _handshakee);
481
if (!async) {
482
HandleMark hm(_handshakee);
483
PreserveExceptionMark pem(_handshakee);
484
op->do_handshake(_handshakee);
485
} else {
486
// An asynchronous handshake may put the JavaThread in blocked state (safepoint safe).
487
// The destructor ~PreserveExceptionMark touches the exception oop so it must not be executed,
488
// since a safepoint may be in-progress when returning from the async handshake.
489
op->do_handshake(_handshakee);
490
log_handshake_info(((AsyncHandshakeOperation*)op)->start_time(), op->name(), 1, 0, "asynchronous");
491
delete op;
492
return true; // Must check for safepoints
493
}
494
} else {
495
return false;
496
}
497
}
498
return false;
499
}
500
501
bool HandshakeState::can_process_handshake() {
502
// handshake_safe may only be called with polls armed.
503
// Handshaker controls this by first claiming the handshake via claim_handshake().
504
return SafepointSynchronize::handshake_safe(_handshakee);
505
}
506
507
bool HandshakeState::possibly_can_process_handshake() {
508
// Note that this method is allowed to produce false positives.
509
if (_handshakee->is_terminated()) {
510
return true;
511
}
512
switch (_handshakee->thread_state()) {
513
case _thread_in_native:
514
// native threads are safe if they have no java stack or have walkable stack
515
return !_handshakee->has_last_Java_frame() || _handshakee->frame_anchor()->walkable();
516
517
case _thread_blocked:
518
return true;
519
520
default:
521
return false;
522
}
523
}
524
525
bool HandshakeState::claim_handshake() {
526
if (!_lock.try_lock()) {
527
return false;
528
}
529
// Operations are added lock free and then the poll is armed.
530
// If all handshake operations for the handshakee are finished and someone
531
// just adds an operation we may see it here. But if the handshakee is not
532
// armed yet it is not safe to proceed.
533
if (have_non_self_executable_operation()) {
534
if (SafepointMechanism::local_poll_armed(_handshakee)) {
535
return true;
536
}
537
}
538
_lock.unlock();
539
return false;
540
}
541
542
HandshakeState::ProcessResult HandshakeState::try_process(HandshakeOperation* match_op) {
543
if (!has_operation()) {
544
// JT has already cleared its handshake
545
return HandshakeState::_no_operation;
546
}
547
548
if (!possibly_can_process_handshake()) {
549
// JT is observed in an unsafe state, it must notice the handshake itself
550
return HandshakeState::_not_safe;
551
}
552
553
// Claim the mutex if there still an operation to be executed.
554
if (!claim_handshake()) {
555
return HandshakeState::_claim_failed;
556
}
557
558
// If we own the mutex at this point and while owning the mutex we
559
// can observe a safe state the thread cannot possibly continue without
560
// getting caught by the mutex.
561
if (!can_process_handshake()) {
562
_lock.unlock();
563
return HandshakeState::_not_safe;
564
}
565
566
Thread* current_thread = Thread::current();
567
568
HandshakeState::ProcessResult pr_ret = HandshakeState::_processed;
569
int executed = 0;
570
571
do {
572
HandshakeOperation* op = pop();
573
if (op != NULL) {
574
assert(SafepointMechanism::local_poll_armed(_handshakee), "Must be");
575
assert(op->_target == NULL || _handshakee == op->_target, "Wrong thread");
576
log_trace(handshake)("Processing handshake " INTPTR_FORMAT " by %s(%s)", p2i(op),
577
op == match_op ? "handshaker" : "cooperative",
578
current_thread->is_VM_thread() ? "VM Thread" : "JavaThread");
579
580
if (op == match_op) {
581
pr_ret = HandshakeState::_succeeded;
582
}
583
584
op->prepare(_handshakee, current_thread);
585
586
_active_handshaker = current_thread;
587
op->do_handshake(_handshakee);
588
_active_handshaker = NULL;
589
590
executed++;
591
}
592
} while (have_non_self_executable_operation());
593
594
_lock.unlock();
595
596
log_trace(handshake)("%s(" INTPTR_FORMAT ") executed %d ops for JavaThread: " INTPTR_FORMAT " %s target op: " INTPTR_FORMAT,
597
current_thread->is_VM_thread() ? "VM Thread" : "JavaThread",
598
p2i(current_thread), executed, p2i(_handshakee),
599
pr_ret == HandshakeState::_succeeded ? "including" : "excluding", p2i(match_op));
600
return pr_ret;
601
}
602
603
void HandshakeState::do_self_suspend() {
604
assert(Thread::current() == _handshakee, "should call from _handshakee");
605
assert(_lock.owned_by_self(), "Lock must be held");
606
assert(!_handshakee->has_last_Java_frame() || _handshakee->frame_anchor()->walkable(), "should have walkable stack");
607
JavaThreadState jts = _handshakee->thread_state();
608
while (is_suspended()) {
609
_handshakee->set_thread_state(_thread_blocked);
610
log_trace(thread, suspend)("JavaThread:" INTPTR_FORMAT " suspended", p2i(_handshakee));
611
_lock.wait_without_safepoint_check();
612
}
613
_handshakee->set_thread_state(jts);
614
set_async_suspend_handshake(false);
615
log_trace(thread, suspend)("JavaThread:" INTPTR_FORMAT " resumed", p2i(_handshakee));
616
}
617
618
// This is the closure that prevents a suspended JavaThread from
619
// escaping the suspend request.
620
class ThreadSelfSuspensionHandshake : public AsyncHandshakeClosure {
621
public:
622
ThreadSelfSuspensionHandshake() : AsyncHandshakeClosure("ThreadSelfSuspensionHandshake") {}
623
void do_thread(Thread* thr) {
624
JavaThread* current = thr->as_Java_thread();
625
assert(current == Thread::current(), "Must be self executed.");
626
current->handshake_state()->do_self_suspend();
627
}
628
};
629
630
bool HandshakeState::suspend_with_handshake() {
631
if (_handshakee->is_exiting() ||
632
_handshakee->threadObj() == NULL) {
633
log_trace(thread, suspend)("JavaThread:" INTPTR_FORMAT " exiting", p2i(_handshakee));
634
return false;
635
}
636
if (has_async_suspend_handshake()) {
637
if (is_suspended()) {
638
// Target is already suspended.
639
log_trace(thread, suspend)("JavaThread:" INTPTR_FORMAT " already suspended", p2i(_handshakee));
640
return false;
641
} else {
642
// Target is going to wake up and leave suspension.
643
// Let's just stop the thread from doing that.
644
log_trace(thread, suspend)("JavaThread:" INTPTR_FORMAT " re-suspended", p2i(_handshakee));
645
set_suspended(true);
646
return true;
647
}
648
}
649
// no suspend request
650
assert(!is_suspended(), "cannot be suspended without a suspend request");
651
// Thread is safe, so it must execute the request, thus we can count it as suspended
652
// from this point.
653
set_suspended(true);
654
set_async_suspend_handshake(true);
655
log_trace(thread, suspend)("JavaThread:" INTPTR_FORMAT " suspended, arming ThreadSuspension", p2i(_handshakee));
656
ThreadSelfSuspensionHandshake* ts = new ThreadSelfSuspensionHandshake();
657
Handshake::execute(ts, _handshakee);
658
return true;
659
}
660
661
// This is the closure that synchronously honors the suspend request.
662
class SuspendThreadHandshake : public HandshakeClosure {
663
bool _did_suspend;
664
public:
665
SuspendThreadHandshake() : HandshakeClosure("SuspendThread"), _did_suspend(false) {}
666
void do_thread(Thread* thr) {
667
JavaThread* target = thr->as_Java_thread();
668
_did_suspend = target->handshake_state()->suspend_with_handshake();
669
}
670
bool did_suspend() { return _did_suspend; }
671
};
672
673
bool HandshakeState::suspend() {
674
SuspendThreadHandshake st;
675
Handshake::execute(&st, _handshakee);
676
return st.did_suspend();
677
}
678
679
bool HandshakeState::resume() {
680
if (!is_suspended()) {
681
return false;
682
}
683
MutexLocker ml(&_lock, Mutex::_no_safepoint_check_flag);
684
if (!is_suspended()) {
685
assert(!_handshakee->is_suspended(), "cannot be suspended without a suspend request");
686
return false;
687
}
688
// Resume the thread.
689
set_suspended(false);
690
_lock.notify();
691
return true;
692
}
693
694