1 /*
   2  * Copyright (c) 2001, 2018, 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.inline.hpp"
  27 #include "classfile/systemDictionary.hpp"
  28 #include "gc/shared/collectedHeap.hpp"
  29 #include "gc/shared/collectedHeap.inline.hpp"
  30 #include "gc/shared/gcTimer.hpp"
  31 #include "gc/shared/gcTraceTime.inline.hpp"
  32 #include "gc/shared/referencePolicy.hpp"
  33 #include "gc/shared/referenceProcessor.inline.hpp"
  34 #include "logging/log.hpp"
  35 #include "memory/allocation.inline.hpp"
  36 #include "memory/resourceArea.hpp"
  37 #include "oops/access.inline.hpp"
  38 #include "oops/oop.inline.hpp"
  39 #include "runtime/java.hpp"
  40 
  41 ReferencePolicy* ReferenceProcessor::_always_clear_soft_ref_policy = NULL;
  42 ReferencePolicy* ReferenceProcessor::_default_soft_ref_policy      = NULL;
  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   if (is_server_compilation_mode_vm()) {
  61     _default_soft_ref_policy = new LRUMaxHeapPolicy();
  62   } else {
  63     _default_soft_ref_policy = new LRUCurrentHeapPolicy();
  64   }
  65   if (_always_clear_soft_ref_policy == NULL || _default_soft_ref_policy == NULL) {
  66     vm_exit_during_initialization("Could not allocate reference policy object");
  67   }
  68   guarantee(RefDiscoveryPolicy == ReferenceBasedDiscovery ||
  69             RefDiscoveryPolicy == ReferentBasedDiscovery,
  70             "Unrecognized RefDiscoveryPolicy");
  71 }
  72 
  73 void ReferenceProcessor::enable_discovery(bool check_no_refs) {
  74 #ifdef ASSERT
  75   // Verify that we're not currently discovering refs
  76   assert(!_discovering_refs, "nested call?");
  77 
  78   if (check_no_refs) {
  79     // Verify that the discovered lists are empty
  80     verify_no_references_recorded();
  81   }
  82 #endif // ASSERT
  83 
  84   // Someone could have modified the value of the static
  85   // field in the j.l.r.SoftReference class that holds the
  86   // soft reference timestamp clock using reflection or
  87   // Unsafe between GCs. Unconditionally update the static
  88   // field in ReferenceProcessor here so that we use the new
  89   // value during reference discovery.
  90 
  91   _soft_ref_timestamp_clock = java_lang_ref_SoftReference::clock();
  92   _discovering_refs = true;
  93 }
  94 
  95 ReferenceProcessor::ReferenceProcessor(BoolObjectClosure* is_subject_to_discovery,
  96                                        bool      mt_processing,
  97                                        uint      mt_processing_degree,
  98                                        bool      mt_discovery,
  99                                        uint      mt_discovery_degree,
 100                                        bool      atomic_discovery,
 101                                        BoolObjectClosure* is_alive_non_header)  :
 102   _is_subject_to_discovery(is_subject_to_discovery),
 103   _discovering_refs(false),
 104   _enqueuing_is_done(false),
 105   _is_alive_non_header(is_alive_non_header),
 106   _processing_is_mt(mt_processing),
 107   _next_id(0)
 108 {
 109   assert(is_subject_to_discovery != NULL, "must be set");
 110 
 111   _discovery_is_atomic = atomic_discovery;
 112   _discovery_is_mt     = mt_discovery;
 113   _num_queues          = MAX2(1U, mt_processing_degree);
 114   _max_num_queues      = MAX2(_num_queues, mt_discovery_degree);
 115   _discovered_refs     = NEW_C_HEAP_ARRAY(DiscoveredList,
 116             _max_num_queues * number_of_subclasses_of_ref(), mtGC);
 117 
 118   if (_discovered_refs == NULL) {
 119     vm_exit_during_initialization("Could not allocated RefProc Array");
 120   }
 121   _discoveredSoftRefs    = &_discovered_refs[0];
 122   _discoveredWeakRefs    = &_discoveredSoftRefs[_max_num_queues];
 123   _discoveredFinalRefs   = &_discoveredWeakRefs[_max_num_queues];
 124   _discoveredPhantomRefs = &_discoveredFinalRefs[_max_num_queues];
 125 
 126   // Initialize all entries to NULL
 127   for (uint i = 0; i < _max_num_queues * number_of_subclasses_of_ref(); i++) {
 128     _discovered_refs[i].set_head(NULL);
 129     _discovered_refs[i].set_length(0);
 130   }
 131 
 132   setup_policy(false /* default soft ref policy */);
 133 }
 134 
 135 #ifndef PRODUCT
 136 void ReferenceProcessor::verify_no_references_recorded() {
 137   guarantee(!_discovering_refs, "Discovering refs?");
 138   for (uint i = 0; i < _max_num_queues * number_of_subclasses_of_ref(); i++) {
 139     guarantee(_discovered_refs[i].is_empty(),
 140               "Found non-empty discovered list at %u", i);
 141   }
 142 }
 143 #endif
 144 
 145 void ReferenceProcessor::weak_oops_do(OopClosure* f) {
 146   for (uint i = 0; i < _max_num_queues * number_of_subclasses_of_ref(); i++) {
 147     if (UseCompressedOops) {
 148       f->do_oop((narrowOop*)_discovered_refs[i].adr_head());
 149     } else {
 150       f->do_oop((oop*)_discovered_refs[i].adr_head());
 151     }
 152   }
 153 }
 154 
 155 void ReferenceProcessor::update_soft_ref_master_clock() {
 156   // Update (advance) the soft ref master clock field. This must be done
 157   // after processing the soft ref list.
 158 
 159   // We need a monotonically non-decreasing time in ms but
 160   // os::javaTimeMillis() does not guarantee monotonicity.
 161   jlong now = os::javaTimeNanos() / NANOSECS_PER_MILLISEC;
 162   jlong soft_ref_clock = java_lang_ref_SoftReference::clock();
 163   assert(soft_ref_clock == _soft_ref_timestamp_clock, "soft ref clocks out of sync");
 164 
 165   NOT_PRODUCT(
 166   if (now < _soft_ref_timestamp_clock) {
 167     log_warning(gc)("time warp: " JLONG_FORMAT " to " JLONG_FORMAT,
 168                     _soft_ref_timestamp_clock, now);
 169   }
 170   )
 171   // The values of now and _soft_ref_timestamp_clock are set using
 172   // javaTimeNanos(), which is guaranteed to be monotonically
 173   // non-decreasing provided the underlying platform provides such
 174   // a time source (and it is bug free).
 175   // In product mode, however, protect ourselves from non-monotonicity.
 176   if (now > _soft_ref_timestamp_clock) {
 177     _soft_ref_timestamp_clock = now;
 178     java_lang_ref_SoftReference::set_clock(now);
 179   }
 180   // Else leave clock stalled at its old value until time progresses
 181   // past clock value.
 182 }
 183 
 184 size_t ReferenceProcessor::total_count(DiscoveredList lists[]) const {
 185   size_t total = 0;
 186   for (uint i = 0; i < _max_num_queues; ++i) {
 187     total += lists[i].length();
 188   }
 189   return total;
 190 }
 191 
 192 ReferenceProcessorStats ReferenceProcessor::process_discovered_references(
 193   BoolObjectClosure*            is_alive,
 194   OopClosure*                   keep_alive,
 195   VoidClosure*                  complete_gc,
 196   AbstractRefProcTaskExecutor*  task_executor,
 197   ReferenceProcessorPhaseTimes* phase_times) {
 198 
 199   double start_time = os::elapsedTime();
 200 
 201   assert(!enqueuing_is_done(), "If here enqueuing should not be complete");
 202   // Stop treating discovered references specially.
 203   disable_discovery();
 204 
 205   // If discovery was concurrent, someone could have modified
 206   // the value of the static field in the j.l.r.SoftReference
 207   // class that holds the soft reference timestamp clock using
 208   // reflection or Unsafe between when discovery was enabled and
 209   // now. Unconditionally update the static field in ReferenceProcessor
 210   // here so that we use the new value during processing of the
 211   // discovered soft refs.
 212 
 213   _soft_ref_timestamp_clock = java_lang_ref_SoftReference::clock();
 214 
 215   ReferenceProcessorStats stats(total_count(_discoveredSoftRefs),
 216                                 total_count(_discoveredWeakRefs),
 217                                 total_count(_discoveredFinalRefs),
 218                                 total_count(_discoveredPhantomRefs));
 219 
 220   // Soft references
 221   {
 222     RefProcPhaseTimesTracker tt(REF_SOFT, phase_times, this);
 223     process_discovered_reflist(_discoveredSoftRefs, _current_soft_ref_policy, true,
 224                                is_alive, keep_alive, complete_gc, task_executor, phase_times);
 225   }
 226 
 227   update_soft_ref_master_clock();
 228 
 229   // Weak references
 230   {
 231     RefProcPhaseTimesTracker tt(REF_WEAK, phase_times, this);
 232     process_discovered_reflist(_discoveredWeakRefs, NULL, true,
 233                                is_alive, keep_alive, complete_gc, task_executor, phase_times);
 234   }
 235 
 236   // Final references
 237   {
 238     RefProcPhaseTimesTracker tt(REF_FINAL, phase_times, this);
 239     process_discovered_reflist(_discoveredFinalRefs, NULL, false,
 240                                is_alive, keep_alive, complete_gc, task_executor, phase_times);
 241   }
 242 
 243   // Phantom references
 244   {
 245     RefProcPhaseTimesTracker tt(REF_PHANTOM, phase_times, this);
 246     process_discovered_reflist(_discoveredPhantomRefs, NULL, true,
 247                                is_alive, keep_alive, complete_gc, task_executor, phase_times);
 248   }
 249 
 250   if (task_executor != NULL) {
 251     // Record the work done by the parallel workers.
 252     task_executor->set_single_threaded_mode();
 253   }
 254 
 255   phase_times->set_total_time_ms((os::elapsedTime() - start_time) * 1000);
 256 
 257   return stats;
 258 }
 259 
 260 void DiscoveredListIterator::load_ptrs(DEBUG_ONLY(bool allow_null_referent)) {
 261   _current_discovered_addr = java_lang_ref_Reference::discovered_addr_raw(_current_discovered);
 262   oop discovered = java_lang_ref_Reference::discovered(_current_discovered);
 263   assert(_current_discovered_addr && oopDesc::is_oop_or_null(discovered),
 264          "Expected an oop or NULL for discovered field at " PTR_FORMAT, p2i(discovered));
 265   _next_discovered = discovered;
 266 
 267   _referent_addr = java_lang_ref_Reference::referent_addr_raw(_current_discovered);
 268   _referent = java_lang_ref_Reference::referent(_current_discovered);
 269   assert(Universe::heap()->is_in_reserved_or_null(_referent),
 270          "Wrong oop found in java.lang.Reference object");
 271   assert(allow_null_referent ?
 272              oopDesc::is_oop_or_null(_referent)
 273            : oopDesc::is_oop(_referent),
 274          "Expected an oop%s for referent field at " PTR_FORMAT,
 275          (allow_null_referent ? " or NULL" : ""),
 276          p2i(_referent));
 277 }
 278 
 279 void DiscoveredListIterator::remove() {
 280   assert(oopDesc::is_oop(_current_discovered), "Dropping a bad reference");
 281   RawAccess<>::oop_store(_current_discovered_addr, oop(NULL));
 282 
 283   // First _prev_next ref actually points into DiscoveredList (gross).
 284   oop new_next;
 285   if (_next_discovered == _current_discovered) {
 286     // At the end of the list, we should make _prev point to itself.
 287     // If _ref is the first ref, then _prev_next will be in the DiscoveredList,
 288     // and _prev will be NULL.
 289     new_next = _prev_discovered;
 290   } else {
 291     new_next = _next_discovered;
 292   }
 293   // Remove Reference object from discovered list. Note that G1 does not need a
 294   // pre-barrier here because we know the Reference has already been found/marked,
 295   // that's how it ended up in the discovered list in the first place.
 296   RawAccess<>::oop_store(_prev_discovered_addr, new_next);
 297   NOT_PRODUCT(_removed++);
 298   _refs_list.dec_length(1);
 299 }
 300 
 301 void DiscoveredListIterator::clear_referent() {
 302   RawAccess<>::oop_store(_referent_addr, oop(NULL));
 303 }
 304 
 305 void DiscoveredListIterator::enqueue() {
 306   HeapAccess<AS_NO_KEEPALIVE>::oop_store_at(_current_discovered,
 307                                             java_lang_ref_Reference::discovered_offset,
 308                                             _next_discovered);
 309 }
 310 
 311 void DiscoveredListIterator::complete_enqueue() {
 312   if (_prev_discovered != NULL) {
 313     // This is the last object.
 314     // Swap refs_list into pending list and set obj's
 315     // discovered to what we read from the pending list.
 316     oop old = Universe::swap_reference_pending_list(_refs_list.head());
 317     HeapAccess<AS_NO_KEEPALIVE>::oop_store_at(_prev_discovered, java_lang_ref_Reference::discovered_offset, old);
 318   }
 319 }
 320 
 321 // NOTE: process_phase*() are largely similar, and at a high level
 322 // merely iterate over the extant list applying a predicate to
 323 // each of its elements and possibly removing that element from the
 324 // list and applying some further closures to that element.
 325 // We should consider the possibility of replacing these
 326 // process_phase*() methods by abstracting them into
 327 // a single general iterator invocation that receives appropriate
 328 // closures that accomplish this work.
 329 
 330 // (SoftReferences only) Traverse the list and remove any SoftReferences whose
 331 // referents are not alive, but that should be kept alive for policy reasons.
 332 // Keep alive the transitive closure of all such referents.
 333 void
 334 ReferenceProcessor::process_phase1(DiscoveredList&    refs_list,
 335                                    ReferencePolicy*   policy,
 336                                    BoolObjectClosure* is_alive,
 337                                    OopClosure*        keep_alive,
 338                                    VoidClosure*       complete_gc) {
 339   assert(policy != NULL, "Must have a non-NULL policy");
 340   DiscoveredListIterator iter(refs_list, keep_alive, is_alive);
 341   // Decide which softly reachable refs should be kept alive.
 342   while (iter.has_next()) {
 343     iter.load_ptrs(DEBUG_ONLY(!discovery_is_atomic() /* allow_null_referent */));
 344     bool referent_is_dead = (iter.referent() != NULL) && !iter.is_referent_alive();
 345     if (referent_is_dead &&
 346         !policy->should_clear_reference(iter.obj(), _soft_ref_timestamp_clock)) {
 347       log_develop_trace(gc, ref)("Dropping reference (" INTPTR_FORMAT ": %s"  ") by policy",
 348                                  p2i(iter.obj()), iter.obj()->klass()->internal_name());
 349       // Remove Reference object from list
 350       iter.remove();
 351       // keep the referent around
 352       iter.make_referent_alive();
 353       iter.move_to_next();
 354     } else {
 355       iter.next();
 356     }
 357   }
 358   // Close the reachable set
 359   complete_gc->do_void();
 360   log_develop_trace(gc, ref)(" Dropped " SIZE_FORMAT " dead Refs out of " SIZE_FORMAT " discovered Refs by policy, from list " INTPTR_FORMAT,
 361                              iter.removed(), iter.processed(), p2i(&refs_list));
 362 }
 363 
 364 inline void log_dropped_ref(const DiscoveredListIterator& iter, const char* reason) {
 365   log_develop_trace(gc, ref)("Dropping %s reference " PTR_FORMAT ": %s",
 366                              reason, p2i(iter.obj()),
 367                              iter.obj()->klass()->internal_name());
 368 }
 369 
 370 // Traverse the list and remove any Refs whose referents are alive,
 371 // or NULL if discovery is not atomic.
 372 void ReferenceProcessor::process_phase2(DiscoveredList&    refs_list,
 373                                         BoolObjectClosure* is_alive,
 374                                         OopClosure*        keep_alive,
 375                                         VoidClosure*       complete_gc) {
 376   // complete_gc is unused.
 377   DiscoveredListIterator iter(refs_list, keep_alive, is_alive);
 378   while (iter.has_next()) {
 379     iter.load_ptrs(DEBUG_ONLY(!discovery_is_atomic() /* allow_null_referent */));
 380     if (iter.referent() == NULL) {
 381       // Reference has been cleared since discovery; only possible if
 382       // discovery is not atomic.  Remove reference from list.
 383       log_dropped_ref(iter, "cleared");
 384       iter.remove();
 385       iter.move_to_next();
 386     } else if (iter.is_referent_alive()) {
 387       // The referent is reachable after all.
 388       // Remove reference from list.
 389       log_dropped_ref(iter, "reachable");
 390       iter.remove();
 391       // Update the referent pointer as necessary.  Note that this
 392       // should not entail any recursive marking because the
 393       // referent must already have been traversed.
 394       iter.make_referent_alive();
 395       iter.move_to_next();
 396     } else {
 397       iter.next();
 398     }
 399   }
 400   NOT_PRODUCT(
 401     if (iter.processed() > 0) {
 402       log_develop_trace(gc, ref)(" Dropped " SIZE_FORMAT " active Refs out of " SIZE_FORMAT
 403         " Refs in discovered list " INTPTR_FORMAT,
 404         iter.removed(), iter.processed(), p2i(&refs_list));
 405     }
 406   )
 407 }
 408 
 409 void ReferenceProcessor::process_phase3(DiscoveredList&    refs_list,
 410                                         bool               clear_referent,
 411                                         BoolObjectClosure* is_alive,
 412                                         OopClosure*        keep_alive,
 413                                         VoidClosure*       complete_gc) {
 414   ResourceMark rm;
 415   DiscoveredListIterator iter(refs_list, keep_alive, is_alive);
 416   while (iter.has_next()) {
 417     iter.load_ptrs(DEBUG_ONLY(false /* allow_null_referent */));
 418     if (clear_referent) {
 419       // NULL out referent pointer
 420       iter.clear_referent();
 421     } else {
 422       // Current reference is a FinalReference; that's the only kind we
 423       // don't clear the referent, instead keeping it for calling finalize.
 424       iter.make_referent_alive();
 425       // Self-loop next, to mark it not active.
 426       assert(java_lang_ref_Reference::next(iter.obj()) == NULL, "enqueued FinalReference");
 427       java_lang_ref_Reference::set_next_raw(iter.obj(), iter.obj());
 428     }
 429     iter.enqueue();
 430     log_develop_trace(gc, ref)("Adding %sreference (" INTPTR_FORMAT ": %s) as pending",
 431                                clear_referent ? "cleared " : "", p2i(iter.obj()), iter.obj()->klass()->internal_name());
 432     assert(oopDesc::is_oop(iter.obj(), UseConcMarkSweepGC), "Adding a bad reference");
 433     iter.next();
 434   }
 435   iter.complete_enqueue();
 436   // Close the reachable set
 437   complete_gc->do_void();
 438   // Clear the list.
 439   refs_list.set_head(NULL);
 440   refs_list.set_length(0);
 441 }
 442 
 443 void
 444 ReferenceProcessor::clear_discovered_references(DiscoveredList& refs_list) {
 445   oop obj = NULL;
 446   oop next = refs_list.head();
 447   while (next != obj) {
 448     obj = next;
 449     next = java_lang_ref_Reference::discovered(obj);
 450     java_lang_ref_Reference::set_discovered_raw(obj, NULL);
 451   }
 452   refs_list.set_head(NULL);
 453   refs_list.set_length(0);
 454 }
 455 
 456 void ReferenceProcessor::abandon_partial_discovery() {
 457   // loop over the lists
 458   for (uint i = 0; i < _max_num_queues * number_of_subclasses_of_ref(); i++) {
 459     if ((i % _max_num_queues) == 0) {
 460       log_develop_trace(gc, ref)("Abandoning %s discovered list", list_name(i));
 461     }
 462     clear_discovered_references(_discovered_refs[i]);
 463   }
 464 }
 465 
 466 size_t ReferenceProcessor::total_reference_count(ReferenceType type) const {
 467   DiscoveredList* list = NULL;
 468 
 469   switch (type) {
 470     case REF_SOFT:
 471       list = _discoveredSoftRefs;
 472       break;
 473     case REF_WEAK:
 474       list = _discoveredWeakRefs;
 475       break;
 476     case REF_FINAL:
 477       list = _discoveredFinalRefs;
 478       break;
 479     case REF_PHANTOM:
 480       list = _discoveredPhantomRefs;
 481       break;
 482     case REF_OTHER:
 483     case REF_NONE:
 484     default:
 485       ShouldNotReachHere();
 486   }
 487   return total_count(list);
 488 }
 489 
 490 class RefProcPhase1Task: public AbstractRefProcTaskExecutor::ProcessTask {
 491 public:
 492   RefProcPhase1Task(ReferenceProcessor&           ref_processor,
 493                     DiscoveredList                refs_lists[],
 494                     ReferencePolicy*              policy,
 495                     bool                          marks_oops_alive,
 496                     ReferenceProcessorPhaseTimes* phase_times)
 497     : ProcessTask(ref_processor, refs_lists, marks_oops_alive, phase_times),
 498       _policy(policy)
 499   { }
 500   virtual void work(unsigned int i, BoolObjectClosure& is_alive,
 501                     OopClosure& keep_alive,
 502                     VoidClosure& complete_gc)
 503   {
 504     RefProcWorkerTimeTracker tt(ReferenceProcessorPhaseTimes::RefPhase1, _phase_times, i);
 505 
 506     _ref_processor.process_phase1(_refs_lists[i], _policy,
 507                                   &is_alive, &keep_alive, &complete_gc);
 508   }
 509 private:
 510   ReferencePolicy* _policy;
 511 };
 512 
 513 class RefProcPhase2Task: public AbstractRefProcTaskExecutor::ProcessTask {
 514 public:
 515   RefProcPhase2Task(ReferenceProcessor&           ref_processor,
 516                     DiscoveredList                refs_lists[],
 517                     bool                          marks_oops_alive,
 518                     ReferenceProcessorPhaseTimes* phase_times)
 519     : ProcessTask(ref_processor, refs_lists, marks_oops_alive, phase_times)
 520   { }
 521   virtual void work(unsigned int i, BoolObjectClosure& is_alive,
 522                     OopClosure& keep_alive,
 523                     VoidClosure& complete_gc)
 524   {
 525     RefProcWorkerTimeTracker tt(ReferenceProcessorPhaseTimes::RefPhase2, _phase_times, i);
 526 
 527     _ref_processor.process_phase2(_refs_lists[i],
 528                                   &is_alive, &keep_alive, &complete_gc);
 529   }
 530 };
 531 
 532 class RefProcPhase3Task: public AbstractRefProcTaskExecutor::ProcessTask {
 533 public:
 534   RefProcPhase3Task(ReferenceProcessor&           ref_processor,
 535                     DiscoveredList                refs_lists[],
 536                     bool                         clear_referent,
 537                     bool                          marks_oops_alive,
 538                     ReferenceProcessorPhaseTimes* phase_times)
 539     : ProcessTask(ref_processor, refs_lists, marks_oops_alive, phase_times),
 540       _clear_referent(clear_referent)
 541   { }
 542   virtual void work(unsigned int i, BoolObjectClosure& is_alive,
 543                     OopClosure& keep_alive,
 544                     VoidClosure& complete_gc)
 545   {
 546     RefProcWorkerTimeTracker tt(ReferenceProcessorPhaseTimes::RefPhase3, _phase_times, i);
 547 
 548     _ref_processor.process_phase3(_refs_lists[i], _clear_referent,
 549                                   &is_alive, &keep_alive, &complete_gc);
 550   }
 551 private:
 552   bool _clear_referent;
 553 };
 554 
 555 void ReferenceProcessor::log_reflist(const char* prefix, DiscoveredList list[], uint num_active_queues) {
 556   LogTarget(Trace, gc, ref) lt;
 557 
 558   if (!lt.is_enabled()) {
 559     return;
 560   }
 561 
 562   size_t total = 0;
 563 
 564   LogStream ls(lt);
 565   ls.print("%s", prefix);
 566   for (uint i = 0; i < num_active_queues; i++) {
 567     ls.print(SIZE_FORMAT " ", list[i].length());
 568     total += list[i].length();
 569   }
 570   ls.print_cr("(" SIZE_FORMAT ")", total);
 571 }
 572 
 573 #ifndef PRODUCT
 574 void ReferenceProcessor::log_reflist_counts(DiscoveredList ref_lists[], uint num_active_queues) {
 575   if (!log_is_enabled(Trace, gc, ref)) {
 576     return;
 577   }
 578 
 579   log_reflist("", ref_lists, num_active_queues);
 580 #ifdef ASSERT
 581   for (uint i = num_active_queues; i < _max_num_queues; i++) {
 582     assert(ref_lists[i].length() == 0, SIZE_FORMAT " unexpected References in %u",
 583            ref_lists[i].length(), i);
 584   }
 585 #endif
 586 }
 587 #endif
 588 
 589 void ReferenceProcessor::set_active_mt_degree(uint v) {
 590   _num_queues = v;
 591   _next_id = 0;
 592 }
 593 
 594 // Balances reference queues.
 595 // Move entries from all queues[0, 1, ..., _max_num_q-1] to
 596 // queues[0, 1, ..., _num_q-1] because only the first _num_q
 597 // corresponding to the active workers will be processed.
 598 void ReferenceProcessor::balance_queues(DiscoveredList ref_lists[])
 599 {
 600   // calculate total length
 601   size_t total_refs = 0;
 602   log_develop_trace(gc, ref)("Balance ref_lists ");
 603 
 604   log_reflist_counts(ref_lists, _max_num_queues);
 605 
 606   for (uint i = 0; i < _max_num_queues; ++i) {
 607     total_refs += ref_lists[i].length();
 608   }
 609   size_t avg_refs = total_refs / _num_queues + 1;
 610   uint to_idx = 0;
 611   for (uint from_idx = 0; from_idx < _max_num_queues; from_idx++) {
 612     bool move_all = false;
 613     if (from_idx >= _num_queues) {
 614       move_all = ref_lists[from_idx].length() > 0;
 615     }
 616     while ((ref_lists[from_idx].length() > avg_refs) ||
 617            move_all) {
 618       assert(to_idx < _num_queues, "Sanity Check!");
 619       if (ref_lists[to_idx].length() < avg_refs) {
 620         // move superfluous refs
 621         size_t refs_to_move;
 622         // Move all the Ref's if the from queue will not be processed.
 623         if (move_all) {
 624           refs_to_move = MIN2(ref_lists[from_idx].length(),
 625                               avg_refs - ref_lists[to_idx].length());
 626         } else {
 627           refs_to_move = MIN2(ref_lists[from_idx].length() - avg_refs,
 628                               avg_refs - ref_lists[to_idx].length());
 629         }
 630 
 631         assert(refs_to_move > 0, "otherwise the code below will fail");
 632 
 633         oop move_head = ref_lists[from_idx].head();
 634         oop move_tail = move_head;
 635         oop new_head  = move_head;
 636         // find an element to split the list on
 637         for (size_t j = 0; j < refs_to_move; ++j) {
 638           move_tail = new_head;
 639           new_head = java_lang_ref_Reference::discovered(new_head);
 640         }
 641 
 642         // Add the chain to the to list.
 643         if (ref_lists[to_idx].head() == NULL) {
 644           // to list is empty. Make a loop at the end.
 645           java_lang_ref_Reference::set_discovered_raw(move_tail, move_tail);
 646         } else {
 647           java_lang_ref_Reference::set_discovered_raw(move_tail, ref_lists[to_idx].head());
 648         }
 649         ref_lists[to_idx].set_head(move_head);
 650         ref_lists[to_idx].inc_length(refs_to_move);
 651 
 652         // Remove the chain from the from list.
 653         if (move_tail == new_head) {
 654           // We found the end of the from list.
 655           ref_lists[from_idx].set_head(NULL);
 656         } else {
 657           ref_lists[from_idx].set_head(new_head);
 658         }
 659         ref_lists[from_idx].dec_length(refs_to_move);
 660         if (ref_lists[from_idx].length() == 0) {
 661           break;
 662         }
 663       } else {
 664         to_idx = (to_idx + 1) % _num_queues;
 665       }
 666     }
 667   }
 668 #ifdef ASSERT
 669   log_reflist_counts(ref_lists, _num_queues);
 670   size_t balanced_total_refs = 0;
 671   for (uint i = 0; i < _num_queues; ++i) {
 672     balanced_total_refs += ref_lists[i].length();
 673   }
 674   assert(total_refs == balanced_total_refs, "Balancing was incomplete");
 675 #endif
 676 }
 677 
 678 void ReferenceProcessor::process_discovered_reflist(
 679   DiscoveredList                refs_lists[],
 680   ReferencePolicy*              policy,
 681   bool                          clear_referent,
 682   BoolObjectClosure*            is_alive,
 683   OopClosure*                   keep_alive,
 684   VoidClosure*                  complete_gc,
 685   AbstractRefProcTaskExecutor*  task_executor,
 686   ReferenceProcessorPhaseTimes* phase_times)
 687 {
 688   bool mt_processing = task_executor != NULL && _processing_is_mt;
 689 
 690   phase_times->set_processing_is_mt(mt_processing);
 691 
 692   if (mt_processing && ParallelRefProcBalancingEnabled) {
 693     RefProcBalanceQueuesTimeTracker tt(phase_times);
 694     balance_queues(refs_lists);
 695   }
 696 
 697   // Phase 1 (soft refs only):
 698   // . Traverse the list and remove any SoftReferences whose
 699   //   referents are not alive, but that should be kept alive for
 700   //   policy reasons. Keep alive the transitive closure of all
 701   //   such referents.
 702   if (policy != NULL) {
 703     RefProcParPhaseTimeTracker tt(ReferenceProcessorPhaseTimes::RefPhase1, phase_times);
 704 
 705     if (mt_processing) {
 706       RefProcPhase1Task phase1(*this, refs_lists, policy, true /*marks_oops_alive*/, phase_times);
 707       task_executor->execute(phase1);
 708     } else {
 709       for (uint i = 0; i < _max_num_queues; i++) {
 710         process_phase1(refs_lists[i], policy,
 711                        is_alive, keep_alive, complete_gc);
 712       }
 713     }
 714   } else { // policy == NULL
 715     assert(refs_lists != _discoveredSoftRefs,
 716            "Policy must be specified for soft references.");
 717   }
 718 
 719   // Phase 2:
 720   // . Traverse the list and remove any refs whose referents are alive.
 721   {
 722     RefProcParPhaseTimeTracker tt(ReferenceProcessorPhaseTimes::RefPhase2, phase_times);
 723 
 724     if (mt_processing) {
 725       RefProcPhase2Task phase2(*this, refs_lists, !discovery_is_atomic() /*marks_oops_alive*/, phase_times);
 726       task_executor->execute(phase2);
 727     } else {
 728       for (uint i = 0; i < _max_num_queues; i++) {
 729         process_phase2(refs_lists[i], is_alive, keep_alive, complete_gc);
 730       }
 731     }
 732   }
 733 
 734   // Phase 3:
 735   // . Traverse the list and process referents as appropriate.
 736   {
 737     RefProcParPhaseTimeTracker tt(ReferenceProcessorPhaseTimes::RefPhase3, phase_times);
 738 
 739     if (mt_processing) {
 740       RefProcPhase3Task phase3(*this, refs_lists, clear_referent, true /*marks_oops_alive*/, phase_times);
 741       task_executor->execute(phase3);
 742     } else {
 743       for (uint i = 0; i < _max_num_queues; i++) {
 744         process_phase3(refs_lists[i], clear_referent,
 745                        is_alive, keep_alive, complete_gc);
 746       }
 747     }
 748   }
 749 }
 750 
 751 inline DiscoveredList* ReferenceProcessor::get_discovered_list(ReferenceType rt) {
 752   uint id = 0;
 753   // Determine the queue index to use for this object.
 754   if (_discovery_is_mt) {
 755     // During a multi-threaded discovery phase,
 756     // each thread saves to its "own" list.
 757     Thread* thr = Thread::current();
 758     id = thr->as_Worker_thread()->id();
 759   } else {
 760     // single-threaded discovery, we save in round-robin
 761     // fashion to each of the lists.
 762     if (_processing_is_mt) {
 763       id = next_id();
 764     }
 765   }
 766   assert(id < _max_num_queues, "Id is out of bounds id %u and max id %u)", id, _max_num_queues);
 767 
 768   // Get the discovered queue to which we will add
 769   DiscoveredList* list = NULL;
 770   switch (rt) {
 771     case REF_OTHER:
 772       // Unknown reference type, no special treatment
 773       break;
 774     case REF_SOFT:
 775       list = &_discoveredSoftRefs[id];
 776       break;
 777     case REF_WEAK:
 778       list = &_discoveredWeakRefs[id];
 779       break;
 780     case REF_FINAL:
 781       list = &_discoveredFinalRefs[id];
 782       break;
 783     case REF_PHANTOM:
 784       list = &_discoveredPhantomRefs[id];
 785       break;
 786     case REF_NONE:
 787       // we should not reach here if we are an InstanceRefKlass
 788     default:
 789       ShouldNotReachHere();
 790   }
 791   log_develop_trace(gc, ref)("Thread %d gets list " INTPTR_FORMAT, id, p2i(list));
 792   return list;
 793 }
 794 
 795 inline void
 796 ReferenceProcessor::add_to_discovered_list_mt(DiscoveredList& refs_list,
 797                                               oop             obj,
 798                                               HeapWord*       discovered_addr) {
 799   assert(_discovery_is_mt, "!_discovery_is_mt should have been handled by caller");
 800   // First we must make sure this object is only enqueued once. CAS in a non null
 801   // discovered_addr.
 802   oop current_head = refs_list.head();
 803   // The last ref must have its discovered field pointing to itself.
 804   oop next_discovered = (current_head != NULL) ? current_head : obj;
 805 
 806   oop retest = RawAccess<>::oop_atomic_cmpxchg(next_discovered, discovered_addr, oop(NULL));
 807 
 808   if (retest == NULL) {
 809     // This thread just won the right to enqueue the object.
 810     // We have separate lists for enqueueing, so no synchronization
 811     // is necessary.
 812     refs_list.set_head(obj);
 813     refs_list.inc_length(1);
 814 
 815     log_develop_trace(gc, ref)("Discovered reference (mt) (" INTPTR_FORMAT ": %s)",
 816                                p2i(obj), obj->klass()->internal_name());
 817   } else {
 818     // If retest was non NULL, another thread beat us to it:
 819     // The reference has already been discovered...
 820     log_develop_trace(gc, ref)("Already discovered reference (" INTPTR_FORMAT ": %s)",
 821                                p2i(obj), obj->klass()->internal_name());
 822   }
 823 }
 824 
 825 #ifndef PRODUCT
 826 // Non-atomic (i.e. concurrent) discovery might allow us
 827 // to observe j.l.References with NULL referents, being those
 828 // cleared concurrently by mutators during (or after) discovery.
 829 void ReferenceProcessor::verify_referent(oop obj) {
 830   bool da = discovery_is_atomic();
 831   oop referent = java_lang_ref_Reference::referent(obj);
 832   assert(da ? oopDesc::is_oop(referent) : oopDesc::is_oop_or_null(referent),
 833          "Bad referent " INTPTR_FORMAT " found in Reference "
 834          INTPTR_FORMAT " during %satomic discovery ",
 835          p2i(referent), p2i(obj), da ? "" : "non-");
 836 }
 837 #endif
 838 
 839 bool ReferenceProcessor::is_subject_to_discovery(oop const obj) const {
 840   return _is_subject_to_discovery->do_object_b(obj);
 841 }
 842 
 843 // We mention two of several possible choices here:
 844 // #0: if the reference object is not in the "originating generation"
 845 //     (or part of the heap being collected, indicated by our "span"
 846 //     we don't treat it specially (i.e. we scan it as we would
 847 //     a normal oop, treating its references as strong references).
 848 //     This means that references can't be discovered unless their
 849 //     referent is also in the same span. This is the simplest,
 850 //     most "local" and most conservative approach, albeit one
 851 //     that may cause weak references to be enqueued least promptly.
 852 //     We call this choice the "ReferenceBasedDiscovery" policy.
 853 // #1: the reference object may be in any generation (span), but if
 854 //     the referent is in the generation (span) being currently collected
 855 //     then we can discover the reference object, provided
 856 //     the object has not already been discovered by
 857 //     a different concurrently running collector (as may be the
 858 //     case, for instance, if the reference object is in CMS and
 859 //     the referent in DefNewGeneration), and provided the processing
 860 //     of this reference object by the current collector will
 861 //     appear atomic to every other collector in the system.
 862 //     (Thus, for instance, a concurrent collector may not
 863 //     discover references in other generations even if the
 864 //     referent is in its own generation). This policy may,
 865 //     in certain cases, enqueue references somewhat sooner than
 866 //     might Policy #0 above, but at marginally increased cost
 867 //     and complexity in processing these references.
 868 //     We call this choice the "RefeferentBasedDiscovery" policy.
 869 bool ReferenceProcessor::discover_reference(oop obj, ReferenceType rt) {
 870   // Make sure we are discovering refs (rather than processing discovered refs).
 871   if (!_discovering_refs || !RegisterReferences) {
 872     return false;
 873   }
 874 
 875   if ((rt == REF_FINAL) && (java_lang_ref_Reference::next(obj) != NULL)) {
 876     // Don't rediscover non-active FinalReferences.
 877     return false;
 878   }
 879 
 880   if (RefDiscoveryPolicy == ReferenceBasedDiscovery &&
 881       !is_subject_to_discovery(obj)) {
 882     // Reference is not in the originating generation;
 883     // don't treat it specially (i.e. we want to scan it as a normal
 884     // object with strong references).
 885     return false;
 886   }
 887 
 888   // We only discover references whose referents are not (yet)
 889   // known to be strongly reachable.
 890   if (is_alive_non_header() != NULL) {
 891     verify_referent(obj);
 892     if (is_alive_non_header()->do_object_b(java_lang_ref_Reference::referent(obj))) {
 893       return false;  // referent is reachable
 894     }
 895   }
 896   if (rt == REF_SOFT) {
 897     // For soft refs we can decide now if these are not
 898     // current candidates for clearing, in which case we
 899     // can mark through them now, rather than delaying that
 900     // to the reference-processing phase. Since all current
 901     // time-stamp policies advance the soft-ref clock only
 902     // at a full collection cycle, this is always currently
 903     // accurate.
 904     if (!_current_soft_ref_policy->should_clear_reference(obj, _soft_ref_timestamp_clock)) {
 905       return false;
 906     }
 907   }
 908 
 909   ResourceMark rm;      // Needed for tracing.
 910 
 911   HeapWord* const discovered_addr = java_lang_ref_Reference::discovered_addr_raw(obj);
 912   const oop  discovered = java_lang_ref_Reference::discovered(obj);
 913   assert(oopDesc::is_oop_or_null(discovered), "Expected an oop or NULL for discovered field at " PTR_FORMAT, p2i(discovered));
 914   if (discovered != NULL) {
 915     // The reference has already been discovered...
 916     log_develop_trace(gc, ref)("Already discovered reference (" INTPTR_FORMAT ": %s)",
 917                                p2i(obj), obj->klass()->internal_name());
 918     if (RefDiscoveryPolicy == ReferentBasedDiscovery) {
 919       // assumes that an object is not processed twice;
 920       // if it's been already discovered it must be on another
 921       // generation's discovered list; so we won't discover it.
 922       return false;
 923     } else {
 924       assert(RefDiscoveryPolicy == ReferenceBasedDiscovery,
 925              "Unrecognized policy");
 926       // Check assumption that an object is not potentially
 927       // discovered twice except by concurrent collectors that potentially
 928       // trace the same Reference object twice.
 929       assert(UseConcMarkSweepGC || UseG1GC,
 930              "Only possible with a concurrent marking collector");
 931       return true;
 932     }
 933   }
 934 
 935   if (RefDiscoveryPolicy == ReferentBasedDiscovery) {
 936     verify_referent(obj);
 937     // Discover if and only if EITHER:
 938     // .. reference is in our span, OR
 939     // .. we are an atomic collector and referent is in our span
 940     if (is_subject_to_discovery(obj) ||
 941         (discovery_is_atomic() &&
 942          is_subject_to_discovery(java_lang_ref_Reference::referent(obj)))) {
 943     } else {
 944       return false;
 945     }
 946   } else {
 947     assert(RefDiscoveryPolicy == ReferenceBasedDiscovery &&
 948            is_subject_to_discovery(obj), "code inconsistency");
 949   }
 950 
 951   // Get the right type of discovered queue head.
 952   DiscoveredList* list = get_discovered_list(rt);
 953   if (list == NULL) {
 954     return false;   // nothing special needs to be done
 955   }
 956 
 957   if (_discovery_is_mt) {
 958     add_to_discovered_list_mt(*list, obj, discovered_addr);
 959   } else {
 960     // We do a raw store here: the field will be visited later when processing
 961     // the discovered references.
 962     oop current_head = list->head();
 963     // The last ref must have its discovered field pointing to itself.
 964     oop next_discovered = (current_head != NULL) ? current_head : obj;
 965 
 966     assert(discovered == NULL, "control point invariant");
 967     RawAccess<>::oop_store(discovered_addr, next_discovered);
 968     list->set_head(obj);
 969     list->inc_length(1);
 970 
 971     log_develop_trace(gc, ref)("Discovered reference (" INTPTR_FORMAT ": %s)", p2i(obj), obj->klass()->internal_name());
 972   }
 973   assert(oopDesc::is_oop(obj), "Discovered a bad reference");
 974   verify_referent(obj);
 975   return true;
 976 }
 977 
 978 bool ReferenceProcessor::has_discovered_references() {
 979   for (uint i = 0; i < _max_num_queues * number_of_subclasses_of_ref(); i++) {
 980     if (!_discovered_refs[i].is_empty()) {
 981       return true;
 982     }
 983   }
 984   return false;
 985 }
 986 
 987 void ReferenceProcessor::preclean_discovered_references(BoolObjectClosure* is_alive,
 988                                                         OopClosure* keep_alive,
 989                                                         VoidClosure* complete_gc,
 990                                                         YieldClosure* yield,
 991                                                         GCTimer* gc_timer) {
 992   // These lists can be handled here in any order and, indeed, concurrently.
 993 
 994   // Soft references
 995   {
 996     GCTraceTime(Debug, gc, ref) tm("Preclean SoftReferences", gc_timer);
 997     log_reflist("SoftRef before: ", _discoveredSoftRefs, _max_num_queues);
 998     for (uint i = 0; i < _max_num_queues; i++) {
 999       if (yield->should_return()) {
1000         return;
1001       }
1002       if (preclean_discovered_reflist(_discoveredSoftRefs[i], is_alive,
1003                                       keep_alive, complete_gc, yield)) {
1004         log_reflist("SoftRef abort: ", _discoveredSoftRefs, _max_num_queues);
1005         return;
1006       }
1007     }
1008     log_reflist("SoftRef after: ", _discoveredSoftRefs, _max_num_queues);
1009   }
1010 
1011   // Weak references
1012   {
1013     GCTraceTime(Debug, gc, ref) tm("Preclean WeakReferences", gc_timer);
1014     log_reflist("WeakRef before: ", _discoveredWeakRefs, _max_num_queues);
1015     for (uint i = 0; i < _max_num_queues; i++) {
1016       if (yield->should_return()) {
1017         return;
1018       }
1019       if (preclean_discovered_reflist(_discoveredWeakRefs[i], is_alive,
1020                                       keep_alive, complete_gc, yield)) {
1021         log_reflist("WeakRef abort: ", _discoveredWeakRefs, _max_num_queues);
1022         return;
1023       }
1024     }
1025     log_reflist("WeakRef after: ", _discoveredWeakRefs, _max_num_queues);
1026   }
1027 
1028   // Final references
1029   {
1030     GCTraceTime(Debug, gc, ref) tm("Preclean FinalReferences", gc_timer);
1031     log_reflist("FinalRef before: ", _discoveredFinalRefs, _max_num_queues);
1032     for (uint i = 0; i < _max_num_queues; i++) {
1033       if (yield->should_return()) {
1034         return;
1035       }
1036       if (preclean_discovered_reflist(_discoveredFinalRefs[i], is_alive,
1037                                       keep_alive, complete_gc, yield)) {
1038         log_reflist("FinalRef abort: ", _discoveredFinalRefs, _max_num_queues);
1039         return;
1040       }
1041     }
1042     log_reflist("FinalRef after: ", _discoveredFinalRefs, _max_num_queues);
1043   }
1044 
1045   // Phantom references
1046   {
1047     GCTraceTime(Debug, gc, ref) tm("Preclean PhantomReferences", gc_timer);
1048     log_reflist("PhantomRef before: ", _discoveredPhantomRefs, _max_num_queues);
1049     for (uint i = 0; i < _max_num_queues; i++) {
1050       if (yield->should_return()) {
1051         return;
1052       }
1053       if (preclean_discovered_reflist(_discoveredPhantomRefs[i], is_alive,
1054                                       keep_alive, complete_gc, yield)) {
1055         log_reflist("PhantomRef abort: ", _discoveredPhantomRefs, _max_num_queues);
1056         return;
1057       }
1058     }
1059     log_reflist("PhantomRef after: ", _discoveredPhantomRefs, _max_num_queues);
1060   }
1061 }
1062 
1063 // Walk the given discovered ref list, and remove all reference objects
1064 // whose referents are still alive, whose referents are NULL or which
1065 // are not active (have a non-NULL next field). NOTE: When we are
1066 // thus precleaning the ref lists (which happens single-threaded today),
1067 // we do not disable refs discovery to honor the correct semantics of
1068 // java.lang.Reference. As a result, we need to be careful below
1069 // that ref removal steps interleave safely with ref discovery steps
1070 // (in this thread).
1071 bool ReferenceProcessor::preclean_discovered_reflist(DiscoveredList&    refs_list,
1072                                                      BoolObjectClosure* is_alive,
1073                                                      OopClosure*        keep_alive,
1074                                                      VoidClosure*       complete_gc,
1075                                                      YieldClosure*      yield) {
1076   DiscoveredListIterator iter(refs_list, keep_alive, is_alive);
1077   while (iter.has_next()) {
1078     if (yield->should_return_fine_grain()) {
1079       return true;
1080     }
1081     iter.load_ptrs(DEBUG_ONLY(true /* allow_null_referent */));
1082     if (iter.referent() == NULL || iter.is_referent_alive()) {
1083       // The referent has been cleared, or is alive; we need to trace
1084       // and mark its cohort.
1085       log_develop_trace(gc, ref)("Precleaning Reference (" INTPTR_FORMAT ": %s)",
1086                                  p2i(iter.obj()), iter.obj()->klass()->internal_name());
1087       // Remove Reference object from list
1088       iter.remove();
1089       // Keep alive its cohort.
1090       iter.make_referent_alive();
1091       iter.move_to_next();
1092     } else {
1093       iter.next();
1094     }
1095   }
1096   // Close the reachable set
1097   complete_gc->do_void();
1098 
1099   NOT_PRODUCT(
1100     if (iter.processed() > 0) {
1101       log_develop_trace(gc, ref)(" Dropped " SIZE_FORMAT " Refs out of " SIZE_FORMAT " Refs in discovered list " INTPTR_FORMAT,
1102         iter.removed(), iter.processed(), p2i(&refs_list));
1103     }
1104   )
1105   return false;
1106 }
1107 
1108 const char* ReferenceProcessor::list_name(uint i) {
1109    assert(i <= _max_num_queues * number_of_subclasses_of_ref(),
1110           "Out of bounds index");
1111 
1112    int j = i / _max_num_queues;
1113    switch (j) {
1114      case 0: return "SoftRef";
1115      case 1: return "WeakRef";
1116      case 2: return "FinalRef";
1117      case 3: return "PhantomRef";
1118    }
1119    ShouldNotReachHere();
1120    return NULL;
1121 }