< prev index next >

src/share/vm/gc/shared/referenceProcessor.cpp

Print this page
rev 13070 : [mq]: webrev.0a
   1 /*
   2  * Copyright (c) 2001, 2016, 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  *


 110   _discovery_is_mt     = mt_discovery;
 111   _num_q               = MAX2(1U, mt_processing_degree);
 112   _max_num_q           = MAX2(_num_q, mt_discovery_degree);
 113   _discovered_refs     = NEW_C_HEAP_ARRAY(DiscoveredList,
 114             _max_num_q * number_of_subclasses_of_ref(), mtGC);
 115 
 116   if (_discovered_refs == NULL) {
 117     vm_exit_during_initialization("Could not allocated RefProc Array");
 118   }
 119   _discoveredSoftRefs    = &_discovered_refs[0];
 120   _discoveredWeakRefs    = &_discoveredSoftRefs[_max_num_q];
 121   _discoveredFinalRefs   = &_discoveredWeakRefs[_max_num_q];
 122   _discoveredPhantomRefs = &_discoveredFinalRefs[_max_num_q];
 123 
 124   // Initialize all entries to NULL
 125   for (uint i = 0; i < _max_num_q * number_of_subclasses_of_ref(); i++) {
 126     _discovered_refs[i].set_head(NULL);
 127     _discovered_refs[i].set_length(0);
 128   }
 129 


 130   setup_policy(false /* default soft ref policy */);
 131 }
 132 
 133 #ifndef PRODUCT
 134 void ReferenceProcessor::verify_no_references_recorded() {
 135   guarantee(!_discovering_refs, "Discovering refs?");
 136   for (uint i = 0; i < _max_num_q * number_of_subclasses_of_ref(); i++) {
 137     guarantee(_discovered_refs[i].is_empty(),
 138               "Found non-empty discovered list at %u", i);
 139   }
 140 }
 141 #endif
 142 
 143 void ReferenceProcessor::weak_oops_do(OopClosure* f) {
 144   for (uint i = 0; i < _max_num_q * number_of_subclasses_of_ref(); i++) {
 145     if (UseCompressedOops) {
 146       f->do_oop((narrowOop*)_discovered_refs[i].adr_head());
 147     } else {
 148       f->do_oop((oop*)_discovered_refs[i].adr_head());
 149     }


 191   BoolObjectClosure*           is_alive,
 192   OopClosure*                  keep_alive,
 193   VoidClosure*                 complete_gc,
 194   AbstractRefProcTaskExecutor* task_executor,
 195   GCTimer*                     gc_timer) {
 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   ReferenceProcessorStats stats(
 212       total_count(_discoveredSoftRefs),
 213       total_count(_discoveredWeakRefs),
 214       total_count(_discoveredFinalRefs),
 215       total_count(_discoveredPhantomRefs));
 216 
 217   // Soft references
 218   {
 219     GCTraceTime(Debug, gc, ref) tt("SoftReference", gc_timer);
 220     process_discovered_reflist(_discoveredSoftRefs, _current_soft_ref_policy, true,
 221                                is_alive, keep_alive, complete_gc, task_executor);
 222   }
 223 
 224   update_soft_ref_master_clock();
 225 
 226   // Weak references
 227   {
 228     GCTraceTime(Debug, gc, ref) tt("WeakReference", gc_timer);
 229     process_discovered_reflist(_discoveredWeakRefs, NULL, true,
 230                                is_alive, keep_alive, complete_gc, task_executor);
 231   }
 232 
 233   // Final references
 234   {
 235     GCTraceTime(Debug, gc, ref) tt("FinalReference", gc_timer);
 236     process_discovered_reflist(_discoveredFinalRefs, NULL, false,
 237                                is_alive, keep_alive, complete_gc, task_executor);
 238   }
 239 
 240   // Phantom references
 241   {
 242     GCTraceTime(Debug, gc, ref) tt("PhantomReference", gc_timer);
 243     process_discovered_reflist(_discoveredPhantomRefs, NULL, true,
 244                                is_alive, keep_alive, complete_gc, task_executor);
 245   }
 246 
 247   // Weak global JNI references. It would make more sense (semantically) to
 248   // traverse these simultaneously with the regular weak references above, but
 249   // that is not how the JDK1.2 specification is. See #4126360. Native code can
 250   // thus use JNI weak references to circumvent the phantom references and
 251   // resurrect a "post-mortem" object.
 252   {
 253     GCTraceTime(Debug, gc, ref) tt("JNI Weak Reference", gc_timer);
 254     if (task_executor != NULL) {
 255       task_executor->set_single_threaded_mode();
 256     }
 257     process_phaseJNI(is_alive, keep_alive, complete_gc);
 258   }
 259 
 260   log_debug(gc, ref)("Ref Counts: Soft: " SIZE_FORMAT " Weak: " SIZE_FORMAT " Final: " SIZE_FORMAT " Phantom: " SIZE_FORMAT,
 261                      stats.soft_count(), stats.weak_count(), stats.final_count(), stats.phantom_count());
 262   log_develop_trace(gc, ref)("JNI Weak Reference count: " SIZE_FORMAT, count_jni_refs());
 263 
 264   return stats;
 265 }
 266 
 267 #ifndef PRODUCT
 268 // Calculate the number of jni handles.
 269 size_t ReferenceProcessor::count_jni_refs() {
 270   class CountHandleClosure: public OopClosure {
 271   private:
 272     size_t _count;
 273   public:
 274     CountHandleClosure(): _count(0) {}
 275     void do_oop(oop* unused)       { _count++; }
 276     void do_oop(narrowOop* unused) { ShouldNotReachHere(); }
 277     size_t count() { return _count; }
 278   };
 279   CountHandleClosure global_handle_count;
 280   JNIHandles::weak_oops_do(&global_handle_count);
 281   return global_handle_count.count();
 282 }
 283 #endif
 284 
 285 void ReferenceProcessor::process_phaseJNI(BoolObjectClosure* is_alive,
 286                                           OopClosure*        keep_alive,
 287                                           VoidClosure*       complete_gc) {
 288   JNIHandles::weak_oops_do(is_alive, keep_alive);
 289   complete_gc->do_void();
 290 }
 291 
 292 void ReferenceProcessor::enqueue_discovered_references(AbstractRefProcTaskExecutor* task_executor) {
 293   // Enqueue references that are not made active again, and
 294   // clear the decks for the next collection (cycle).
 295   enqueue_discovered_reflists(task_executor);
 296 
 297   // Stop treating discovered references specially.
 298   disable_discovery();
 299 }
 300 
 301 void ReferenceProcessor::enqueue_discovered_reflist(DiscoveredList& refs_list) {
 302   // Given a list of refs linked through the "discovered" field
 303   // (java.lang.ref.Reference.discovered), self-loop their "next" field
 304   // thus distinguishing them from active References, then
 305   // prepend them to the pending list.
 306   //
 307   // The Java threads will see the Reference objects linked together through
 308   // the discovered field. Instead of trying to do the write barrier updates
 309   // in all places in the reference processor where we manipulate the discovered
 310   // field we make sure to do the barrier here where we anyway iterate through
 311   // all linked Reference objects. Note that it is important to not dirty any
 312   // cards during reference processing since this will cause card table
 313   // verification to fail for G1.
 314   log_develop_trace(gc, ref)("ReferenceProcessor::enqueue_discovered_reflist list " INTPTR_FORMAT, p2i(&refs_list));
 315 


 333       // This is the last object.
 334       // Swap refs_list into pending list and set obj's
 335       // discovered to what we read from the pending list.
 336       oop old = Universe::swap_reference_pending_list(refs_list.head());
 337       java_lang_ref_Reference::set_discovered_raw(obj, old); // old may be NULL
 338       oopDesc::bs()->write_ref_field(java_lang_ref_Reference::discovered_addr(obj), old);
 339     }
 340   }
 341 }
 342 
 343 // Parallel enqueue task
 344 class RefProcEnqueueTask: public AbstractRefProcTaskExecutor::EnqueueTask {
 345 public:
 346   RefProcEnqueueTask(ReferenceProcessor& ref_processor,
 347                      DiscoveredList      discovered_refs[],
 348                      int                 n_queues)
 349     : EnqueueTask(ref_processor, discovered_refs, n_queues)
 350   { }
 351 
 352   virtual void work(unsigned int work_id) {


 353     assert(work_id < (unsigned int)_ref_processor.max_num_q(), "Index out-of-bounds");
 354     // Simplest first cut: static partitioning.
 355     int index = work_id;
 356     // The increment on "index" must correspond to the maximum number of queues
 357     // (n_queues) with which that ReferenceProcessor was created.  That
 358     // is because of the "clever" way the discovered references lists were
 359     // allocated and are indexed into.
 360     assert(_n_queues == (int) _ref_processor.max_num_q(), "Different number not expected");
 361     for (int j = 0;
 362          j < ReferenceProcessor::number_of_subclasses_of_ref();
 363          j++, index += _n_queues) {
 364       _ref_processor.enqueue_discovered_reflist(_refs_lists[index]);
 365       _refs_lists[index].set_head(NULL);
 366       _refs_lists[index].set_length(0);
 367     }
 368   }
 369 };
 370 
 371 // Enqueue references that are not made active again
 372 void ReferenceProcessor::enqueue_discovered_reflists(AbstractRefProcTaskExecutor* task_executor) {








 373   if (_processing_is_mt && task_executor != NULL) {
 374     // Parallel code
 375     RefProcEnqueueTask tsk(*this, _discovered_refs, _max_num_q);
 376     task_executor->execute(tsk);
 377   } else {
 378     // Serial code: call the parent class's implementation
 379     for (uint i = 0; i < _max_num_q * number_of_subclasses_of_ref(); i++) {
 380       enqueue_discovered_reflist(_discovered_refs[i]);
 381       _discovered_refs[i].set_head(NULL);
 382       _discovered_refs[i].set_length(0);
 383     }
 384   }
 385 }
 386 
 387 void DiscoveredListIterator::load_ptrs(DEBUG_ONLY(bool allow_null_referent)) {
 388   _discovered_addr = java_lang_ref_Reference::discovered_addr(_ref);
 389   oop discovered = java_lang_ref_Reference::discovered(_ref);
 390   assert(_discovered_addr && discovered->is_oop_or_null(),
 391          "Expected an oop or NULL for discovered field at " PTR_FORMAT, p2i(discovered));
 392   _next = discovered;


 452   while (iter.has_next()) {
 453     iter.load_ptrs(DEBUG_ONLY(!discovery_is_atomic() /* allow_null_referent */));
 454     bool referent_is_dead = (iter.referent() != NULL) && !iter.is_referent_alive();
 455     if (referent_is_dead &&
 456         !policy->should_clear_reference(iter.obj(), _soft_ref_timestamp_clock)) {
 457       log_develop_trace(gc, ref)("Dropping reference (" INTPTR_FORMAT ": %s"  ") by policy",
 458                                  p2i(iter.obj()), iter.obj()->klass()->internal_name());
 459       // Remove Reference object from list
 460       iter.remove();
 461       // keep the referent around
 462       iter.make_referent_alive();
 463       iter.move_to_next();
 464     } else {
 465       iter.next();
 466     }
 467   }
 468   // Close the reachable set
 469   complete_gc->do_void();
 470   log_develop_trace(gc, ref)(" Dropped " SIZE_FORMAT " dead Refs out of " SIZE_FORMAT " discovered Refs by policy, from list " INTPTR_FORMAT,
 471                              iter.removed(), iter.processed(), p2i(&refs_list));
 472     }
 473 
 474 // Traverse the list and remove any Refs that are not active, or
 475 // whose referents are either alive or NULL.
 476 void
 477 ReferenceProcessor::pp2_work(DiscoveredList&    refs_list,
 478                              BoolObjectClosure* is_alive,
 479                              OopClosure*        keep_alive) {
 480   assert(discovery_is_atomic(), "Error");
 481   DiscoveredListIterator iter(refs_list, keep_alive, is_alive);
 482   while (iter.has_next()) {
 483     iter.load_ptrs(DEBUG_ONLY(false /* allow_null_referent */));
 484     DEBUG_ONLY(oop next = java_lang_ref_Reference::next(iter.obj());)
 485     assert(next == NULL, "Should not discover inactive Reference");
 486     if (iter.is_referent_alive()) {
 487       log_develop_trace(gc, ref)("Dropping strongly reachable reference (" INTPTR_FORMAT ": %s)",
 488                                  p2i(iter.obj()), iter.obj()->klass()->internal_name());
 489       // The referent is reachable after all.
 490       // Remove Reference object from list.
 491       iter.remove();
 492       // Update the referent pointer as necessary: Note that this


 594     if ((i % _max_num_q) == 0) {
 595       log_develop_trace(gc, ref)("Abandoning %s discovered list", list_name(i));
 596     }
 597     clear_discovered_references(_discovered_refs[i]);
 598   }
 599 }
 600 
 601 class RefProcPhase1Task: public AbstractRefProcTaskExecutor::ProcessTask {
 602 public:
 603   RefProcPhase1Task(ReferenceProcessor& ref_processor,
 604                     DiscoveredList      refs_lists[],
 605                     ReferencePolicy*    policy,
 606                     bool                marks_oops_alive)
 607     : ProcessTask(ref_processor, refs_lists, marks_oops_alive),
 608       _policy(policy)
 609   { }
 610   virtual void work(unsigned int i, BoolObjectClosure& is_alive,
 611                     OopClosure& keep_alive,
 612                     VoidClosure& complete_gc)
 613   {


 614     _ref_processor.process_phase1(_refs_lists[i], _policy,
 615                                   &is_alive, &keep_alive, &complete_gc);
 616   }
 617 private:
 618   ReferencePolicy* _policy;
 619 };
 620 
 621 class RefProcPhase2Task: public AbstractRefProcTaskExecutor::ProcessTask {
 622 public:
 623   RefProcPhase2Task(ReferenceProcessor& ref_processor,
 624                     DiscoveredList      refs_lists[],
 625                     bool                marks_oops_alive)
 626     : ProcessTask(ref_processor, refs_lists, marks_oops_alive)
 627   { }
 628   virtual void work(unsigned int i, BoolObjectClosure& is_alive,
 629                     OopClosure& keep_alive,
 630                     VoidClosure& complete_gc)
 631   {


 632     _ref_processor.process_phase2(_refs_lists[i],
 633                                   &is_alive, &keep_alive, &complete_gc);
 634   }
 635 };
 636 
 637 class RefProcPhase3Task: public AbstractRefProcTaskExecutor::ProcessTask {
 638 public:
 639   RefProcPhase3Task(ReferenceProcessor& ref_processor,
 640                     DiscoveredList      refs_lists[],
 641                     bool                clear_referent,
 642                     bool                marks_oops_alive)
 643     : ProcessTask(ref_processor, refs_lists, marks_oops_alive),
 644       _clear_referent(clear_referent)
 645   { }
 646   virtual void work(unsigned int i, BoolObjectClosure& is_alive,
 647                     OopClosure& keep_alive,
 648                     VoidClosure& complete_gc)
 649   {


 650     _ref_processor.process_phase3(_refs_lists[i], _clear_referent,
 651                                   &is_alive, &keep_alive, &complete_gc);
 652   }
 653 private:
 654   bool _clear_referent;
 655 };
 656 
 657 #ifndef PRODUCT
 658 void ReferenceProcessor::log_reflist_counts(DiscoveredList ref_lists[], uint active_length, size_t total_refs) {
 659   if (!log_is_enabled(Trace, gc, ref)) {
 660     return;
 661   }
 662 
 663   stringStream st;
 664   for (uint i = 0; i < active_length; ++i) {
 665     st.print(SIZE_FORMAT " ", ref_lists[i].length());
 666   }
 667   log_develop_trace(gc, ref)("%s= " SIZE_FORMAT, st.as_string(), total_refs);
 668 #ifdef ASSERT
 669   for (uint i = active_length; i < _max_num_q; i++) {


 759   }
 760   log_reflist_counts(ref_lists, _num_q, balanced_total_refs);
 761   assert(total_refs == balanced_total_refs, "Balancing was incomplete");
 762 #endif
 763 }
 764 
 765 void ReferenceProcessor::balance_all_queues() {
 766   balance_queues(_discoveredSoftRefs);
 767   balance_queues(_discoveredWeakRefs);
 768   balance_queues(_discoveredFinalRefs);
 769   balance_queues(_discoveredPhantomRefs);
 770 }
 771 
 772 void ReferenceProcessor::process_discovered_reflist(
 773   DiscoveredList               refs_lists[],
 774   ReferencePolicy*             policy,
 775   bool                         clear_referent,
 776   BoolObjectClosure*           is_alive,
 777   OopClosure*                  keep_alive,
 778   VoidClosure*                 complete_gc,
 779   AbstractRefProcTaskExecutor* task_executor)

 780 {
 781   bool mt_processing = task_executor != NULL && _processing_is_mt;



 782   // If discovery used MT and a dynamic number of GC threads, then
 783   // the queues must be balanced for correctness if fewer than the
 784   // maximum number of queues were used.  The number of queue used
 785   // during discovery may be different than the number to be used
 786   // for processing so don't depend of _num_q < _max_num_q as part
 787   // of the test.
 788   bool must_balance = _discovery_is_mt;
 789 
 790   if ((mt_processing && ParallelRefProcBalancingEnabled) ||
 791       must_balance) {

 792     balance_queues(refs_lists);
 793   }
 794 
 795   // Phase 1 (soft refs only):
 796   // . Traverse the list and remove any SoftReferences whose
 797   //   referents are not alive, but that should be kept alive for
 798   //   policy reasons. Keep alive the transitive closure of all
 799   //   such referents.
 800   if (policy != NULL) {


 801     if (mt_processing) {
 802       RefProcPhase1Task phase1(*this, refs_lists, policy, true /*marks_oops_alive*/);
 803       task_executor->execute(phase1);
 804     } else {
 805       for (uint i = 0; i < _max_num_q; i++) {
 806         process_phase1(refs_lists[i], policy,
 807                        is_alive, keep_alive, complete_gc);
 808       }
 809     }
 810   } else { // policy == NULL
 811     assert(refs_lists != _discoveredSoftRefs,
 812            "Policy must be specified for soft references.");
 813   }
 814 
 815   // Phase 2:
 816   // . Traverse the list and remove any refs whose referents are alive.



 817   if (mt_processing) {
 818     RefProcPhase2Task phase2(*this, refs_lists, !discovery_is_atomic() /*marks_oops_alive*/);
 819     task_executor->execute(phase2);
 820   } else {
 821     for (uint i = 0; i < _max_num_q; i++) {
 822       process_phase2(refs_lists[i], is_alive, keep_alive, complete_gc);
 823     }
 824   }

 825 
 826   // Phase 3:
 827   // . Traverse the list and process referents as appropriate.



 828   if (mt_processing) {
 829     RefProcPhase3Task phase3(*this, refs_lists, clear_referent, true /*marks_oops_alive*/);
 830     task_executor->execute(phase3);
 831   } else {
 832     for (uint i = 0; i < _max_num_q; i++) {
 833       process_phase3(refs_lists[i], clear_referent,
 834                      is_alive, keep_alive, complete_gc);
 835     }
 836   }

 837 }
 838 
 839 inline DiscoveredList* ReferenceProcessor::get_discovered_list(ReferenceType rt) {
 840   uint id = 0;
 841   // Determine the queue index to use for this object.
 842   if (_discovery_is_mt) {
 843     // During a multi-threaded discovery phase,
 844     // each thread saves to its "own" list.
 845     Thread* thr = Thread::current();
 846     id = thr->as_Worker_thread()->id();
 847   } else {
 848     // single-threaded discovery, we save in round-robin
 849     // fashion to each of the lists.
 850     if (_processing_is_mt) {
 851       id = next_id();
 852     }
 853   }
 854   assert(id < _max_num_q, "Id is out-of-bounds id %u and max id %u)", id, _max_num_q);
 855 
 856   // Get the discovered queue to which we will add


1179       log_develop_trace(gc, ref)(" Dropped " SIZE_FORMAT " Refs out of " SIZE_FORMAT " Refs in discovered list " INTPTR_FORMAT,
1180         iter.removed(), iter.processed(), p2i(&refs_list));
1181     }
1182   )
1183 }
1184 
1185 const char* ReferenceProcessor::list_name(uint i) {
1186    assert(i <= _max_num_q * number_of_subclasses_of_ref(),
1187           "Out of bounds index");
1188 
1189    int j = i / _max_num_q;
1190    switch (j) {
1191      case 0: return "SoftRef";
1192      case 1: return "WeakRef";
1193      case 2: return "FinalRef";
1194      case 3: return "PhantomRef";
1195    }
1196    ShouldNotReachHere();
1197    return NULL;
1198 }
1199 
   1 /*
   2  * Copyright (c) 2001, 2017, 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  *


 110   _discovery_is_mt     = mt_discovery;
 111   _num_q               = MAX2(1U, mt_processing_degree);
 112   _max_num_q           = MAX2(_num_q, mt_discovery_degree);
 113   _discovered_refs     = NEW_C_HEAP_ARRAY(DiscoveredList,
 114             _max_num_q * number_of_subclasses_of_ref(), mtGC);
 115 
 116   if (_discovered_refs == NULL) {
 117     vm_exit_during_initialization("Could not allocated RefProc Array");
 118   }
 119   _discoveredSoftRefs    = &_discovered_refs[0];
 120   _discoveredWeakRefs    = &_discoveredSoftRefs[_max_num_q];
 121   _discoveredFinalRefs   = &_discoveredWeakRefs[_max_num_q];
 122   _discoveredPhantomRefs = &_discoveredFinalRefs[_max_num_q];
 123 
 124   // Initialize all entries to NULL
 125   for (uint i = 0; i < _max_num_q * number_of_subclasses_of_ref(); i++) {
 126     _discovered_refs[i].set_head(NULL);
 127     _discovered_refs[i].set_length(0);
 128   }
 129 
 130   _phase_times = new ReferenceProcessorPhaseTimes(_num_q, _processing_is_mt);
 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_q * 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_q * 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     }


 193   BoolObjectClosure*           is_alive,
 194   OopClosure*                  keep_alive,
 195   VoidClosure*                 complete_gc,
 196   AbstractRefProcTaskExecutor* task_executor,
 197   GCTimer*                     gc_timer) {
 198 
 199   assert(!enqueuing_is_done(), "If here enqueuing should not be complete");
 200   // Stop treating discovered references specially.
 201   disable_discovery();
 202 
 203   // If discovery was concurrent, someone could have modified
 204   // the value of the static field in the j.l.r.SoftReference
 205   // class that holds the soft reference timestamp clock using
 206   // reflection or Unsafe between when discovery was enabled and
 207   // now. Unconditionally update the static field in ReferenceProcessor
 208   // here so that we use the new value during processing of the
 209   // discovered soft refs.
 210 
 211   _soft_ref_timestamp_clock = java_lang_ref_SoftReference::clock();
 212 
 213   ReferenceProcessorStats stats(total_count(_discoveredSoftRefs),

 214                                 total_count(_discoveredWeakRefs),
 215                                 total_count(_discoveredFinalRefs),
 216                                 total_count(_discoveredPhantomRefs));
 217 
 218   // Soft references
 219   {
 220     RefProcPhaseTimesLogger tt("SoftReference", phase_times(), _discoveredSoftRefs, gc_timer);
 221     process_discovered_reflist(_discoveredSoftRefs, _current_soft_ref_policy, true,
 222                                is_alive, keep_alive, complete_gc, task_executor, gc_timer);
 223   }
 224 
 225   update_soft_ref_master_clock();
 226 
 227   // Weak references
 228   {
 229     RefProcPhaseTimesLogger tt("WeakReference", phase_times(), _discoveredWeakRefs, gc_timer);
 230     process_discovered_reflist(_discoveredWeakRefs, NULL, true,
 231                                is_alive, keep_alive, complete_gc, task_executor, gc_timer);
 232   }
 233 
 234   // Final references
 235   {
 236     RefProcPhaseTimesLogger tt("FinalReference", phase_times(), _discoveredFinalRefs, gc_timer);
 237     process_discovered_reflist(_discoveredFinalRefs, NULL, false,
 238                                is_alive, keep_alive, complete_gc, task_executor, gc_timer);
 239   }
 240 
 241   // Phantom references
 242   {
 243     RefProcPhaseTimesLogger tt("PhantomReference", phase_times(), _discoveredPhantomRefs, gc_timer);
 244     process_discovered_reflist(_discoveredPhantomRefs, NULL, true,
 245                                is_alive, keep_alive, complete_gc, task_executor, gc_timer);
 246   }
 247 
 248   // Weak global JNI references. It would make more sense (semantically) to
 249   // traverse these simultaneously with the regular weak references above, but
 250   // that is not how the JDK1.2 specification is. See #4126360. Native code can
 251   // thus use JNI weak references to circumvent the phantom references and
 252   // resurrect a "post-mortem" object.
 253   {
 254     GCTraceTime(Debug, gc, ref) tt("JNI Weak Reference", gc_timer);
 255     if (task_executor != NULL) {
 256       task_executor->set_single_threaded_mode();
 257     }
 258     process_phaseJNI(is_alive, keep_alive, complete_gc);
 259   }
 260 


 261   log_develop_trace(gc, ref)("JNI Weak Reference count: " SIZE_FORMAT, count_jni_refs());
 262 
 263   return stats;
 264 }
 265 
 266 #ifndef PRODUCT
 267 // Calculate the number of jni handles.
 268 size_t ReferenceProcessor::count_jni_refs() {
 269   class CountHandleClosure: public OopClosure {
 270   private:
 271     size_t _count;
 272   public:
 273     CountHandleClosure(): _count(0) {}
 274     void do_oop(oop* unused)       { _count++; }
 275     void do_oop(narrowOop* unused) { ShouldNotReachHere(); }
 276     size_t count() { return _count; }
 277   };
 278   CountHandleClosure global_handle_count;
 279   JNIHandles::weak_oops_do(&global_handle_count);
 280   return global_handle_count.count();
 281 }
 282 #endif
 283 
 284 void ReferenceProcessor::process_phaseJNI(BoolObjectClosure* is_alive,
 285                                           OopClosure*        keep_alive,
 286                                           VoidClosure*       complete_gc) {
 287   JNIHandles::weak_oops_do(is_alive, keep_alive);
 288   complete_gc->do_void();
 289 }
 290 
 291 void ReferenceProcessor::enqueue_discovered_references(AbstractRefProcTaskExecutor* task_executor, GCTimer* gc_timer) {
 292   // Enqueue references that are not made active again, and
 293   // clear the decks for the next collection (cycle).
 294   enqueue_discovered_reflists(task_executor, gc_timer);
 295 
 296   // Stop treating discovered references specially.
 297   disable_discovery();
 298 }
 299 
 300 void ReferenceProcessor::enqueue_discovered_reflist(DiscoveredList& refs_list) {
 301   // Given a list of refs linked through the "discovered" field
 302   // (java.lang.ref.Reference.discovered), self-loop their "next" field
 303   // thus distinguishing them from active References, then
 304   // prepend them to the pending list.
 305   //
 306   // The Java threads will see the Reference objects linked together through
 307   // the discovered field. Instead of trying to do the write barrier updates
 308   // in all places in the reference processor where we manipulate the discovered
 309   // field we make sure to do the barrier here where we anyway iterate through
 310   // all linked Reference objects. Note that it is important to not dirty any
 311   // cards during reference processing since this will cause card table
 312   // verification to fail for G1.
 313   log_develop_trace(gc, ref)("ReferenceProcessor::enqueue_discovered_reflist list " INTPTR_FORMAT, p2i(&refs_list));
 314 


 332       // This is the last object.
 333       // Swap refs_list into pending list and set obj's
 334       // discovered to what we read from the pending list.
 335       oop old = Universe::swap_reference_pending_list(refs_list.head());
 336       java_lang_ref_Reference::set_discovered_raw(obj, old); // old may be NULL
 337       oopDesc::bs()->write_ref_field(java_lang_ref_Reference::discovered_addr(obj), old);
 338     }
 339   }
 340 }
 341 
 342 // Parallel enqueue task
 343 class RefProcEnqueueTask: public AbstractRefProcTaskExecutor::EnqueueTask {
 344 public:
 345   RefProcEnqueueTask(ReferenceProcessor& ref_processor,
 346                      DiscoveredList      discovered_refs[],
 347                      int                 n_queues)
 348     : EnqueueTask(ref_processor, discovered_refs, n_queues)
 349   { }
 350 
 351   virtual void work(unsigned int work_id) {
 352     RefProcWorkerTimeTracker tt(_ref_processor.phase_times()->worker_time_sec(ReferenceProcessorPhaseTimes::RefEnqueue), work_id);
 353 
 354     assert(work_id < (unsigned int)_ref_processor.max_num_q(), "Index out-of-bounds");
 355     // Simplest first cut: static partitioning.
 356     int index = work_id;
 357     // The increment on "index" must correspond to the maximum number of queues
 358     // (n_queues) with which that ReferenceProcessor was created.  That
 359     // is because of the "clever" way the discovered references lists were
 360     // allocated and are indexed into.
 361     assert(_n_queues == (int) _ref_processor.max_num_q(), "Different number not expected");
 362     for (int j = 0;
 363          j < ReferenceProcessor::number_of_subclasses_of_ref();
 364          j++, index += _n_queues) {
 365       _ref_processor.enqueue_discovered_reflist(_refs_lists[index]);
 366       _refs_lists[index].set_head(NULL);
 367       _refs_lists[index].set_length(0);
 368     }
 369   }
 370 };
 371 
 372 // Enqueue references that are not made active again
 373 void ReferenceProcessor::enqueue_discovered_reflists(AbstractRefProcTaskExecutor* task_executor, GCTimer* gc_timer) {
 374 
 375   ReferenceProcessorStats stats(total_count(_discoveredSoftRefs),
 376                                 total_count(_discoveredWeakRefs),
 377                                 total_count(_discoveredFinalRefs),
 378                                 total_count(_discoveredPhantomRefs));
 379 
 380   RefProcEnqueueTimeLogger tt(phase_times(), stats, gc_timer);
 381 
 382   if (_processing_is_mt && task_executor != NULL) {
 383     // Parallel code
 384     RefProcEnqueueTask tsk(*this, _discovered_refs, _max_num_q);
 385     task_executor->execute(tsk);
 386   } else {
 387     // Serial code: call the parent class's implementation
 388     for (uint i = 0; i < _max_num_q * number_of_subclasses_of_ref(); i++) {
 389       enqueue_discovered_reflist(_discovered_refs[i]);
 390       _discovered_refs[i].set_head(NULL);
 391       _discovered_refs[i].set_length(0);
 392     }
 393   }
 394 }
 395 
 396 void DiscoveredListIterator::load_ptrs(DEBUG_ONLY(bool allow_null_referent)) {
 397   _discovered_addr = java_lang_ref_Reference::discovered_addr(_ref);
 398   oop discovered = java_lang_ref_Reference::discovered(_ref);
 399   assert(_discovered_addr && discovered->is_oop_or_null(),
 400          "Expected an oop or NULL for discovered field at " PTR_FORMAT, p2i(discovered));
 401   _next = discovered;


 461   while (iter.has_next()) {
 462     iter.load_ptrs(DEBUG_ONLY(!discovery_is_atomic() /* allow_null_referent */));
 463     bool referent_is_dead = (iter.referent() != NULL) && !iter.is_referent_alive();
 464     if (referent_is_dead &&
 465         !policy->should_clear_reference(iter.obj(), _soft_ref_timestamp_clock)) {
 466       log_develop_trace(gc, ref)("Dropping reference (" INTPTR_FORMAT ": %s"  ") by policy",
 467                                  p2i(iter.obj()), iter.obj()->klass()->internal_name());
 468       // Remove Reference object from list
 469       iter.remove();
 470       // keep the referent around
 471       iter.make_referent_alive();
 472       iter.move_to_next();
 473     } else {
 474       iter.next();
 475     }
 476   }
 477   // Close the reachable set
 478   complete_gc->do_void();
 479   log_develop_trace(gc, ref)(" Dropped " SIZE_FORMAT " dead Refs out of " SIZE_FORMAT " discovered Refs by policy, from list " INTPTR_FORMAT,
 480                              iter.removed(), iter.processed(), p2i(&refs_list));
 481 }
 482 
 483 // Traverse the list and remove any Refs that are not active, or
 484 // whose referents are either alive or NULL.
 485 void
 486 ReferenceProcessor::pp2_work(DiscoveredList&    refs_list,
 487                              BoolObjectClosure* is_alive,
 488                              OopClosure*        keep_alive) {
 489   assert(discovery_is_atomic(), "Error");
 490   DiscoveredListIterator iter(refs_list, keep_alive, is_alive);
 491   while (iter.has_next()) {
 492     iter.load_ptrs(DEBUG_ONLY(false /* allow_null_referent */));
 493     DEBUG_ONLY(oop next = java_lang_ref_Reference::next(iter.obj());)
 494     assert(next == NULL, "Should not discover inactive Reference");
 495     if (iter.is_referent_alive()) {
 496       log_develop_trace(gc, ref)("Dropping strongly reachable reference (" INTPTR_FORMAT ": %s)",
 497                                  p2i(iter.obj()), iter.obj()->klass()->internal_name());
 498       // The referent is reachable after all.
 499       // Remove Reference object from list.
 500       iter.remove();
 501       // Update the referent pointer as necessary: Note that this


 603     if ((i % _max_num_q) == 0) {
 604       log_develop_trace(gc, ref)("Abandoning %s discovered list", list_name(i));
 605     }
 606     clear_discovered_references(_discovered_refs[i]);
 607   }
 608 }
 609 
 610 class RefProcPhase1Task: public AbstractRefProcTaskExecutor::ProcessTask {
 611 public:
 612   RefProcPhase1Task(ReferenceProcessor& ref_processor,
 613                     DiscoveredList      refs_lists[],
 614                     ReferencePolicy*    policy,
 615                     bool                marks_oops_alive)
 616     : ProcessTask(ref_processor, refs_lists, marks_oops_alive),
 617       _policy(policy)
 618   { }
 619   virtual void work(unsigned int i, BoolObjectClosure& is_alive,
 620                     OopClosure& keep_alive,
 621                     VoidClosure& complete_gc)
 622   {
 623     RefProcWorkerTimeTracker tt(_ref_processor.phase_times()->worker_time_sec(ReferenceProcessorPhaseTimes::RefPhase1), i);
 624 
 625     _ref_processor.process_phase1(_refs_lists[i], _policy,
 626                                   &is_alive, &keep_alive, &complete_gc);
 627   }
 628 private:
 629   ReferencePolicy* _policy;
 630 };
 631 
 632 class RefProcPhase2Task: public AbstractRefProcTaskExecutor::ProcessTask {
 633 public:
 634   RefProcPhase2Task(ReferenceProcessor& ref_processor,
 635                     DiscoveredList      refs_lists[],
 636                     bool                marks_oops_alive)
 637     : ProcessTask(ref_processor, refs_lists, marks_oops_alive)
 638   { }
 639   virtual void work(unsigned int i, BoolObjectClosure& is_alive,
 640                     OopClosure& keep_alive,
 641                     VoidClosure& complete_gc)
 642   {
 643     RefProcWorkerTimeTracker tt(_ref_processor.phase_times()->worker_time_sec(ReferenceProcessorPhaseTimes::RefPhase2), i);
 644 
 645     _ref_processor.process_phase2(_refs_lists[i],
 646                                   &is_alive, &keep_alive, &complete_gc);
 647   }
 648 };
 649 
 650 class RefProcPhase3Task: public AbstractRefProcTaskExecutor::ProcessTask {
 651 public:
 652   RefProcPhase3Task(ReferenceProcessor& ref_processor,
 653                     DiscoveredList      refs_lists[],
 654                     bool                clear_referent,
 655                     bool                marks_oops_alive)
 656     : ProcessTask(ref_processor, refs_lists, marks_oops_alive),
 657       _clear_referent(clear_referent)
 658   { }
 659   virtual void work(unsigned int i, BoolObjectClosure& is_alive,
 660                     OopClosure& keep_alive,
 661                     VoidClosure& complete_gc)
 662   {
 663     RefProcWorkerTimeTracker tt(_ref_processor.phase_times()->worker_time_sec(ReferenceProcessorPhaseTimes::RefPhase3), i);
 664 
 665     _ref_processor.process_phase3(_refs_lists[i], _clear_referent,
 666                                   &is_alive, &keep_alive, &complete_gc);
 667   }
 668 private:
 669   bool _clear_referent;
 670 };
 671 
 672 #ifndef PRODUCT
 673 void ReferenceProcessor::log_reflist_counts(DiscoveredList ref_lists[], uint active_length, size_t total_refs) {
 674   if (!log_is_enabled(Trace, gc, ref)) {
 675     return;
 676   }
 677 
 678   stringStream st;
 679   for (uint i = 0; i < active_length; ++i) {
 680     st.print(SIZE_FORMAT " ", ref_lists[i].length());
 681   }
 682   log_develop_trace(gc, ref)("%s= " SIZE_FORMAT, st.as_string(), total_refs);
 683 #ifdef ASSERT
 684   for (uint i = active_length; i < _max_num_q; i++) {


 774   }
 775   log_reflist_counts(ref_lists, _num_q, balanced_total_refs);
 776   assert(total_refs == balanced_total_refs, "Balancing was incomplete");
 777 #endif
 778 }
 779 
 780 void ReferenceProcessor::balance_all_queues() {
 781   balance_queues(_discoveredSoftRefs);
 782   balance_queues(_discoveredWeakRefs);
 783   balance_queues(_discoveredFinalRefs);
 784   balance_queues(_discoveredPhantomRefs);
 785 }
 786 
 787 void ReferenceProcessor::process_discovered_reflist(
 788   DiscoveredList               refs_lists[],
 789   ReferencePolicy*             policy,
 790   bool                         clear_referent,
 791   BoolObjectClosure*           is_alive,
 792   OopClosure*                  keep_alive,
 793   VoidClosure*                 complete_gc,
 794   AbstractRefProcTaskExecutor* task_executor,
 795   GCTimer*                     gc_timer)
 796 {
 797   bool mt_processing = task_executor != NULL && _processing_is_mt;
 798 
 799   phase_times()->set_processing_is_mt(mt_processing);
 800 
 801   // If discovery used MT and a dynamic number of GC threads, then
 802   // the queues must be balanced for correctness if fewer than the
 803   // maximum number of queues were used.  The number of queue used
 804   // during discovery may be different than the number to be used
 805   // for processing so don't depend of _num_q < _max_num_q as part
 806   // of the test.
 807   bool must_balance = _discovery_is_mt;
 808 
 809   if ((mt_processing && ParallelRefProcBalancingEnabled) ||
 810       must_balance) {
 811     RefProcBalanceQueuesTimeTracker tt(phase_times(), gc_timer);
 812     balance_queues(refs_lists);
 813   }
 814 
 815   // Phase 1 (soft refs only):
 816   // . Traverse the list and remove any SoftReferences whose
 817   //   referents are not alive, but that should be kept alive for
 818   //   policy reasons. Keep alive the transitive closure of all
 819   //   such referents.
 820   if (policy != NULL) {
 821     RefProcPhaseTimeTracker tt(ReferenceProcessorPhaseTimes::RefPhase1, phase_times(), gc_timer);
 822 
 823     if (mt_processing) {
 824       RefProcPhase1Task phase1(*this, refs_lists, policy, true /*marks_oops_alive*/);
 825       task_executor->execute(phase1);
 826     } else {
 827       for (uint i = 0; i < _max_num_q; i++) {
 828         process_phase1(refs_lists[i], policy,
 829                        is_alive, keep_alive, complete_gc);
 830       }
 831     }
 832   } else { // policy == NULL
 833     assert(refs_lists != _discoveredSoftRefs,
 834            "Policy must be specified for soft references.");
 835   }
 836 
 837   // Phase 2:
 838   // . Traverse the list and remove any refs whose referents are alive.
 839   {
 840     RefProcPhaseTimeTracker tt(ReferenceProcessorPhaseTimes::RefPhase2, phase_times(), gc_timer);
 841 
 842     if (mt_processing) {
 843       RefProcPhase2Task phase2(*this, refs_lists, !discovery_is_atomic() /*marks_oops_alive*/);
 844       task_executor->execute(phase2);
 845     } else {
 846       for (uint i = 0; i < _max_num_q; i++) {
 847         process_phase2(refs_lists[i], is_alive, keep_alive, complete_gc);
 848       }
 849     }
 850   }
 851 
 852   // Phase 3:
 853   // . Traverse the list and process referents as appropriate.
 854   {
 855     RefProcPhaseTimeTracker tt(ReferenceProcessorPhaseTimes::RefPhase3, phase_times(), gc_timer);
 856 
 857     if (mt_processing) {
 858       RefProcPhase3Task phase3(*this, refs_lists, clear_referent, true /*marks_oops_alive*/);
 859       task_executor->execute(phase3);
 860     } else {
 861       for (uint i = 0; i < _max_num_q; i++) {
 862         process_phase3(refs_lists[i], clear_referent,
 863                        is_alive, keep_alive, complete_gc);
 864       }
 865     }
 866   }
 867 }
 868 
 869 inline DiscoveredList* ReferenceProcessor::get_discovered_list(ReferenceType rt) {
 870   uint id = 0;
 871   // Determine the queue index to use for this object.
 872   if (_discovery_is_mt) {
 873     // During a multi-threaded discovery phase,
 874     // each thread saves to its "own" list.
 875     Thread* thr = Thread::current();
 876     id = thr->as_Worker_thread()->id();
 877   } else {
 878     // single-threaded discovery, we save in round-robin
 879     // fashion to each of the lists.
 880     if (_processing_is_mt) {
 881       id = next_id();
 882     }
 883   }
 884   assert(id < _max_num_q, "Id is out-of-bounds id %u and max id %u)", id, _max_num_q);
 885 
 886   // Get the discovered queue to which we will add


1209       log_develop_trace(gc, ref)(" Dropped " SIZE_FORMAT " Refs out of " SIZE_FORMAT " Refs in discovered list " INTPTR_FORMAT,
1210         iter.removed(), iter.processed(), p2i(&refs_list));
1211     }
1212   )
1213 }
1214 
1215 const char* ReferenceProcessor::list_name(uint i) {
1216    assert(i <= _max_num_q * number_of_subclasses_of_ref(),
1217           "Out of bounds index");
1218 
1219    int j = i / _max_num_q;
1220    switch (j) {
1221      case 0: return "SoftRef";
1222      case 1: return "WeakRef";
1223      case 2: return "FinalRef";
1224      case 3: return "PhantomRef";
1225    }
1226    ShouldNotReachHere();
1227    return NULL;
1228 }

< prev index next >