/
referenceProcessor.cpp
1326 lines (1166 loc) · 50.7 KB
/
referenceProcessor.cpp
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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2001, 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
#include "precompiled.hpp"
#include "classfile/javaClasses.inline.hpp"
#include "gc/shared/collectedHeap.hpp"
#include "gc/shared/collectedHeap.inline.hpp"
#include "gc/shared/gc_globals.hpp"
#include "gc/shared/gcTimer.hpp"
#include "gc/shared/gcTraceTime.inline.hpp"
#include "gc/shared/referencePolicy.hpp"
#include "gc/shared/referenceProcessor.inline.hpp"
#include "gc/shared/referenceProcessorPhaseTimes.hpp"
#include "logging/log.hpp"
#include "memory/allocation.inline.hpp"
#include "memory/resourceArea.hpp"
#include "memory/universe.hpp"
#include "oops/access.inline.hpp"
#include "oops/oop.inline.hpp"
#include "runtime/java.hpp"
#include "runtime/nonJavaThread.hpp"
ReferencePolicy* ReferenceProcessor::_always_clear_soft_ref_policy = NULL;
ReferencePolicy* ReferenceProcessor::_default_soft_ref_policy = NULL;
jlong ReferenceProcessor::_soft_ref_timestamp_clock = 0;
void referenceProcessor_init() {
ReferenceProcessor::init_statics();
}
void ReferenceProcessor::init_statics() {
// We need a monotonically non-decreasing time in ms but
// os::javaTimeMillis() does not guarantee monotonicity.
jlong now = os::javaTimeNanos() / NANOSECS_PER_MILLISEC;
// Initialize the soft ref timestamp clock.
_soft_ref_timestamp_clock = now;
// Also update the soft ref clock in j.l.r.SoftReference
java_lang_ref_SoftReference::set_clock(_soft_ref_timestamp_clock);
_always_clear_soft_ref_policy = new AlwaysClearPolicy();
if (CompilerConfig::is_c2_or_jvmci_compiler_enabled()) {
_default_soft_ref_policy = new LRUMaxHeapPolicy();
} else {
_default_soft_ref_policy = new LRUCurrentHeapPolicy();
}
guarantee(RefDiscoveryPolicy == ReferenceBasedDiscovery ||
RefDiscoveryPolicy == ReferentBasedDiscovery,
"Unrecognized RefDiscoveryPolicy");
}
void ReferenceProcessor::enable_discovery(bool check_no_refs) {
#ifdef ASSERT
// Verify that we're not currently discovering refs
assert(!_discovering_refs, "nested call?");
if (check_no_refs) {
// Verify that the discovered lists are empty
verify_no_references_recorded();
}
#endif // ASSERT
// Someone could have modified the value of the static
// field in the j.l.r.SoftReference class that holds the
// soft reference timestamp clock using reflection or
// Unsafe between GCs. Unconditionally update the static
// field in ReferenceProcessor here so that we use the new
// value during reference discovery.
_soft_ref_timestamp_clock = java_lang_ref_SoftReference::clock();
_discovering_refs = true;
}
ReferenceProcessor::ReferenceProcessor(BoolObjectClosure* is_subject_to_discovery,
uint mt_processing_degree,
bool mt_discovery,
uint mt_discovery_degree,
bool atomic_discovery,
BoolObjectClosure* is_alive_non_header) :
_is_subject_to_discovery(is_subject_to_discovery),
_discovering_refs(false),
_enqueuing_is_done(false),
_next_id(0),
_is_alive_non_header(is_alive_non_header)
{
assert(is_subject_to_discovery != NULL, "must be set");
_discovery_is_atomic = atomic_discovery;
_discovery_is_mt = mt_discovery;
_num_queues = MAX2(1U, mt_processing_degree);
_max_num_queues = MAX2(_num_queues, mt_discovery_degree);
_discovered_refs = NEW_C_HEAP_ARRAY(DiscoveredList,
_max_num_queues * number_of_subclasses_of_ref(), mtGC);
_discoveredSoftRefs = &_discovered_refs[0];
_discoveredWeakRefs = &_discoveredSoftRefs[_max_num_queues];
_discoveredFinalRefs = &_discoveredWeakRefs[_max_num_queues];
_discoveredPhantomRefs = &_discoveredFinalRefs[_max_num_queues];
// Initialize all entries to NULL
for (uint i = 0; i < _max_num_queues * number_of_subclasses_of_ref(); i++) {
_discovered_refs[i].clear();
}
setup_policy(false /* default soft ref policy */);
}
#ifndef PRODUCT
void ReferenceProcessor::verify_no_references_recorded() {
guarantee(!_discovering_refs, "Discovering refs?");
for (uint i = 0; i < _max_num_queues * number_of_subclasses_of_ref(); i++) {
guarantee(_discovered_refs[i].is_empty(),
"Found non-empty discovered list at %u", i);
}
}
#endif
bool ReferenceProcessor::processing_is_mt() const {
return ParallelRefProcEnabled && _num_queues > 1;
}
void ReferenceProcessor::weak_oops_do(OopClosure* f) {
for (uint i = 0; i < _max_num_queues * number_of_subclasses_of_ref(); i++) {
if (UseCompressedOops) {
f->do_oop((narrowOop*)_discovered_refs[i].adr_head());
} else {
f->do_oop((oop*)_discovered_refs[i].adr_head());
}
}
}
void ReferenceProcessor::update_soft_ref_master_clock() {
// Update (advance) the soft ref master clock field. This must be done
// after processing the soft ref list.
// We need a monotonically non-decreasing time in ms but
// os::javaTimeMillis() does not guarantee monotonicity.
jlong now = os::javaTimeNanos() / NANOSECS_PER_MILLISEC;
jlong soft_ref_clock = java_lang_ref_SoftReference::clock();
assert(soft_ref_clock == _soft_ref_timestamp_clock, "soft ref clocks out of sync");
NOT_PRODUCT(
if (now < _soft_ref_timestamp_clock) {
log_warning(gc)("time warp: " JLONG_FORMAT " to " JLONG_FORMAT,
_soft_ref_timestamp_clock, now);
}
)
// The values of now and _soft_ref_timestamp_clock are set using
// javaTimeNanos(), which is guaranteed to be monotonically
// non-decreasing provided the underlying platform provides such
// a time source (and it is bug free).
// In product mode, however, protect ourselves from non-monotonicity.
if (now > _soft_ref_timestamp_clock) {
_soft_ref_timestamp_clock = now;
java_lang_ref_SoftReference::set_clock(now);
}
// Else leave clock stalled at its old value until time progresses
// past clock value.
}
size_t ReferenceProcessor::total_count(DiscoveredList lists[]) const {
size_t total = 0;
for (uint i = 0; i < _max_num_queues; ++i) {
total += lists[i].length();
}
return total;
}
#ifdef ASSERT
void ReferenceProcessor::verify_total_count_zero(DiscoveredList lists[], const char* type) {
size_t count = total_count(lists);
assert(count == 0, "%ss must be empty but has " SIZE_FORMAT " elements", type, count);
}
#endif
ReferenceProcessorStats ReferenceProcessor::process_discovered_references(RefProcProxyTask& proxy_task,
ReferenceProcessorPhaseTimes& phase_times) {
double start_time = os::elapsedTime();
assert(!enqueuing_is_done(), "If here enqueuing should not be complete");
// Stop treating discovered references specially.
disable_discovery();
// If discovery was concurrent, someone could have modified
// the value of the static field in the j.l.r.SoftReference
// class that holds the soft reference timestamp clock using
// reflection or Unsafe between when discovery was enabled and
// now. Unconditionally update the static field in ReferenceProcessor
// here so that we use the new value during processing of the
// discovered soft refs.
_soft_ref_timestamp_clock = java_lang_ref_SoftReference::clock();
ReferenceProcessorStats stats(total_count(_discoveredSoftRefs),
total_count(_discoveredWeakRefs),
total_count(_discoveredFinalRefs),
total_count(_discoveredPhantomRefs));
{
RefProcTotalPhaseTimesTracker tt(RefPhase1, &phase_times);
process_soft_ref_reconsider(proxy_task, phase_times);
}
update_soft_ref_master_clock();
{
RefProcTotalPhaseTimesTracker tt(RefPhase2, &phase_times);
process_soft_weak_final_refs(proxy_task, phase_times);
}
{
RefProcTotalPhaseTimesTracker tt(RefPhase3, &phase_times);
process_final_keep_alive(proxy_task, phase_times);
}
{
RefProcTotalPhaseTimesTracker tt(RefPhase4, &phase_times);
process_phantom_refs(proxy_task, phase_times);
}
phase_times.set_total_time_ms((os::elapsedTime() - start_time) * 1000);
return stats;
}
void DiscoveredListIterator::load_ptrs(DEBUG_ONLY(bool allow_null_referent)) {
_current_discovered_addr = java_lang_ref_Reference::discovered_addr_raw(_current_discovered);
oop discovered = java_lang_ref_Reference::discovered(_current_discovered);
assert(_current_discovered_addr && oopDesc::is_oop_or_null(discovered),
"Expected an oop or NULL for discovered field at " PTR_FORMAT, p2i(discovered));
_next_discovered = discovered;
_referent = java_lang_ref_Reference::unknown_referent_no_keepalive(_current_discovered);
assert(Universe::heap()->is_in_or_null(_referent),
"Wrong oop found in java.lang.Reference object");
assert(allow_null_referent ?
oopDesc::is_oop_or_null(_referent)
: oopDesc::is_oop(_referent),
"Expected an oop%s for referent field at " PTR_FORMAT,
(allow_null_referent ? " or NULL" : ""),
p2i(_referent));
}
void DiscoveredListIterator::remove() {
assert(oopDesc::is_oop(_current_discovered), "Dropping a bad reference");
RawAccess<>::oop_store(_current_discovered_addr, oop(NULL));
// First _prev_next ref actually points into DiscoveredList (gross).
oop new_next;
if (_next_discovered == _current_discovered) {
// At the end of the list, we should make _prev point to itself.
// If _ref is the first ref, then _prev_next will be in the DiscoveredList,
// and _prev will be NULL.
new_next = _prev_discovered;
} else {
new_next = _next_discovered;
}
// Remove Reference object from discovered list. Note that G1 does not need a
// pre-barrier here because we know the Reference has already been found/marked,
// that's how it ended up in the discovered list in the first place.
RawAccess<>::oop_store(_prev_discovered_addr, new_next);
_removed++;
_refs_list.dec_length(1);
}
void DiscoveredListIterator::make_referent_alive() {
HeapWord* addr = java_lang_ref_Reference::referent_addr_raw(_current_discovered);
if (UseCompressedOops) {
_keep_alive->do_oop((narrowOop*)addr);
} else {
_keep_alive->do_oop((oop*)addr);
}
}
void DiscoveredListIterator::clear_referent() {
java_lang_ref_Reference::clear_referent(_current_discovered);
}
void DiscoveredListIterator::enqueue() {
HeapAccess<AS_NO_KEEPALIVE>::oop_store_at(_current_discovered,
java_lang_ref_Reference::discovered_offset(),
_next_discovered);
}
void DiscoveredListIterator::complete_enqueue() {
if (_prev_discovered != NULL) {
// This is the last object.
// Swap refs_list into pending list and set obj's
// discovered to what we read from the pending list.
oop old = Universe::swap_reference_pending_list(_refs_list.head());
HeapAccess<AS_NO_KEEPALIVE>::oop_store_at(_prev_discovered, java_lang_ref_Reference::discovered_offset(), old);
}
}
inline void log_dropped_ref(const DiscoveredListIterator& iter, const char* reason) {
if (log_develop_is_enabled(Trace, gc, ref)) {
ResourceMark rm;
log_develop_trace(gc, ref)("Dropping %s reference " PTR_FORMAT ": %s",
reason, p2i(iter.obj()),
iter.obj()->klass()->internal_name());
}
}
inline void log_enqueued_ref(const DiscoveredListIterator& iter, const char* reason) {
if (log_develop_is_enabled(Trace, gc, ref)) {
ResourceMark rm;
log_develop_trace(gc, ref)("Enqueue %s reference (" INTPTR_FORMAT ": %s)",
reason, p2i(iter.obj()), iter.obj()->klass()->internal_name());
}
assert(oopDesc::is_oop(iter.obj()), "Adding a bad reference");
}
size_t ReferenceProcessor::process_soft_ref_reconsider_work(DiscoveredList& refs_list,
ReferencePolicy* policy,
BoolObjectClosure* is_alive,
OopClosure* keep_alive,
VoidClosure* complete_gc) {
assert(policy != NULL, "Must have a non-NULL policy");
DiscoveredListIterator iter(refs_list, keep_alive, is_alive);
// Decide which softly reachable refs should be kept alive.
while (iter.has_next()) {
iter.load_ptrs(DEBUG_ONLY(!discovery_is_atomic() /* allow_null_referent */));
bool referent_is_dead = (iter.referent() != NULL) && !iter.is_referent_alive();
if (referent_is_dead &&
!policy->should_clear_reference(iter.obj(), _soft_ref_timestamp_clock)) {
log_dropped_ref(iter, "by policy");
// Remove Reference object from list
iter.remove();
// keep the referent around
iter.make_referent_alive();
iter.move_to_next();
} else {
iter.next();
}
}
// Close the reachable set
complete_gc->do_void();
log_develop_trace(gc, ref)(" Dropped " SIZE_FORMAT " dead Refs out of " SIZE_FORMAT " discovered Refs by policy, from list " INTPTR_FORMAT,
iter.removed(), iter.processed(), p2i(&refs_list));
return iter.removed();
}
size_t ReferenceProcessor::process_soft_weak_final_refs_work(DiscoveredList& refs_list,
BoolObjectClosure* is_alive,
OopClosure* keep_alive,
bool do_enqueue_and_clear) {
DiscoveredListIterator iter(refs_list, keep_alive, is_alive);
while (iter.has_next()) {
iter.load_ptrs(DEBUG_ONLY(!discovery_is_atomic() /* allow_null_referent */));
if (iter.referent() == NULL) {
// Reference has been cleared since discovery; only possible if
// discovery is not atomic (checked by load_ptrs). Remove
// reference from list.
log_dropped_ref(iter, "cleared");
iter.remove();
iter.move_to_next();
} else if (iter.is_referent_alive()) {
// The referent is reachable after all.
// Remove reference from list.
log_dropped_ref(iter, "reachable");
iter.remove();
// Update the referent pointer as necessary. Note that this
// should not entail any recursive marking because the
// referent must already have been traversed.
iter.make_referent_alive();
iter.move_to_next();
} else {
if (do_enqueue_and_clear) {
iter.clear_referent();
iter.enqueue();
log_enqueued_ref(iter, "cleared");
}
// Keep in discovered list
iter.next();
}
}
if (do_enqueue_and_clear) {
iter.complete_enqueue();
refs_list.clear();
}
log_develop_trace(gc, ref)(" Dropped " SIZE_FORMAT " active Refs out of " SIZE_FORMAT
" Refs in discovered list " INTPTR_FORMAT,
iter.removed(), iter.processed(), p2i(&refs_list));
return iter.removed();
}
size_t ReferenceProcessor::process_final_keep_alive_work(DiscoveredList& refs_list,
OopClosure* keep_alive,
VoidClosure* complete_gc) {
DiscoveredListIterator iter(refs_list, keep_alive, NULL);
while (iter.has_next()) {
iter.load_ptrs(DEBUG_ONLY(false /* allow_null_referent */));
// keep the referent and followers around
iter.make_referent_alive();
// Self-loop next, to mark the FinalReference not active.
assert(java_lang_ref_Reference::next(iter.obj()) == NULL, "enqueued FinalReference");
java_lang_ref_Reference::set_next_raw(iter.obj(), iter.obj());
iter.enqueue();
log_enqueued_ref(iter, "Final");
iter.next();
}
iter.complete_enqueue();
// Close the reachable set
complete_gc->do_void();
refs_list.clear();
assert(iter.removed() == 0, "This phase does not remove anything.");
return iter.removed();
}
size_t ReferenceProcessor::process_phantom_refs_work(DiscoveredList& refs_list,
BoolObjectClosure* is_alive,
OopClosure* keep_alive,
VoidClosure* complete_gc) {
DiscoveredListIterator iter(refs_list, keep_alive, is_alive);
while (iter.has_next()) {
iter.load_ptrs(DEBUG_ONLY(!discovery_is_atomic() /* allow_null_referent */));
oop const referent = iter.referent();
if (referent == NULL || iter.is_referent_alive()) {
iter.make_referent_alive();
iter.remove();
iter.move_to_next();
} else {
iter.clear_referent();
iter.enqueue();
log_enqueued_ref(iter, "cleared Phantom");
iter.next();
}
}
iter.complete_enqueue();
// Close the reachable set; needed for collectors which keep_alive_closure do
// not immediately complete their work.
complete_gc->do_void();
refs_list.clear();
return iter.removed();
}
void
ReferenceProcessor::clear_discovered_references(DiscoveredList& refs_list) {
oop obj = NULL;
oop next = refs_list.head();
while (next != obj) {
obj = next;
next = java_lang_ref_Reference::discovered(obj);
java_lang_ref_Reference::set_discovered_raw(obj, NULL);
}
refs_list.clear();
}
void ReferenceProcessor::abandon_partial_discovery() {
// loop over the lists
for (uint i = 0; i < _max_num_queues * number_of_subclasses_of_ref(); i++) {
if ((i % _max_num_queues) == 0) {
log_develop_trace(gc, ref)("Abandoning %s discovered list", list_name(i));
}
clear_discovered_references(_discovered_refs[i]);
}
}
size_t ReferenceProcessor::total_reference_count(ReferenceType type) const {
DiscoveredList* list = NULL;
switch (type) {
case REF_SOFT:
list = _discoveredSoftRefs;
break;
case REF_WEAK:
list = _discoveredWeakRefs;
break;
case REF_FINAL:
list = _discoveredFinalRefs;
break;
case REF_PHANTOM:
list = _discoveredPhantomRefs;
break;
case REF_OTHER:
case REF_NONE:
default:
ShouldNotReachHere();
}
return total_count(list);
}
class RefProcPhase1Task : public RefProcTask {
public:
RefProcPhase1Task(ReferenceProcessor& ref_processor,
ReferenceProcessorPhaseTimes* phase_times,
ReferencePolicy* policy)
: RefProcTask(ref_processor,
phase_times),
_policy(policy) { }
void rp_work(uint worker_id,
BoolObjectClosure* is_alive,
OopClosure* keep_alive,
VoidClosure* complete_gc) override {
ResourceMark rm;
RefProcSubPhasesWorkerTimeTracker tt(ReferenceProcessor::SoftRefSubPhase1, _phase_times, tracker_id(worker_id));
size_t const removed = _ref_processor.process_soft_ref_reconsider_work(_ref_processor._discoveredSoftRefs[worker_id],
_policy,
is_alive,
keep_alive,
complete_gc);
_phase_times->add_ref_cleared(REF_SOFT, removed);
}
private:
ReferencePolicy* _policy;
};
class RefProcPhase2Task: public RefProcTask {
void run_phase2(uint worker_id,
DiscoveredList list[],
BoolObjectClosure* is_alive,
OopClosure* keep_alive,
bool do_enqueue_and_clear,
ReferenceType ref_type) {
size_t const removed = _ref_processor.process_soft_weak_final_refs_work(list[worker_id],
is_alive,
keep_alive,
do_enqueue_and_clear);
_phase_times->add_ref_cleared(ref_type, removed);
}
public:
RefProcPhase2Task(ReferenceProcessor& ref_processor,
ReferenceProcessorPhaseTimes* phase_times)
: RefProcTask(ref_processor,
phase_times) {}
void rp_work(uint worker_id,
BoolObjectClosure* is_alive,
OopClosure* keep_alive,
VoidClosure* complete_gc) override {
ResourceMark rm;
RefProcWorkerTimeTracker t(_phase_times->phase2_worker_time_sec(), tracker_id(worker_id));
{
RefProcSubPhasesWorkerTimeTracker tt(ReferenceProcessor::SoftRefSubPhase2, _phase_times, tracker_id(worker_id));
run_phase2(worker_id, _ref_processor._discoveredSoftRefs, is_alive, keep_alive, true /* do_enqueue_and_clear */, REF_SOFT);
}
{
RefProcSubPhasesWorkerTimeTracker tt(ReferenceProcessor::WeakRefSubPhase2, _phase_times, tracker_id(worker_id));
run_phase2(worker_id, _ref_processor._discoveredWeakRefs, is_alive, keep_alive, true /* do_enqueue_and_clear */, REF_WEAK);
}
{
RefProcSubPhasesWorkerTimeTracker tt(ReferenceProcessor::FinalRefSubPhase2, _phase_times, tracker_id(worker_id));
run_phase2(worker_id, _ref_processor._discoveredFinalRefs, is_alive, keep_alive, false /* do_enqueue_and_clear */, REF_FINAL);
}
// Close the reachable set; needed for collectors which keep_alive_closure do
// not immediately complete their work.
complete_gc->do_void();
}
};
class RefProcPhase3Task: public RefProcTask {
public:
RefProcPhase3Task(ReferenceProcessor& ref_processor,
ReferenceProcessorPhaseTimes* phase_times)
: RefProcTask(ref_processor,
phase_times) {}
void rp_work(uint worker_id,
BoolObjectClosure* is_alive,
OopClosure* keep_alive,
VoidClosure* complete_gc) override {
ResourceMark rm;
RefProcSubPhasesWorkerTimeTracker tt(ReferenceProcessor::FinalRefSubPhase3, _phase_times, tracker_id(worker_id));
_ref_processor.process_final_keep_alive_work(_ref_processor._discoveredFinalRefs[worker_id], keep_alive, complete_gc);
}
};
class RefProcPhase4Task: public RefProcTask {
public:
RefProcPhase4Task(ReferenceProcessor& ref_processor,
ReferenceProcessorPhaseTimes* phase_times)
: RefProcTask(ref_processor,
phase_times) {}
void rp_work(uint worker_id,
BoolObjectClosure* is_alive,
OopClosure* keep_alive,
VoidClosure* complete_gc) override {
ResourceMark rm;
RefProcSubPhasesWorkerTimeTracker tt(ReferenceProcessor::PhantomRefSubPhase4, _phase_times, tracker_id(worker_id));
size_t const removed = _ref_processor.process_phantom_refs_work(_ref_processor._discoveredPhantomRefs[worker_id],
is_alive,
keep_alive,
complete_gc);
_phase_times->add_ref_cleared(REF_PHANTOM, removed);
}
};
void ReferenceProcessor::log_reflist(const char* prefix, DiscoveredList list[], uint num_active_queues) {
LogTarget(Trace, gc, ref) lt;
if (!lt.is_enabled()) {
return;
}
size_t total = 0;
LogStream ls(lt);
ls.print("%s", prefix);
for (uint i = 0; i < num_active_queues; i++) {
ls.print(SIZE_FORMAT " ", list[i].length());
total += list[i].length();
}
ls.print_cr("(" SIZE_FORMAT ")", total);
}
#ifndef PRODUCT
void ReferenceProcessor::log_reflist_counts(DiscoveredList ref_lists[], uint num_active_queues) {
if (!log_is_enabled(Trace, gc, ref)) {
return;
}
log_reflist("", ref_lists, num_active_queues);
#ifdef ASSERT
for (uint i = num_active_queues; i < _max_num_queues; i++) {
assert(ref_lists[i].length() == 0, SIZE_FORMAT " unexpected References in %u",
ref_lists[i].length(), i);
}
#endif
}
#endif
void ReferenceProcessor::set_active_mt_degree(uint v) {
_num_queues = v;
_next_id = 0;
}
bool ReferenceProcessor::need_balance_queues(DiscoveredList refs_lists[]) {
assert(processing_is_mt(), "why balance non-mt processing?");
// _num_queues is the processing degree. Only list entries up to
// _num_queues will be processed, so any non-empty lists beyond
// that must be redistributed to lists in that range. Even if not
// needed for that, balancing may be desirable to eliminate poor
// distribution of references among the lists.
if (ParallelRefProcBalancingEnabled) {
return true; // Configuration says do it.
} else {
// Configuration says don't balance, but if there are non-empty
// lists beyond the processing degree, then must ignore the
// configuration and balance anyway.
for (uint i = _num_queues; i < _max_num_queues; ++i) {
if (!refs_lists[i].is_empty()) {
return true; // Must balance despite configuration.
}
}
return false; // Safe to obey configuration and not balance.
}
}
void ReferenceProcessor::maybe_balance_queues(DiscoveredList refs_lists[]) {
assert(processing_is_mt(), "Should not call this otherwise");
if (need_balance_queues(refs_lists)) {
balance_queues(refs_lists);
}
}
// Balances reference queues.
// Move entries from all queues[0, 1, ..., _max_num_q-1] to
// queues[0, 1, ..., _num_q-1] because only the first _num_q
// corresponding to the active workers will be processed.
void ReferenceProcessor::balance_queues(DiscoveredList ref_lists[])
{
// calculate total length
size_t total_refs = 0;
log_develop_trace(gc, ref)("Balance ref_lists ");
log_reflist_counts(ref_lists, _max_num_queues);
for (uint i = 0; i < _max_num_queues; ++i) {
total_refs += ref_lists[i].length();
}
size_t avg_refs = total_refs / _num_queues + 1;
uint to_idx = 0;
for (uint from_idx = 0; from_idx < _max_num_queues; from_idx++) {
bool move_all = false;
if (from_idx >= _num_queues) {
move_all = ref_lists[from_idx].length() > 0;
}
while ((ref_lists[from_idx].length() > avg_refs) ||
move_all) {
assert(to_idx < _num_queues, "Sanity Check!");
if (ref_lists[to_idx].length() < avg_refs) {
// move superfluous refs
size_t refs_to_move;
// Move all the Ref's if the from queue will not be processed.
if (move_all) {
refs_to_move = MIN2(ref_lists[from_idx].length(),
avg_refs - ref_lists[to_idx].length());
} else {
refs_to_move = MIN2(ref_lists[from_idx].length() - avg_refs,
avg_refs - ref_lists[to_idx].length());
}
assert(refs_to_move > 0, "otherwise the code below will fail");
oop move_head = ref_lists[from_idx].head();
oop move_tail = move_head;
oop new_head = move_head;
// find an element to split the list on
for (size_t j = 0; j < refs_to_move; ++j) {
move_tail = new_head;
new_head = java_lang_ref_Reference::discovered(new_head);
}
// Add the chain to the to list.
if (ref_lists[to_idx].head() == NULL) {
// to list is empty. Make a loop at the end.
java_lang_ref_Reference::set_discovered_raw(move_tail, move_tail);
} else {
java_lang_ref_Reference::set_discovered_raw(move_tail, ref_lists[to_idx].head());
}
ref_lists[to_idx].set_head(move_head);
ref_lists[to_idx].inc_length(refs_to_move);
// Remove the chain from the from list.
if (move_tail == new_head) {
// We found the end of the from list.
ref_lists[from_idx].set_head(NULL);
} else {
ref_lists[from_idx].set_head(new_head);
}
ref_lists[from_idx].dec_length(refs_to_move);
if (ref_lists[from_idx].length() == 0) {
break;
}
} else {
to_idx = (to_idx + 1) % _num_queues;
}
}
}
#ifdef ASSERT
log_reflist_counts(ref_lists, _num_queues);
size_t balanced_total_refs = 0;
for (uint i = 0; i < _num_queues; ++i) {
balanced_total_refs += ref_lists[i].length();
}
assert(total_refs == balanced_total_refs, "Balancing was incomplete");
#endif
}
void ReferenceProcessor::run_task(RefProcTask& task, RefProcProxyTask& proxy_task, bool marks_oops_alive) {
log_debug(gc, ref)("ReferenceProcessor::execute queues: %d, %s, marks_oops_alive: %s",
num_queues(),
processing_is_mt() ? "RefProcThreadModel::Multi" : "RefProcThreadModel::Single",
marks_oops_alive ? "true" : "false");
proxy_task.prepare_run_task(task, num_queues(), processing_is_mt() ? RefProcThreadModel::Multi : RefProcThreadModel::Single, marks_oops_alive);
if (processing_is_mt()) {
WorkGang* gang = Universe::heap()->safepoint_workers();
assert(gang != NULL, "can not dispatch multi threaded without a work gang");
assert(gang->active_workers() >= num_queues(),
"Ergonomically chosen workers(%u) should be less than or equal to active workers(%u)",
num_queues(), gang->active_workers());
gang->run_task(&proxy_task, num_queues());
} else {
for (unsigned i = 0; i < _max_num_queues; ++i) {
proxy_task.work(i);
}
}
}
void ReferenceProcessor::process_soft_ref_reconsider(RefProcProxyTask& proxy_task,
ReferenceProcessorPhaseTimes& phase_times) {
size_t const num_soft_refs = total_count(_discoveredSoftRefs);
phase_times.set_ref_discovered(REF_SOFT, num_soft_refs);
phase_times.set_processing_is_mt(processing_is_mt());
if (num_soft_refs == 0) {
log_debug(gc, ref)("Skipped phase 1 of Reference Processing: no references");
return;
}
if (_current_soft_ref_policy == NULL) {
log_debug(gc, ref)("Skipped phase 1 of Reference Processing: no policy");
return;
}
RefProcMTDegreeAdjuster a(this, RefPhase1, num_soft_refs);
if (processing_is_mt()) {
RefProcBalanceQueuesTimeTracker tt(RefPhase1, &phase_times);
maybe_balance_queues(_discoveredSoftRefs);
}
RefProcPhaseTimeTracker tt(RefPhase1, &phase_times);
log_reflist("Phase 1 Soft before", _discoveredSoftRefs, _max_num_queues);
RefProcPhase1Task phase1(*this, &phase_times, _current_soft_ref_policy);
run_task(phase1, proxy_task, true);
log_reflist("Phase 1 Soft after", _discoveredSoftRefs, _max_num_queues);
}
void ReferenceProcessor::process_soft_weak_final_refs(RefProcProxyTask& proxy_task,
ReferenceProcessorPhaseTimes& phase_times) {
size_t const num_soft_refs = total_count(_discoveredSoftRefs);
size_t const num_weak_refs = total_count(_discoveredWeakRefs);
size_t const num_final_refs = total_count(_discoveredFinalRefs);
size_t const num_total_refs = num_soft_refs + num_weak_refs + num_final_refs;
phase_times.set_ref_discovered(REF_WEAK, num_weak_refs);
phase_times.set_ref_discovered(REF_FINAL, num_final_refs);
phase_times.set_processing_is_mt(processing_is_mt());
if (num_total_refs == 0) {
log_debug(gc, ref)("Skipped phase 2 of Reference Processing: no references");
return;
}
RefProcMTDegreeAdjuster a(this, RefPhase2, num_total_refs);
if (processing_is_mt()) {
RefProcBalanceQueuesTimeTracker tt(RefPhase2, &phase_times);
maybe_balance_queues(_discoveredSoftRefs);
maybe_balance_queues(_discoveredWeakRefs);
maybe_balance_queues(_discoveredFinalRefs);
}
RefProcPhaseTimeTracker tt(RefPhase2, &phase_times);
log_reflist("Phase 2 Soft before", _discoveredSoftRefs, _max_num_queues);
log_reflist("Phase 2 Weak before", _discoveredWeakRefs, _max_num_queues);
log_reflist("Phase 2 Final before", _discoveredFinalRefs, _max_num_queues);
RefProcPhase2Task phase2(*this, &phase_times);
run_task(phase2, proxy_task, false);
verify_total_count_zero(_discoveredSoftRefs, "SoftReference");
verify_total_count_zero(_discoveredWeakRefs, "WeakReference");
log_reflist("Phase 2 Final after", _discoveredFinalRefs, _max_num_queues);
}
void ReferenceProcessor::process_final_keep_alive(RefProcProxyTask& proxy_task,
ReferenceProcessorPhaseTimes& phase_times) {
size_t const num_final_refs = total_count(_discoveredFinalRefs);
phase_times.set_processing_is_mt(processing_is_mt());
if (num_final_refs == 0) {
log_debug(gc, ref)("Skipped phase 3 of Reference Processing: no references");
return;
}
RefProcMTDegreeAdjuster a(this, RefPhase3, num_final_refs);
if (processing_is_mt()) {
RefProcBalanceQueuesTimeTracker tt(RefPhase3, &phase_times);
maybe_balance_queues(_discoveredFinalRefs);
}
// Phase 3:
// . Traverse referents of final references and keep them and followers alive.
RefProcPhaseTimeTracker tt(RefPhase3, &phase_times);
RefProcPhase3Task phase3(*this, &phase_times);
run_task(phase3, proxy_task, true);
verify_total_count_zero(_discoveredFinalRefs, "FinalReference");
}
void ReferenceProcessor::process_phantom_refs(RefProcProxyTask& proxy_task,
ReferenceProcessorPhaseTimes& phase_times) {
size_t const num_phantom_refs = total_count(_discoveredPhantomRefs);
phase_times.set_ref_discovered(REF_PHANTOM, num_phantom_refs);
phase_times.set_processing_is_mt(processing_is_mt());
if (num_phantom_refs == 0) {
log_debug(gc, ref)("Skipped phase 4 of Reference Processing: no references");
return;
}
RefProcMTDegreeAdjuster a(this, RefPhase4, num_phantom_refs);
if (processing_is_mt()) {
RefProcBalanceQueuesTimeTracker tt(RefPhase4, &phase_times);
maybe_balance_queues(_discoveredPhantomRefs);
}
// Phase 4: Walk phantom references appropriately.
RefProcPhaseTimeTracker tt(RefPhase4, &phase_times);
log_reflist("Phase 4 Phantom before", _discoveredPhantomRefs, _max_num_queues);
RefProcPhase4Task phase4(*this, &phase_times);
run_task(phase4, proxy_task, false);
verify_total_count_zero(_discoveredPhantomRefs, "PhantomReference");
}
inline DiscoveredList* ReferenceProcessor::get_discovered_list(ReferenceType rt) {
uint id = 0;
// Determine the queue index to use for this object.
if (_discovery_is_mt) {
// During a multi-threaded discovery phase,
// each thread saves to its "own" list.
id = WorkerThread::current()->id();
} else {
// single-threaded discovery, we save in round-robin
// fashion to each of the lists.
if (processing_is_mt()) {
id = next_id();
}
}
assert(id < _max_num_queues, "Id is out of bounds id %u and max id %u)", id, _max_num_queues);
// Get the discovered queue to which we will add
DiscoveredList* list = NULL;
switch (rt) {
case REF_OTHER:
// Unknown reference type, no special treatment
break;
case REF_SOFT:
list = &_discoveredSoftRefs[id];
break;
case REF_WEAK:
list = &_discoveredWeakRefs[id];
break;
case REF_FINAL:
list = &_discoveredFinalRefs[id];
break;
case REF_PHANTOM:
list = &_discoveredPhantomRefs[id];
break;
case REF_NONE:
// we should not reach here if we are an InstanceRefKlass
default:
ShouldNotReachHere();
}
log_develop_trace(gc, ref)("Thread %d gets list " INTPTR_FORMAT, id, p2i(list));
return list;
}
inline void
ReferenceProcessor::add_to_discovered_list_mt(DiscoveredList& refs_list,
oop obj,
HeapWord* discovered_addr) {
assert(_discovery_is_mt, "!_discovery_is_mt should have been handled by caller");
// First we must make sure this object is only enqueued once. CAS in a non null
// discovered_addr.
oop current_head = refs_list.head();
// The last ref must have its discovered field pointing to itself.
oop next_discovered = (current_head != NULL) ? current_head : obj;
oop retest = HeapAccess<AS_NO_KEEPALIVE>::oop_atomic_cmpxchg(discovered_addr, oop(NULL), next_discovered);
if (retest == NULL) {
// This thread just won the right to enqueue the object.
// We have separate lists for enqueueing, so no synchronization
// is necessary.
refs_list.set_head(obj);
refs_list.inc_length(1);
log_develop_trace(gc, ref)("Discovered reference (mt) (" INTPTR_FORMAT ": %s)",
p2i(obj), obj->klass()->internal_name());
} else {
// If retest was non NULL, another thread beat us to it:
// The reference has already been discovered...
log_develop_trace(gc, ref)("Already discovered reference (" INTPTR_FORMAT ": %s)",
p2i(obj), obj->klass()->internal_name());
}
}
#ifndef PRODUCT
// Non-atomic (i.e. concurrent) discovery might allow us
// to observe j.l.References with NULL referents, being those