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