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