1 /* 2 * Copyright (c) 2001, 2015, 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 "classfile/javaClasses.hpp" 27 #include "classfile/systemDictionary.hpp" 28 #include "gc/shared/collectedHeap.hpp" 29 #include "gc/shared/collectedHeap.inline.hpp" 30 #include "gc/shared/gcTimer.hpp" 31 #include "gc/shared/gcTraceTime.hpp" 32 #include "gc/shared/referencePolicy.hpp" 33 #include "gc/shared/referenceProcessor.hpp" 34 #include "oops/oop.inline.hpp" 35 #include "runtime/java.hpp" 36 #include "runtime/jniHandles.hpp" 37 38 ReferencePolicy* ReferenceProcessor::_always_clear_soft_ref_policy = NULL; 39 ReferencePolicy* ReferenceProcessor::_default_soft_ref_policy = NULL; 40 jlong ReferenceProcessor::_soft_ref_timestamp_clock = 0; 41 42 void referenceProcessor_init() { 43 ReferenceProcessor::init_statics(); 44 } 45 46 void ReferenceProcessor::init_statics() { 47 // We need a monotonically non-decreasing time in ms but 48 // os::javaTimeMillis() does not guarantee monotonicity. 49 jlong now = os::javaTimeNanos() / NANOSECS_PER_MILLISEC; 50 51 // Initialize the soft ref timestamp clock. 52 _soft_ref_timestamp_clock = now; 53 // Also update the soft ref clock in j.l.r.SoftReference 54 java_lang_ref_SoftReference::set_clock(_soft_ref_timestamp_clock); 55 56 _always_clear_soft_ref_policy = new AlwaysClearPolicy(); 57 _default_soft_ref_policy = new COMPILER2_PRESENT(LRUMaxHeapPolicy()) 58 NOT_COMPILER2(LRUCurrentHeapPolicy()); 59 if (_always_clear_soft_ref_policy == NULL || _default_soft_ref_policy == NULL) { 60 vm_exit_during_initialization("Could not allocate reference policy object"); 61 } 62 guarantee(RefDiscoveryPolicy == ReferenceBasedDiscovery || 63 RefDiscoveryPolicy == ReferentBasedDiscovery, 64 "Unrecognized RefDiscoveryPolicy"); 65 } 66 67 void ReferenceProcessor::enable_discovery(bool check_no_refs) { 68 #ifdef ASSERT 69 // Verify that we're not currently discovering refs 70 assert(!_discovering_refs, "nested call?"); 71 72 if (check_no_refs) { 73 // Verify that the discovered lists are empty 74 verify_no_references_recorded(); 75 } 76 #endif // ASSERT 77 78 // Someone could have modified the value of the static 79 // field in the j.l.r.SoftReference class that holds the 80 // soft reference timestamp clock using reflection or 81 // Unsafe between GCs. Unconditionally update the static 82 // field in ReferenceProcessor here so that we use the new 83 // value during reference discovery. 84 85 _soft_ref_timestamp_clock = java_lang_ref_SoftReference::clock(); 86 _discovering_refs = true; 87 } 88 89 ReferenceProcessor::ReferenceProcessor(MemRegion span, 90 bool mt_processing, 91 uint mt_processing_degree, 92 bool mt_discovery, 93 uint mt_discovery_degree, 94 bool atomic_discovery, 95 BoolObjectClosure* is_alive_non_header) : 96 _discovering_refs(false), 97 _enqueuing_is_done(false), 98 _is_alive_non_header(is_alive_non_header), 99 _processing_is_mt(mt_processing), 100 _next_id(0) 101 { 102 _span = span; 103 _discovery_is_atomic = atomic_discovery; 104 _discovery_is_mt = mt_discovery; 105 _num_q = MAX2(1U, mt_processing_degree); 106 _max_num_q = MAX2(_num_q, mt_discovery_degree); 107 _discovered_refs = NEW_C_HEAP_ARRAY(DiscoveredList, 108 _max_num_q * number_of_subclasses_of_ref(), mtGC); 109 110 if (_discovered_refs == NULL) { 111 vm_exit_during_initialization("Could not allocated RefProc Array"); 112 } 113 _discoveredSoftRefs = &_discovered_refs[0]; 114 _discoveredWeakRefs = &_discoveredSoftRefs[_max_num_q]; 115 _discoveredFinalRefs = &_discoveredWeakRefs[_max_num_q]; 116 _discoveredPhantomRefs = &_discoveredFinalRefs[_max_num_q]; 117 _discoveredCleanerRefs = &_discoveredPhantomRefs[_max_num_q]; 118 119 // Initialize all entries to NULL 120 for (uint i = 0; i < _max_num_q * number_of_subclasses_of_ref(); i++) { 121 _discovered_refs[i].set_head(NULL); 122 _discovered_refs[i].set_length(0); 123 } 124 125 setup_policy(false /* default soft ref policy */); 126 } 127 128 #ifndef PRODUCT 129 void ReferenceProcessor::verify_no_references_recorded() { 130 guarantee(!_discovering_refs, "Discovering refs?"); 131 for (uint i = 0; i < _max_num_q * number_of_subclasses_of_ref(); i++) { 132 guarantee(_discovered_refs[i].is_empty(), 133 "Found non-empty discovered list"); 134 } 135 } 136 #endif 137 138 void ReferenceProcessor::weak_oops_do(OopClosure* f) { 139 for (uint i = 0; i < _max_num_q * number_of_subclasses_of_ref(); i++) { 140 if (UseCompressedOops) { 141 f->do_oop((narrowOop*)_discovered_refs[i].adr_head()); 142 } else { 143 f->do_oop((oop*)_discovered_refs[i].adr_head()); 144 } 145 } 146 } 147 148 void ReferenceProcessor::update_soft_ref_master_clock() { 149 // Update (advance) the soft ref master clock field. This must be done 150 // after processing the soft ref list. 151 152 // We need a monotonically non-decreasing time in ms but 153 // os::javaTimeMillis() does not guarantee monotonicity. 154 jlong now = os::javaTimeNanos() / NANOSECS_PER_MILLISEC; 155 jlong soft_ref_clock = java_lang_ref_SoftReference::clock(); 156 assert(soft_ref_clock == _soft_ref_timestamp_clock, "soft ref clocks out of sync"); 157 158 NOT_PRODUCT( 159 if (now < _soft_ref_timestamp_clock) { 160 warning("time warp: " JLONG_FORMAT " to " JLONG_FORMAT, 161 _soft_ref_timestamp_clock, now); 162 } 163 ) 164 // The values of now and _soft_ref_timestamp_clock are set using 165 // javaTimeNanos(), which is guaranteed to be monotonically 166 // non-decreasing provided the underlying platform provides such 167 // a time source (and it is bug free). 168 // In product mode, however, protect ourselves from non-monotonicity. 169 if (now > _soft_ref_timestamp_clock) { 170 _soft_ref_timestamp_clock = now; 171 java_lang_ref_SoftReference::set_clock(now); 172 } 173 // Else leave clock stalled at its old value until time progresses 174 // past clock value. 175 } 176 177 size_t ReferenceProcessor::total_count(DiscoveredList lists[]) { 178 size_t total = 0; 179 for (uint i = 0; i < _max_num_q; ++i) { 180 total += lists[i].length(); 181 } 182 return total; 183 } 184 185 ReferenceProcessorStats ReferenceProcessor::process_discovered_references( 186 BoolObjectClosure* is_alive, 187 OopClosure* keep_alive, 188 VoidClosure* complete_gc, 189 AbstractRefProcTaskExecutor* task_executor, 190 GCTimer* gc_timer, 191 GCId gc_id) { 192 193 assert(!enqueuing_is_done(), "If here enqueuing should not be complete"); 194 // Stop treating discovered references specially. 195 disable_discovery(); 196 197 // If discovery was concurrent, someone could have modified 198 // the value of the static field in the j.l.r.SoftReference 199 // class that holds the soft reference timestamp clock using 200 // reflection or Unsafe between when discovery was enabled and 201 // now. Unconditionally update the static field in ReferenceProcessor 202 // here so that we use the new value during processing of the 203 // discovered soft refs. 204 205 _soft_ref_timestamp_clock = java_lang_ref_SoftReference::clock(); 206 207 bool trace_time = PrintGCDetails && PrintReferenceGC; 208 209 // Soft references 210 size_t soft_count = 0; 211 { 212 GCTraceTime tt("SoftReference", trace_time, false, gc_timer, gc_id); 213 soft_count = 214 process_discovered_reflist(_discoveredSoftRefs, _current_soft_ref_policy, true, 215 is_alive, keep_alive, complete_gc, task_executor); 216 } 217 218 update_soft_ref_master_clock(); 219 220 // Weak references 221 size_t weak_count = 0; 222 { 223 GCTraceTime tt("WeakReference", trace_time, false, gc_timer, gc_id); 224 weak_count = 225 process_discovered_reflist(_discoveredWeakRefs, NULL, true, 226 is_alive, keep_alive, complete_gc, task_executor); 227 } 228 229 // Final references 230 size_t final_count = 0; 231 { 232 GCTraceTime tt("FinalReference", trace_time, false, gc_timer, gc_id); 233 final_count = 234 process_discovered_reflist(_discoveredFinalRefs, NULL, false, 235 is_alive, keep_alive, complete_gc, task_executor); 236 } 237 238 // Phantom references 239 size_t phantom_count = 0; 240 { 241 GCTraceTime tt("PhantomReference", trace_time, false, gc_timer, gc_id); 242 phantom_count = 243 process_discovered_reflist(_discoveredPhantomRefs, NULL, false, 244 is_alive, keep_alive, complete_gc, task_executor); 245 246 } 247 248 // Cleaners 249 size_t cleaner_count = 0; 250 { 251 GCTraceTime tt("Cleaners", trace_time, false, gc_timer, gc_id); 252 cleaner_count = 253 process_discovered_reflist(_discoveredCleanerRefs, NULL, true, 254 is_alive, keep_alive, complete_gc, task_executor); 255 } 256 257 // Weak global JNI references. It would make more sense (semantically) to 258 // traverse these simultaneously with the regular weak references above, but 259 // that is not how the JDK1.2 specification is. See #4126360. Native code can 260 // thus use JNI weak references to circumvent the phantom references and 261 // resurrect a "post-mortem" object. 262 size_t jni_weak_ref_count = 0; 263 { 264 GCTraceTime tt("JNI Weak Reference", trace_time, false, gc_timer, gc_id); 265 if (task_executor != NULL) { 266 task_executor->set_single_threaded_mode(); 267 } 268 jni_weak_ref_count = 269 process_phaseJNI(is_alive, keep_alive, complete_gc); 270 } 271 272 return ReferenceProcessorStats(soft_count, weak_count, final_count, phantom_count, cleaner_count, jni_weak_ref_count); 273 } 274 275 #ifndef PRODUCT 276 // Calculate the number of jni handles. 277 uint ReferenceProcessor::count_jni_refs() { 278 class AlwaysAliveClosure: public BoolObjectClosure { 279 public: 280 virtual bool do_object_b(oop obj) { return true; } 281 }; 282 283 class CountHandleClosure: public OopClosure { 284 private: 285 int _count; 286 public: 287 CountHandleClosure(): _count(0) {} 288 void do_oop(oop* unused) { _count++; } 289 void do_oop(narrowOop* unused) { ShouldNotReachHere(); } 290 int count() { return _count; } 291 }; 292 CountHandleClosure global_handle_count; 293 AlwaysAliveClosure always_alive; 294 JNIHandles::weak_oops_do(&always_alive, &global_handle_count); 295 return global_handle_count.count(); 296 } 297 #endif 298 299 size_t ReferenceProcessor::process_phaseJNI(BoolObjectClosure* is_alive, 300 OopClosure* keep_alive, 301 VoidClosure* complete_gc) { 302 DEBUG_ONLY(size_t check_count = count_jni_refs();) 303 size_t count = JNIHandles::weak_oops_do(is_alive, keep_alive); 304 assert(count == check_count, "Counts didn't match"); 305 complete_gc->do_void(); 306 if (PrintGCDetails && PrintReferenceGC) { 307 gclog_or_tty->print(", " SIZE_FORMAT " refs", count); 308 } 309 return count; 310 } 311 312 313 template <class T> 314 bool enqueue_discovered_ref_helper(ReferenceProcessor* ref, 315 AbstractRefProcTaskExecutor* task_executor) { 316 317 // Remember old value of pending references list 318 T* pending_list_addr = (T*)java_lang_ref_Reference::pending_list_addr(); 319 T old_pending_list_value = *pending_list_addr; 320 321 // Enqueue references that are not made active again, and 322 // clear the decks for the next collection (cycle). 323 ref->enqueue_discovered_reflists((HeapWord*)pending_list_addr, task_executor); 324 // Do the post-barrier on pending_list_addr missed in 325 // enqueue_discovered_reflist. 326 oopDesc::bs()->write_ref_field(pending_list_addr, oopDesc::load_decode_heap_oop(pending_list_addr)); 327 328 // Stop treating discovered references specially. 329 ref->disable_discovery(); 330 331 // Return true if new pending references were added 332 return old_pending_list_value != *pending_list_addr; 333 } 334 335 bool ReferenceProcessor::enqueue_discovered_references(AbstractRefProcTaskExecutor* task_executor) { 336 if (UseCompressedOops) { 337 return enqueue_discovered_ref_helper<narrowOop>(this, task_executor); 338 } else { 339 return enqueue_discovered_ref_helper<oop>(this, task_executor); 340 } 341 } 342 343 void ReferenceProcessor::enqueue_discovered_reflist(DiscoveredList& refs_list, 344 HeapWord* pending_list_addr) { 345 // Given a list of refs linked through the "discovered" field 346 // (java.lang.ref.Reference.discovered), self-loop their "next" field 347 // thus distinguishing them from active References, then 348 // prepend them to the pending list. 349 // 350 // The Java threads will see the Reference objects linked together through 351 // the discovered field. Instead of trying to do the write barrier updates 352 // in all places in the reference processor where we manipulate the discovered 353 // field we make sure to do the barrier here where we anyway iterate through 354 // all linked Reference objects. Note that it is important to not dirty any 355 // cards during reference processing since this will cause card table 356 // verification to fail for G1. 357 if (TraceReferenceGC && PrintGCDetails) { 358 gclog_or_tty->print_cr("ReferenceProcessor::enqueue_discovered_reflist list " 359 INTPTR_FORMAT, p2i(refs_list.head())); 360 } 361 362 oop obj = NULL; 363 oop next_d = refs_list.head(); 364 // Walk down the list, self-looping the next field 365 // so that the References are not considered active. 366 while (obj != next_d) { 367 obj = next_d; 368 assert(obj->is_instanceRef(), "should be reference object"); 369 next_d = java_lang_ref_Reference::discovered(obj); 370 if (TraceReferenceGC && PrintGCDetails) { 371 gclog_or_tty->print_cr(" obj " INTPTR_FORMAT "/next_d " INTPTR_FORMAT, 372 p2i(obj), p2i(next_d)); 373 } 374 assert(java_lang_ref_Reference::next(obj) == NULL, 375 "Reference not active; should not be discovered"); 376 // Self-loop next, so as to make Ref not active. 377 java_lang_ref_Reference::set_next_raw(obj, obj); 378 if (next_d != obj) { 379 oopDesc::bs()->write_ref_field(java_lang_ref_Reference::discovered_addr(obj), next_d); 380 } else { 381 // This is the last object. 382 // Swap refs_list into pending_list_addr and 383 // set obj's discovered to what we read from pending_list_addr. 384 oop old = oopDesc::atomic_exchange_oop(refs_list.head(), pending_list_addr); 385 // Need post-barrier on pending_list_addr. See enqueue_discovered_ref_helper() above. 386 java_lang_ref_Reference::set_discovered_raw(obj, old); // old may be NULL 387 oopDesc::bs()->write_ref_field(java_lang_ref_Reference::discovered_addr(obj), old); 388 } 389 } 390 } 391 392 // Parallel enqueue task 393 class RefProcEnqueueTask: public AbstractRefProcTaskExecutor::EnqueueTask { 394 public: 395 RefProcEnqueueTask(ReferenceProcessor& ref_processor, 396 DiscoveredList discovered_refs[], 397 HeapWord* pending_list_addr, 398 int n_queues) 399 : EnqueueTask(ref_processor, discovered_refs, 400 pending_list_addr, n_queues) 401 { } 402 403 virtual void work(unsigned int work_id) { 404 assert(work_id < (unsigned int)_ref_processor.max_num_q(), "Index out-of-bounds"); 405 // Simplest first cut: static partitioning. 406 int index = work_id; 407 // The increment on "index" must correspond to the maximum number of queues 408 // (n_queues) with which that ReferenceProcessor was created. That 409 // is because of the "clever" way the discovered references lists were 410 // allocated and are indexed into. 411 assert(_n_queues == (int) _ref_processor.max_num_q(), "Different number not expected"); 412 for (int j = 0; 413 j < ReferenceProcessor::number_of_subclasses_of_ref(); 414 j++, index += _n_queues) { 415 _ref_processor.enqueue_discovered_reflist( 416 _refs_lists[index], _pending_list_addr); 417 _refs_lists[index].set_head(NULL); 418 _refs_lists[index].set_length(0); 419 } 420 } 421 }; 422 423 // Enqueue references that are not made active again 424 void ReferenceProcessor::enqueue_discovered_reflists(HeapWord* pending_list_addr, 425 AbstractRefProcTaskExecutor* task_executor) { 426 if (_processing_is_mt && task_executor != NULL) { 427 // Parallel code 428 RefProcEnqueueTask tsk(*this, _discovered_refs, 429 pending_list_addr, _max_num_q); 430 task_executor->execute(tsk); 431 } else { 432 // Serial code: call the parent class's implementation 433 for (uint i = 0; i < _max_num_q * number_of_subclasses_of_ref(); i++) { 434 enqueue_discovered_reflist(_discovered_refs[i], pending_list_addr); 435 _discovered_refs[i].set_head(NULL); 436 _discovered_refs[i].set_length(0); 437 } 438 } 439 } 440 441 void DiscoveredListIterator::load_ptrs(DEBUG_ONLY(bool allow_null_referent)) { 442 _discovered_addr = java_lang_ref_Reference::discovered_addr(_ref); 443 oop discovered = java_lang_ref_Reference::discovered(_ref); 444 assert(_discovered_addr && discovered->is_oop_or_null(), 445 err_msg("Expected an oop or NULL for discovered field at " PTR_FORMAT, p2i(discovered))); 446 _next = discovered; 447 _referent_addr = java_lang_ref_Reference::referent_addr(_ref); 448 _referent = java_lang_ref_Reference::referent(_ref); 449 assert(Universe::heap()->is_in_reserved_or_null(_referent), 450 "Wrong oop found in java.lang.Reference object"); 451 assert(allow_null_referent ? 452 _referent->is_oop_or_null() 453 : _referent->is_oop(), 454 err_msg("Expected an oop%s for referent field at " PTR_FORMAT, 455 (allow_null_referent ? " or NULL" : ""), 456 p2i(_referent))); 457 } 458 459 void DiscoveredListIterator::remove() { 460 assert(_ref->is_oop(), "Dropping a bad reference"); 461 oop_store_raw(_discovered_addr, NULL); 462 463 // First _prev_next ref actually points into DiscoveredList (gross). 464 oop new_next; 465 if (_next == _ref) { 466 // At the end of the list, we should make _prev point to itself. 467 // If _ref is the first ref, then _prev_next will be in the DiscoveredList, 468 // and _prev will be NULL. 469 new_next = _prev; 470 } else { 471 new_next = _next; 472 } 473 // Remove Reference object from discovered list. Note that G1 does not need a 474 // pre-barrier here because we know the Reference has already been found/marked, 475 // that's how it ended up in the discovered list in the first place. 476 oop_store_raw(_prev_next, new_next); 477 NOT_PRODUCT(_removed++); 478 _refs_list.dec_length(1); 479 } 480 481 void DiscoveredListIterator::clear_referent() { 482 oop_store_raw(_referent_addr, NULL); 483 } 484 485 // NOTE: process_phase*() are largely similar, and at a high level 486 // merely iterate over the extant list applying a predicate to 487 // each of its elements and possibly removing that element from the 488 // list and applying some further closures to that element. 489 // We should consider the possibility of replacing these 490 // process_phase*() methods by abstracting them into 491 // a single general iterator invocation that receives appropriate 492 // closures that accomplish this work. 493 494 // (SoftReferences only) Traverse the list and remove any SoftReferences whose 495 // referents are not alive, but that should be kept alive for policy reasons. 496 // Keep alive the transitive closure of all such referents. 497 void 498 ReferenceProcessor::process_phase1(DiscoveredList& refs_list, 499 ReferencePolicy* policy, 500 BoolObjectClosure* is_alive, 501 OopClosure* keep_alive, 502 VoidClosure* complete_gc) { 503 assert(policy != NULL, "Must have a non-NULL policy"); 504 DiscoveredListIterator iter(refs_list, keep_alive, is_alive); 505 // Decide which softly reachable refs should be kept alive. 506 while (iter.has_next()) { 507 iter.load_ptrs(DEBUG_ONLY(!discovery_is_atomic() /* allow_null_referent */)); 508 bool referent_is_dead = (iter.referent() != NULL) && !iter.is_referent_alive(); 509 if (referent_is_dead && 510 !policy->should_clear_reference(iter.obj(), _soft_ref_timestamp_clock)) { 511 if (TraceReferenceGC) { 512 gclog_or_tty->print_cr("Dropping reference (" INTPTR_FORMAT ": %s" ") by policy", 513 p2i(iter.obj()), iter.obj()->klass()->internal_name()); 514 } 515 // Remove Reference object from list 516 iter.remove(); 517 // keep the referent around 518 iter.make_referent_alive(); 519 iter.move_to_next(); 520 } else { 521 iter.next(); 522 } 523 } 524 // Close the reachable set 525 complete_gc->do_void(); 526 NOT_PRODUCT( 527 if (PrintGCDetails && TraceReferenceGC) { 528 gclog_or_tty->print_cr(" Dropped " SIZE_FORMAT " dead Refs out of " SIZE_FORMAT 529 " discovered Refs by policy, from list " INTPTR_FORMAT, 530 iter.removed(), iter.processed(), p2i(refs_list.head())); 531 } 532 ) 533 } 534 535 // Traverse the list and remove any Refs that are not active, or 536 // whose referents are either alive or NULL. 537 void 538 ReferenceProcessor::pp2_work(DiscoveredList& refs_list, 539 BoolObjectClosure* is_alive, 540 OopClosure* keep_alive) { 541 assert(discovery_is_atomic(), "Error"); 542 DiscoveredListIterator iter(refs_list, keep_alive, is_alive); 543 while (iter.has_next()) { 544 iter.load_ptrs(DEBUG_ONLY(false /* allow_null_referent */)); 545 DEBUG_ONLY(oop next = java_lang_ref_Reference::next(iter.obj());) 546 assert(next == NULL, "Should not discover inactive Reference"); 547 if (iter.is_referent_alive()) { 548 if (TraceReferenceGC) { 549 gclog_or_tty->print_cr("Dropping strongly reachable reference (" INTPTR_FORMAT ": %s)", 550 p2i(iter.obj()), iter.obj()->klass()->internal_name()); 551 } 552 // The referent is reachable after all. 553 // Remove Reference object from list. 554 iter.remove(); 555 // Update the referent pointer as necessary: Note that this 556 // should not entail any recursive marking because the 557 // referent must already have been traversed. 558 iter.make_referent_alive(); 559 iter.move_to_next(); 560 } else { 561 iter.next(); 562 } 563 } 564 NOT_PRODUCT( 565 if (PrintGCDetails && TraceReferenceGC && (iter.processed() > 0)) { 566 gclog_or_tty->print_cr(" Dropped " SIZE_FORMAT " active Refs out of " SIZE_FORMAT 567 " Refs in discovered list " INTPTR_FORMAT, 568 iter.removed(), iter.processed(), p2i(refs_list.head())); 569 } 570 ) 571 } 572 573 void 574 ReferenceProcessor::pp2_work_concurrent_discovery(DiscoveredList& refs_list, 575 BoolObjectClosure* is_alive, 576 OopClosure* keep_alive, 577 VoidClosure* complete_gc) { 578 assert(!discovery_is_atomic(), "Error"); 579 DiscoveredListIterator iter(refs_list, keep_alive, is_alive); 580 while (iter.has_next()) { 581 iter.load_ptrs(DEBUG_ONLY(true /* allow_null_referent */)); 582 HeapWord* next_addr = java_lang_ref_Reference::next_addr(iter.obj()); 583 oop next = java_lang_ref_Reference::next(iter.obj()); 584 if ((iter.referent() == NULL || iter.is_referent_alive() || 585 next != NULL)) { 586 assert(next->is_oop_or_null(), err_msg("Expected an oop or NULL for next field at " PTR_FORMAT, p2i(next))); 587 // Remove Reference object from list 588 iter.remove(); 589 // Trace the cohorts 590 iter.make_referent_alive(); 591 if (UseCompressedOops) { 592 keep_alive->do_oop((narrowOop*)next_addr); 593 } else { 594 keep_alive->do_oop((oop*)next_addr); 595 } 596 iter.move_to_next(); 597 } else { 598 iter.next(); 599 } 600 } 601 // Now close the newly reachable set 602 complete_gc->do_void(); 603 NOT_PRODUCT( 604 if (PrintGCDetails && TraceReferenceGC && (iter.processed() > 0)) { 605 gclog_or_tty->print_cr(" Dropped " SIZE_FORMAT " active Refs out of " SIZE_FORMAT 606 " Refs in discovered list " INTPTR_FORMAT, 607 iter.removed(), iter.processed(), p2i(refs_list.head())); 608 } 609 ) 610 } 611 612 // Traverse the list and process the referents, by either 613 // clearing them or keeping them (and their reachable 614 // closure) alive. 615 void 616 ReferenceProcessor::process_phase3(DiscoveredList& refs_list, 617 bool clear_referent, 618 BoolObjectClosure* is_alive, 619 OopClosure* keep_alive, 620 VoidClosure* complete_gc) { 621 ResourceMark rm; 622 DiscoveredListIterator iter(refs_list, keep_alive, is_alive); 623 while (iter.has_next()) { 624 iter.load_ptrs(DEBUG_ONLY(false /* allow_null_referent */)); 625 if (clear_referent) { 626 // NULL out referent pointer 627 iter.clear_referent(); 628 } else { 629 // keep the referent around 630 iter.make_referent_alive(); 631 } 632 if (TraceReferenceGC) { 633 gclog_or_tty->print_cr("Adding %sreference (" INTPTR_FORMAT ": %s) as pending", 634 clear_referent ? "cleared " : "", 635 p2i(iter.obj()), iter.obj()->klass()->internal_name()); 636 } 637 assert(iter.obj()->is_oop(UseConcMarkSweepGC), "Adding a bad reference"); 638 iter.next(); 639 } 640 // Close the reachable set 641 complete_gc->do_void(); 642 } 643 644 void 645 ReferenceProcessor::clear_discovered_references(DiscoveredList& refs_list) { 646 oop obj = NULL; 647 oop next = refs_list.head(); 648 while (next != obj) { 649 obj = next; 650 next = java_lang_ref_Reference::discovered(obj); 651 java_lang_ref_Reference::set_discovered_raw(obj, NULL); 652 } 653 refs_list.set_head(NULL); 654 refs_list.set_length(0); 655 } 656 657 void ReferenceProcessor::abandon_partial_discovery() { 658 // loop over the lists 659 for (uint i = 0; i < _max_num_q * number_of_subclasses_of_ref(); i++) { 660 if (TraceReferenceGC && PrintGCDetails && ((i % _max_num_q) == 0)) { 661 gclog_or_tty->print_cr("\nAbandoning %s discovered list", list_name(i)); 662 } 663 clear_discovered_references(_discovered_refs[i]); 664 } 665 } 666 667 class RefProcPhase1Task: public AbstractRefProcTaskExecutor::ProcessTask { 668 public: 669 RefProcPhase1Task(ReferenceProcessor& ref_processor, 670 DiscoveredList refs_lists[], 671 ReferencePolicy* policy, 672 bool marks_oops_alive) 673 : ProcessTask(ref_processor, refs_lists, marks_oops_alive), 674 _policy(policy) 675 { } 676 virtual void work(unsigned int i, BoolObjectClosure& is_alive, 677 OopClosure& keep_alive, 678 VoidClosure& complete_gc) 679 { 680 Thread* thr = Thread::current(); 681 int refs_list_index = ((WorkerThread*)thr)->id(); 682 _ref_processor.process_phase1(_refs_lists[refs_list_index], _policy, 683 &is_alive, &keep_alive, &complete_gc); 684 } 685 private: 686 ReferencePolicy* _policy; 687 }; 688 689 class RefProcPhase2Task: public AbstractRefProcTaskExecutor::ProcessTask { 690 public: 691 RefProcPhase2Task(ReferenceProcessor& ref_processor, 692 DiscoveredList refs_lists[], 693 bool marks_oops_alive) 694 : ProcessTask(ref_processor, refs_lists, marks_oops_alive) 695 { } 696 virtual void work(unsigned int i, BoolObjectClosure& is_alive, 697 OopClosure& keep_alive, 698 VoidClosure& complete_gc) 699 { 700 _ref_processor.process_phase2(_refs_lists[i], 701 &is_alive, &keep_alive, &complete_gc); 702 } 703 }; 704 705 class RefProcPhase3Task: public AbstractRefProcTaskExecutor::ProcessTask { 706 public: 707 RefProcPhase3Task(ReferenceProcessor& ref_processor, 708 DiscoveredList refs_lists[], 709 bool clear_referent, 710 bool marks_oops_alive) 711 : ProcessTask(ref_processor, refs_lists, marks_oops_alive), 712 _clear_referent(clear_referent) 713 { } 714 virtual void work(unsigned int i, BoolObjectClosure& is_alive, 715 OopClosure& keep_alive, 716 VoidClosure& complete_gc) 717 { 718 // Don't use "refs_list_index" calculated in this way because 719 // balance_queues() has moved the Ref's into the first n queues. 720 // Thread* thr = Thread::current(); 721 // int refs_list_index = ((WorkerThread*)thr)->id(); 722 // _ref_processor.process_phase3(_refs_lists[refs_list_index], _clear_referent, 723 _ref_processor.process_phase3(_refs_lists[i], _clear_referent, 724 &is_alive, &keep_alive, &complete_gc); 725 } 726 private: 727 bool _clear_referent; 728 }; 729 730 // Balances reference queues. 731 // Move entries from all queues[0, 1, ..., _max_num_q-1] to 732 // queues[0, 1, ..., _num_q-1] because only the first _num_q 733 // corresponding to the active workers will be processed. 734 void ReferenceProcessor::balance_queues(DiscoveredList ref_lists[]) 735 { 736 // calculate total length 737 size_t total_refs = 0; 738 if (TraceReferenceGC && PrintGCDetails) { 739 gclog_or_tty->print_cr("\nBalance ref_lists "); 740 } 741 742 for (uint i = 0; i < _max_num_q; ++i) { 743 total_refs += ref_lists[i].length(); 744 if (TraceReferenceGC && PrintGCDetails) { 745 gclog_or_tty->print(SIZE_FORMAT " ", ref_lists[i].length()); 746 } 747 } 748 if (TraceReferenceGC && PrintGCDetails) { 749 gclog_or_tty->print_cr(" = " SIZE_FORMAT, total_refs); 750 } 751 size_t avg_refs = total_refs / _num_q + 1; 752 uint to_idx = 0; 753 for (uint from_idx = 0; from_idx < _max_num_q; from_idx++) { 754 bool move_all = false; 755 if (from_idx >= _num_q) { 756 move_all = ref_lists[from_idx].length() > 0; 757 } 758 while ((ref_lists[from_idx].length() > avg_refs) || 759 move_all) { 760 assert(to_idx < _num_q, "Sanity Check!"); 761 if (ref_lists[to_idx].length() < avg_refs) { 762 // move superfluous refs 763 size_t refs_to_move; 764 // Move all the Ref's if the from queue will not be processed. 765 if (move_all) { 766 refs_to_move = MIN2(ref_lists[from_idx].length(), 767 avg_refs - ref_lists[to_idx].length()); 768 } else { 769 refs_to_move = MIN2(ref_lists[from_idx].length() - avg_refs, 770 avg_refs - ref_lists[to_idx].length()); 771 } 772 773 assert(refs_to_move > 0, "otherwise the code below will fail"); 774 775 oop move_head = ref_lists[from_idx].head(); 776 oop move_tail = move_head; 777 oop new_head = move_head; 778 // find an element to split the list on 779 for (size_t j = 0; j < refs_to_move; ++j) { 780 move_tail = new_head; 781 new_head = java_lang_ref_Reference::discovered(new_head); 782 } 783 784 // Add the chain to the to list. 785 if (ref_lists[to_idx].head() == NULL) { 786 // to list is empty. Make a loop at the end. 787 java_lang_ref_Reference::set_discovered_raw(move_tail, move_tail); 788 } else { 789 java_lang_ref_Reference::set_discovered_raw(move_tail, ref_lists[to_idx].head()); 790 } 791 ref_lists[to_idx].set_head(move_head); 792 ref_lists[to_idx].inc_length(refs_to_move); 793 794 // Remove the chain from the from list. 795 if (move_tail == new_head) { 796 // We found the end of the from list. 797 ref_lists[from_idx].set_head(NULL); 798 } else { 799 ref_lists[from_idx].set_head(new_head); 800 } 801 ref_lists[from_idx].dec_length(refs_to_move); 802 if (ref_lists[from_idx].length() == 0) { 803 break; 804 } 805 } else { 806 to_idx = (to_idx + 1) % _num_q; 807 } 808 } 809 } 810 #ifdef ASSERT 811 size_t balanced_total_refs = 0; 812 for (uint i = 0; i < _max_num_q; ++i) { 813 balanced_total_refs += ref_lists[i].length(); 814 if (TraceReferenceGC && PrintGCDetails) { 815 gclog_or_tty->print(SIZE_FORMAT " ", ref_lists[i].length()); 816 } 817 } 818 if (TraceReferenceGC && PrintGCDetails) { 819 gclog_or_tty->print_cr(" = " SIZE_FORMAT, balanced_total_refs); 820 gclog_or_tty->flush(); 821 } 822 assert(total_refs == balanced_total_refs, "Balancing was incomplete"); 823 #endif 824 } 825 826 void ReferenceProcessor::balance_all_queues() { 827 balance_queues(_discoveredSoftRefs); 828 balance_queues(_discoveredWeakRefs); 829 balance_queues(_discoveredFinalRefs); 830 balance_queues(_discoveredPhantomRefs); 831 balance_queues(_discoveredCleanerRefs); 832 } 833 834 size_t 835 ReferenceProcessor::process_discovered_reflist( 836 DiscoveredList refs_lists[], 837 ReferencePolicy* policy, 838 bool clear_referent, 839 BoolObjectClosure* is_alive, 840 OopClosure* keep_alive, 841 VoidClosure* complete_gc, 842 AbstractRefProcTaskExecutor* task_executor) 843 { 844 bool mt_processing = task_executor != NULL && _processing_is_mt; 845 // If discovery used MT and a dynamic number of GC threads, then 846 // the queues must be balanced for correctness if fewer than the 847 // maximum number of queues were used. The number of queue used 848 // during discovery may be different than the number to be used 849 // for processing so don't depend of _num_q < _max_num_q as part 850 // of the test. 851 bool must_balance = _discovery_is_mt; 852 853 if ((mt_processing && ParallelRefProcBalancingEnabled) || 854 must_balance) { 855 balance_queues(refs_lists); 856 } 857 858 size_t total_list_count = total_count(refs_lists); 859 860 if (PrintReferenceGC && PrintGCDetails) { 861 gclog_or_tty->print(", " SIZE_FORMAT " refs", total_list_count); 862 } 863 864 // Phase 1 (soft refs only): 865 // . Traverse the list and remove any SoftReferences whose 866 // referents are not alive, but that should be kept alive for 867 // policy reasons. Keep alive the transitive closure of all 868 // such referents. 869 if (policy != NULL) { 870 if (mt_processing) { 871 RefProcPhase1Task phase1(*this, refs_lists, policy, true /*marks_oops_alive*/); 872 task_executor->execute(phase1); 873 } else { 874 for (uint i = 0; i < _max_num_q; i++) { 875 process_phase1(refs_lists[i], policy, 876 is_alive, keep_alive, complete_gc); 877 } 878 } 879 } else { // policy == NULL 880 assert(refs_lists != _discoveredSoftRefs, 881 "Policy must be specified for soft references."); 882 } 883 884 // Phase 2: 885 // . Traverse the list and remove any refs whose referents are alive. 886 if (mt_processing) { 887 RefProcPhase2Task phase2(*this, refs_lists, !discovery_is_atomic() /*marks_oops_alive*/); 888 task_executor->execute(phase2); 889 } else { 890 for (uint i = 0; i < _max_num_q; i++) { 891 process_phase2(refs_lists[i], is_alive, keep_alive, complete_gc); 892 } 893 } 894 895 // Phase 3: 896 // . Traverse the list and process referents as appropriate. 897 if (mt_processing) { 898 RefProcPhase3Task phase3(*this, refs_lists, clear_referent, true /*marks_oops_alive*/); 899 task_executor->execute(phase3); 900 } else { 901 for (uint i = 0; i < _max_num_q; i++) { 902 process_phase3(refs_lists[i], clear_referent, 903 is_alive, keep_alive, complete_gc); 904 } 905 } 906 907 return total_list_count; 908 } 909 910 inline DiscoveredList* ReferenceProcessor::get_discovered_list(ReferenceType rt) { 911 uint id = 0; 912 // Determine the queue index to use for this object. 913 if (_discovery_is_mt) { 914 // During a multi-threaded discovery phase, 915 // each thread saves to its "own" list. 916 Thread* thr = Thread::current(); 917 id = thr->as_Worker_thread()->id(); 918 } else { 919 // single-threaded discovery, we save in round-robin 920 // fashion to each of the lists. 921 if (_processing_is_mt) { 922 id = next_id(); 923 } 924 } 925 assert(id < _max_num_q, "Id is out-of-bounds (call Freud?)"); 926 927 // Get the discovered queue to which we will add 928 DiscoveredList* list = NULL; 929 switch (rt) { 930 case REF_OTHER: 931 // Unknown reference type, no special treatment 932 break; 933 case REF_SOFT: 934 list = &_discoveredSoftRefs[id]; 935 break; 936 case REF_WEAK: 937 list = &_discoveredWeakRefs[id]; 938 break; 939 case REF_FINAL: 940 list = &_discoveredFinalRefs[id]; 941 break; 942 case REF_PHANTOM: 943 list = &_discoveredPhantomRefs[id]; 944 break; 945 case REF_CLEANER: 946 list = &_discoveredCleanerRefs[id]; 947 break; 948 case REF_NONE: 949 case REF_JNI: 950 // we should not reach here if we are an InstanceRefKlass 951 default: 952 guarantee(false, err_msg("rt should not be %d", rt)); 953 } 954 if (TraceReferenceGC && PrintGCDetails) { 955 gclog_or_tty->print_cr("Thread %d gets list " INTPTR_FORMAT, id, p2i(list)); 956 } 957 return list; 958 } 959 960 inline void 961 ReferenceProcessor::add_to_discovered_list_mt(DiscoveredList& refs_list, 962 oop obj, 963 HeapWord* discovered_addr) { 964 assert(_discovery_is_mt, "!_discovery_is_mt should have been handled by caller"); 965 // First we must make sure this object is only enqueued once. CAS in a non null 966 // discovered_addr. 967 oop current_head = refs_list.head(); 968 // The last ref must have its discovered field pointing to itself. 969 oop next_discovered = (current_head != NULL) ? current_head : obj; 970 971 oop retest = oopDesc::atomic_compare_exchange_oop(next_discovered, discovered_addr, 972 NULL); 973 if (retest == NULL) { 974 // This thread just won the right to enqueue the object. 975 // We have separate lists for enqueueing, so no synchronization 976 // is necessary. 977 refs_list.set_head(obj); 978 refs_list.inc_length(1); 979 980 if (TraceReferenceGC) { 981 gclog_or_tty->print_cr("Discovered reference (mt) (" INTPTR_FORMAT ": %s)", 982 p2i(obj), obj->klass()->internal_name()); 983 } 984 } else { 985 // If retest was non NULL, another thread beat us to it: 986 // The reference has already been discovered... 987 if (TraceReferenceGC) { 988 gclog_or_tty->print_cr("Already discovered reference (" INTPTR_FORMAT ": %s)", 989 p2i(obj), obj->klass()->internal_name()); 990 } 991 } 992 } 993 994 #ifndef PRODUCT 995 // Non-atomic (i.e. concurrent) discovery might allow us 996 // to observe j.l.References with NULL referents, being those 997 // cleared concurrently by mutators during (or after) discovery. 998 void ReferenceProcessor::verify_referent(oop obj) { 999 bool da = discovery_is_atomic(); 1000 oop referent = java_lang_ref_Reference::referent(obj); 1001 assert(da ? referent->is_oop() : referent->is_oop_or_null(), 1002 err_msg("Bad referent " INTPTR_FORMAT " found in Reference " 1003 INTPTR_FORMAT " during %satomic discovery ", 1004 p2i(referent), p2i(obj), da ? "" : "non-")); 1005 } 1006 #endif 1007 1008 // We mention two of several possible choices here: 1009 // #0: if the reference object is not in the "originating generation" 1010 // (or part of the heap being collected, indicated by our "span" 1011 // we don't treat it specially (i.e. we scan it as we would 1012 // a normal oop, treating its references as strong references). 1013 // This means that references can't be discovered unless their 1014 // referent is also in the same span. This is the simplest, 1015 // most "local" and most conservative approach, albeit one 1016 // that may cause weak references to be enqueued least promptly. 1017 // We call this choice the "ReferenceBasedDiscovery" policy. 1018 // #1: the reference object may be in any generation (span), but if 1019 // the referent is in the generation (span) being currently collected 1020 // then we can discover the reference object, provided 1021 // the object has not already been discovered by 1022 // a different concurrently running collector (as may be the 1023 // case, for instance, if the reference object is in CMS and 1024 // the referent in DefNewGeneration), and provided the processing 1025 // of this reference object by the current collector will 1026 // appear atomic to every other collector in the system. 1027 // (Thus, for instance, a concurrent collector may not 1028 // discover references in other generations even if the 1029 // referent is in its own generation). This policy may, 1030 // in certain cases, enqueue references somewhat sooner than 1031 // might Policy #0 above, but at marginally increased cost 1032 // and complexity in processing these references. 1033 // We call this choice the "RefeferentBasedDiscovery" policy. 1034 bool ReferenceProcessor::discover_reference(oop obj, ReferenceType rt) { 1035 // Make sure we are discovering refs (rather than processing discovered refs). 1036 if (!_discovering_refs || !RegisterReferences) { 1037 return false; 1038 } 1039 // We only discover active references. 1040 oop next = java_lang_ref_Reference::next(obj); 1041 if (next != NULL) { // Ref is no longer active 1042 return false; 1043 } 1044 1045 HeapWord* obj_addr = (HeapWord*)obj; 1046 if (RefDiscoveryPolicy == ReferenceBasedDiscovery && 1047 !_span.contains(obj_addr)) { 1048 // Reference is not in the originating generation; 1049 // don't treat it specially (i.e. we want to scan it as a normal 1050 // object with strong references). 1051 return false; 1052 } 1053 1054 // We only discover references whose referents are not (yet) 1055 // known to be strongly reachable. 1056 if (is_alive_non_header() != NULL) { 1057 verify_referent(obj); 1058 if (is_alive_non_header()->do_object_b(java_lang_ref_Reference::referent(obj))) { 1059 return false; // referent is reachable 1060 } 1061 } 1062 if (rt == REF_SOFT) { 1063 // For soft refs we can decide now if these are not 1064 // current candidates for clearing, in which case we 1065 // can mark through them now, rather than delaying that 1066 // to the reference-processing phase. Since all current 1067 // time-stamp policies advance the soft-ref clock only 1068 // at a full collection cycle, this is always currently 1069 // accurate. 1070 if (!_current_soft_ref_policy->should_clear_reference(obj, _soft_ref_timestamp_clock)) { 1071 return false; 1072 } 1073 } 1074 1075 ResourceMark rm; // Needed for tracing. 1076 1077 HeapWord* const discovered_addr = java_lang_ref_Reference::discovered_addr(obj); 1078 const oop discovered = java_lang_ref_Reference::discovered(obj); 1079 assert(discovered->is_oop_or_null(), err_msg("Expected an oop or NULL for discovered field at " PTR_FORMAT, p2i(discovered))); 1080 if (discovered != NULL) { 1081 // The reference has already been discovered... 1082 if (TraceReferenceGC) { 1083 gclog_or_tty->print_cr("Already discovered reference (" INTPTR_FORMAT ": %s)", 1084 p2i(obj), obj->klass()->internal_name()); 1085 } 1086 if (RefDiscoveryPolicy == ReferentBasedDiscovery) { 1087 // assumes that an object is not processed twice; 1088 // if it's been already discovered it must be on another 1089 // generation's discovered list; so we won't discover it. 1090 return false; 1091 } else { 1092 assert(RefDiscoveryPolicy == ReferenceBasedDiscovery, 1093 "Unrecognized policy"); 1094 // Check assumption that an object is not potentially 1095 // discovered twice except by concurrent collectors that potentially 1096 // trace the same Reference object twice. 1097 assert(UseConcMarkSweepGC || UseG1GC || UseShenandoahGC, 1098 "Only possible with a concurrent marking collector"); 1099 return true; 1100 } 1101 } 1102 1103 if (RefDiscoveryPolicy == ReferentBasedDiscovery) { 1104 verify_referent(obj); 1105 // Discover if and only if EITHER: 1106 // .. reference is in our span, OR 1107 // .. we are an atomic collector and referent is in our span 1108 if (_span.contains(obj_addr) || 1109 (discovery_is_atomic() && 1110 _span.contains(java_lang_ref_Reference::referent(obj)))) { 1111 // should_enqueue = true; 1112 } else { 1113 return false; 1114 } 1115 } else { 1116 assert(RefDiscoveryPolicy == ReferenceBasedDiscovery && 1117 _span.contains(obj_addr), "code inconsistency"); 1118 } 1119 1120 // Get the right type of discovered queue head. 1121 DiscoveredList* list = get_discovered_list(rt); 1122 if (list == NULL) { 1123 return false; // nothing special needs to be done 1124 } 1125 1126 if (_discovery_is_mt) { 1127 add_to_discovered_list_mt(*list, obj, discovered_addr); 1128 } else { 1129 // We do a raw store here: the field will be visited later when processing 1130 // the discovered references. 1131 oop current_head = list->head(); 1132 // The last ref must have its discovered field pointing to itself. 1133 oop next_discovered = (current_head != NULL) ? current_head : obj; 1134 1135 assert(discovered == NULL, "control point invariant"); 1136 oop_store_raw(discovered_addr, next_discovered); 1137 list->set_head(obj); 1138 list->inc_length(1); 1139 1140 if (TraceReferenceGC) { 1141 gclog_or_tty->print_cr("Discovered reference (" INTPTR_FORMAT ": %s)", 1142 p2i(obj), obj->klass()->internal_name()); 1143 } 1144 } 1145 assert(obj->is_oop(), "Discovered a bad reference"); 1146 verify_referent(obj); 1147 return true; 1148 } 1149 1150 // Preclean the discovered references by removing those 1151 // whose referents are alive, and by marking from those that 1152 // are not active. These lists can be handled here 1153 // in any order and, indeed, concurrently. 1154 void ReferenceProcessor::preclean_discovered_references( 1155 BoolObjectClosure* is_alive, 1156 OopClosure* keep_alive, 1157 VoidClosure* complete_gc, 1158 YieldClosure* yield, 1159 GCTimer* gc_timer, 1160 GCId gc_id) { 1161 1162 // Soft references 1163 { 1164 GCTraceTime tt("Preclean SoftReferences", PrintGCDetails && PrintReferenceGC, 1165 false, gc_timer, gc_id); 1166 for (uint i = 0; i < _max_num_q; i++) { 1167 if (yield->should_return()) { 1168 return; 1169 } 1170 preclean_discovered_reflist(_discoveredSoftRefs[i], is_alive, 1171 keep_alive, complete_gc, yield); 1172 } 1173 } 1174 1175 // Weak references 1176 { 1177 GCTraceTime tt("Preclean WeakReferences", PrintGCDetails && PrintReferenceGC, 1178 false, gc_timer, gc_id); 1179 for (uint i = 0; i < _max_num_q; i++) { 1180 if (yield->should_return()) { 1181 return; 1182 } 1183 preclean_discovered_reflist(_discoveredWeakRefs[i], is_alive, 1184 keep_alive, complete_gc, yield); 1185 } 1186 } 1187 1188 // Final references 1189 { 1190 GCTraceTime tt("Preclean FinalReferences", PrintGCDetails && PrintReferenceGC, 1191 false, gc_timer, gc_id); 1192 for (uint i = 0; i < _max_num_q; i++) { 1193 if (yield->should_return()) { 1194 return; 1195 } 1196 preclean_discovered_reflist(_discoveredFinalRefs[i], is_alive, 1197 keep_alive, complete_gc, yield); 1198 } 1199 } 1200 1201 // Phantom references 1202 { 1203 GCTraceTime tt("Preclean PhantomReferences", PrintGCDetails && PrintReferenceGC, 1204 false, gc_timer, gc_id); 1205 for (uint i = 0; i < _max_num_q; i++) { 1206 if (yield->should_return()) { 1207 return; 1208 } 1209 preclean_discovered_reflist(_discoveredPhantomRefs[i], is_alive, 1210 keep_alive, complete_gc, yield); 1211 } 1212 1213 // Cleaner references. Included in timing for phantom references. We 1214 // expect Cleaner references to be temporary, and don't want to deal with 1215 // possible incompatibilities arising from making it more visible. 1216 for (uint i = 0; i < _max_num_q; i++) { 1217 if (yield->should_return()) { 1218 return; 1219 } 1220 preclean_discovered_reflist(_discoveredCleanerRefs[i], is_alive, 1221 keep_alive, complete_gc, yield); 1222 } 1223 } 1224 } 1225 1226 // Walk the given discovered ref list, and remove all reference objects 1227 // whose referents are still alive, whose referents are NULL or which 1228 // are not active (have a non-NULL next field). NOTE: When we are 1229 // thus precleaning the ref lists (which happens single-threaded today), 1230 // we do not disable refs discovery to honor the correct semantics of 1231 // java.lang.Reference. As a result, we need to be careful below 1232 // that ref removal steps interleave safely with ref discovery steps 1233 // (in this thread). 1234 void 1235 ReferenceProcessor::preclean_discovered_reflist(DiscoveredList& refs_list, 1236 BoolObjectClosure* is_alive, 1237 OopClosure* keep_alive, 1238 VoidClosure* complete_gc, 1239 YieldClosure* yield) { 1240 DiscoveredListIterator iter(refs_list, keep_alive, is_alive); 1241 while (iter.has_next()) { 1242 iter.load_ptrs(DEBUG_ONLY(true /* allow_null_referent */)); 1243 oop obj = iter.obj(); 1244 oop next = java_lang_ref_Reference::next(obj); 1245 if (iter.referent() == NULL || iter.is_referent_alive() || 1246 next != NULL) { 1247 // The referent has been cleared, or is alive, or the Reference is not 1248 // active; we need to trace and mark its cohort. 1249 if (TraceReferenceGC) { 1250 gclog_or_tty->print_cr("Precleaning Reference (" INTPTR_FORMAT ": %s)", 1251 p2i(iter.obj()), iter.obj()->klass()->internal_name()); 1252 } 1253 // Remove Reference object from list 1254 iter.remove(); 1255 // Keep alive its cohort. 1256 iter.make_referent_alive(); 1257 if (UseCompressedOops) { 1258 narrowOop* next_addr = (narrowOop*)java_lang_ref_Reference::next_addr(obj); 1259 keep_alive->do_oop(next_addr); 1260 } else { 1261 oop* next_addr = (oop*)java_lang_ref_Reference::next_addr(obj); 1262 keep_alive->do_oop(next_addr); 1263 } 1264 iter.move_to_next(); 1265 } else { 1266 iter.next(); 1267 } 1268 } 1269 // Close the reachable set 1270 complete_gc->do_void(); 1271 1272 NOT_PRODUCT( 1273 if (PrintGCDetails && PrintReferenceGC && (iter.processed() > 0)) { 1274 gclog_or_tty->print_cr(" Dropped " SIZE_FORMAT " Refs out of " SIZE_FORMAT 1275 " Refs in discovered list " INTPTR_FORMAT, 1276 iter.removed(), iter.processed(), p2i(refs_list.head())); 1277 } 1278 ) 1279 } 1280 1281 const char* ReferenceProcessor::list_name(uint i) { 1282 assert(i <= _max_num_q * number_of_subclasses_of_ref(), 1283 "Out of bounds index"); 1284 1285 int j = i / _max_num_q; 1286 switch (j) { 1287 case 0: return "SoftRef"; 1288 case 1: return "WeakRef"; 1289 case 2: return "FinalRef"; 1290 case 3: return "PhantomRef"; 1291 case 4: return "CleanerRef"; 1292 } 1293 ShouldNotReachHere(); 1294 return NULL; 1295 }