File: vtkGarbageCollector.cxx

package info (click to toggle)
vtk7 7.1.1%2Bdfsg2-8
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 127,396 kB
  • sloc: cpp: 1,539,584; ansic: 124,382; python: 78,038; tcl: 47,013; xml: 8,142; yacc: 5,040; java: 4,439; perl: 3,132; lex: 1,926; sh: 1,500; makefile: 126; objc: 83
file content (1077 lines) | stat: -rw-r--r-- 34,088 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkGarbageCollector.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkGarbageCollector.h"

#include "vtkMultiThreader.h"
#include "vtkObjectFactory.h"
#include "vtkSmartPointerBase.h"

#include <sstream>
#include <queue>
#include <stack>
#include <vector>

// Leave the hashing version off for now.
#define VTK_GARBAGE_COLLECTOR_HASH 0

#if VTK_GARBAGE_COLLECTOR_HASH
# include <vtksys/hash_set.hxx>
# include <vtksys/hash_map.hxx>
#else
# include <map>
# include <set>
#endif

#include <cassert>

vtkStandardNewMacro(vtkGarbageCollector);

#if VTK_GARBAGE_COLLECTOR_HASH
struct vtkGarbageCollectorHash
{
  size_t operator()(void* p) const { return reinterpret_cast<size_t>(p); }
};
#endif

class vtkGarbageCollectorSingleton;

//----------------------------------------------------------------------------
// The garbage collector singleton.  In order to support delayed
// collection vtkObjectBase::UnRegister passes references to the
// singleton instead of decrementing the reference count.  At some
// point collection occurs and accounts for these references.  This
// MUST be default initialized to zero by the compiler and is
// therefore not initialized here.  The ClassInitialize and
// ClassFinalize methods handle this instance.
static vtkGarbageCollectorSingleton* vtkGarbageCollectorSingletonInstance;

//----------------------------------------------------------------------------
// Global debug setting.  This flag specifies whether a collector
// should print debugging output.  This must be default initialized to
// false by the compiler and is therefore not initialized here.  The
// ClassInitialize and ClassFinalize methods handle it.
static bool vtkGarbageCollectorGlobalDebugFlag;

//----------------------------------------------------------------------------
// The thread identifier of the main thread.  Delayed garbage
// collection is supported only for objects in the main thread.  This
// is initialized when the program loads.  All garbage collection
// calls test whether they are called from this thread.  If not, no
// references are accepted by the singleton.  This must be default
// initialized to zero by the compiler and is therefore not
// initialized here.  The ClassInitialize and ClassFinalize methods
// handle it.
static vtkMultiThreaderIDType vtkGarbageCollectorMainThread;

//----------------------------------------------------------------------------
vtkGarbageCollector::vtkGarbageCollector()
{
}

//----------------------------------------------------------------------------
vtkGarbageCollector::~vtkGarbageCollector()
{
  this->SetReferenceCount(0);
}

//----------------------------------------------------------------------------
void vtkGarbageCollector::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);
}

//----------------------------------------------------------------------------
void vtkGarbageCollector::SetGlobalDebugFlag(bool flag)
{
  vtkGarbageCollectorGlobalDebugFlag = flag;
}

//----------------------------------------------------------------------------
bool vtkGarbageCollector::GetGlobalDebugFlag()
{
  return vtkGarbageCollectorGlobalDebugFlag;
}

//----------------------------------------------------------------------------
// Friendship interface listing non-public methods the garbage
// collector can call on vtkObjectBase.
class vtkGarbageCollectorToObjectBaseFriendship
{
public:
  static void ReportReferences(vtkGarbageCollector* self, vtkObjectBase* obj)
  {
    obj->ReportReferences(self);
  }
  static void RegisterBase(vtkObjectBase* obj)
  {
    // Call vtkObjectBase::RegisterInternal directly to make sure the
    // object does not try to report the call back to the garbage
    // collector and no debugging output is shown.
    obj->vtkObjectBase::RegisterInternal(0, 0);
  }
  static void UnRegisterBase(vtkObjectBase* obj)
  {
    // Call vtkObjectBase::UnRegisterInternal directly to make sure
    // the object does not try to report the call back to the garbage
    // collector and no debugging output is shown.
    obj->vtkObjectBase::UnRegisterInternal(0, 0);
  }
  static void Register(vtkObjectBase* obj, vtkObjectBase* from)
  {
    // Call RegisterInternal directly to make sure the object does not
    // try to report the call back to the garbage collector.
    obj->RegisterInternal(from, 0);
  }
  static void UnRegister(vtkObjectBase* obj, vtkObjectBase* from)
  {
    // Call UnRegisterInternal directly to make sure the object does
    // not try to report the call back to the garbage collector.
    obj->UnRegisterInternal(from, 0);
  }
};

//----------------------------------------------------------------------------
// Function to test whether caller is the main thread.
static int vtkGarbageCollectorIsMainThread()
{
  return
    vtkMultiThreader::ThreadsEqual(vtkGarbageCollectorMainThread,
                                   vtkMultiThreader::GetCurrentThreadID());
}

//----------------------------------------------------------------------------
// Singleton to hold discarded references.
class vtkGarbageCollectorSingleton
{
public:
  vtkGarbageCollectorSingleton();
  ~vtkGarbageCollectorSingleton();

  // Internal implementation of vtkGarbageCollector::GiveReference.
  int GiveReference(vtkObjectBase* obj);

  // Internal implementation of vtkGarbageCollector::TakeReference.
  int TakeReference(vtkObjectBase* obj);

  // Called by GiveReference to decide whether to accept a reference.
  vtkTypeBool CheckAccept();

  // Push/Pop deferred collection.
  void DeferredCollectionPush();
  void DeferredCollectionPop();

  // Map from object to number of stored references.
#if VTK_GARBAGE_COLLECTOR_HASH
  typedef vtksys::hash_map<vtkObjectBase*, int, vtkGarbageCollectorHash>
    ReferencesType;
#else
  typedef std::map<vtkObjectBase*, int> ReferencesType;
#endif
  ReferencesType References;

  // The number of references stored in the map.
  int TotalNumberOfReferences;

  // The number of times DeferredCollectionPush has been called not
  // matched by a DeferredCollectionPop.
  int DeferredCollectionCount;
};

//----------------------------------------------------------------------------
// Internal implementation subclass.
class vtkGarbageCollectorImpl: public vtkGarbageCollector
{
public:
  vtkTypeMacro(vtkGarbageCollectorImpl, vtkGarbageCollector);

  vtkGarbageCollectorImpl();
  ~vtkGarbageCollectorImpl() VTK_OVERRIDE;

  // Description:
  // Prevent normal vtkObject reference counting behavior.
  void Register(vtkObjectBase*) VTK_OVERRIDE;

  // Description:
  // Prevent normal vtkObject reference counting behavior.
  void UnRegister(vtkObjectBase*) VTK_OVERRIDE;

  // Perform a collection check.
  void CollectInternal(vtkObjectBase* root);


// Sun's compiler is broken and does not allow access to protected members from
// nested class
// protected:
  //--------------------------------------------------------------------------
  // Internal data structure types.

#if VTK_GARBAGE_COLLECTOR_HASH
  typedef vtksys::hash_map<vtkObjectBase*, int, vtkGarbageCollectorHash>
    ReferencesType;
#else
  typedef std::map<vtkObjectBase*, int> ReferencesType;
#endif
  struct ComponentType;

  struct Entry;
  struct EntryEdge
  {
    Entry* Reference;
    void* Pointer;
    EntryEdge(Entry* r, void* p): Reference(r), Pointer(p) {}
  };

  // Store garbage collection entries keyed by object.
  struct Entry
  {
    Entry(vtkObjectBase* obj): Object(obj), Root(0), Component(0),
                               VisitOrder(0), Count(0), GarbageCount(0),
                               References() {}
    ~Entry() { assert(this->GarbageCount == 0); }

    // The object corresponding to this entry.
    vtkObjectBase* Object;

    // The candidate root for the component containing this object.
    Entry* Root;

    // The component to which the object is assigned, if any.
    ComponentType* Component;

    // Mark the order in which object's are visited by Tarjan's algorithm.
    int VisitOrder;

    // The number of references from outside the component not
    // counting the garbage collector references.
    int Count;

    // The number of references held by the garbage collector.
    int GarbageCount;

    // The list of references reported by this entry's object.
    typedef std::vector<EntryEdge> ReferencesType;
    ReferencesType References;
  };

  // Compare entries by object pointer for quick lookup.
#if VTK_GARBAGE_COLLECTOR_HASH
  struct EntryCompare
  {
    bool operator()(Entry* l, Entry* r) const
      { return l->Object == r->Object; }
  };
  struct EntryHash
  {
    size_t operator()(Entry* e) const
      { return e?reinterpret_cast<size_t>(e->Object):0; }
  };
#else
  struct EntryCompare
  {
    std::less<vtkObjectBase*> Compare;
    bool operator()(Entry* l, Entry* r) const
      { return Compare(l->Object, r->Object); }
  };
#endif

  // Represent a strongly connected component of the reference graph.
  typedef std::vector<Entry*> ComponentBase;
  struct ComponentType: public ComponentBase
  {
    typedef ComponentBase::iterator iterator;
    ComponentType(): NetCount(0), Identifier(0) {}
    ~ComponentType()
      { for(iterator i = begin(), iend = end(); i != iend; ++i) { (*i)->Component = 0; } }

    // The net reference count of the component.
    int NetCount;

    // The component identifier.
    int Identifier;
  };

  //--------------------------------------------------------------------------
  // Internal data objects.

  // The set of objects that have been visited.
#if VTK_GARBAGE_COLLECTOR_HASH
  typedef vtksys::hash_set<Entry*, EntryHash, EntryCompare> VisitedType;
#else
  typedef std::set<Entry*, EntryCompare> VisitedType;
#endif
  VisitedType Visited;

  // Count the number of components found to give each an identifier
  // for use in debugging messages.
  int NumberOfComponents;

  // The set of components found that have not yet leaked.
#if VTK_GARBAGE_COLLECTOR_HASH
  typedef vtksys::hash_set<ComponentType*, vtkGarbageCollectorHash>
    ComponentsType;
#else
  typedef std::set<ComponentType*> ComponentsType;
#endif
  ComponentsType ReferencedComponents;

  // Queue leaked components for deletion.
  std::queue<ComponentType*> LeakedComponents;

  // The stack of objects forming the connected components.  This is
  // used in the implementation of Tarjan's algorithm.
  std::stack<Entry*> Stack;

  // The object whose references are currently being traced by
  // Tarjan's algorithm.  Used during the ReportReferences callback.
  Entry* Current;

  // Count for visit order of Tarjan's algorithm.
  int VisitCount;

  // The singleton instance from which to take references when passing
  // references to the entries.
  vtkGarbageCollectorSingleton* Singleton;

  //--------------------------------------------------------------------------
  // Internal implementation methods.

  // Walk the reference graph using Tarjan's algorithm to identify
  // strongly connected components.
  void FindComponents(vtkObjectBase* root);

  // Get the entry for the given object.  This may visit the object.
  Entry* MaybeVisit(vtkObjectBase*);

  // Node visitor for Tarjan's algorithm.
  Entry* VisitTarjan(vtkObjectBase*);

  // Callback from objects to report references.
  void Report(vtkObjectBase* obj, void* ptr);
  void Report(vtkObjectBase* obj, void* ptr, const char* desc) VTK_OVERRIDE;

  // Collect the objects of the given leaked component.
  void CollectComponent(ComponentType* c);

  // Print the given component as a debugging message.
  void PrintComponent(ComponentType* c);

  // Subtract references the component holds to itself.
  void SubtractInternalReferences(ComponentType* c);

  // Subtract references the component holds to other components.
  void SubtractExternalReferences(ComponentType* c);

  // Subtract one reference from the given entry.  If the entry's
  // component is left with no references, it is queued as a leaked
  // component.
  void SubtractReference(Entry* e);

  // Transfer references from the garbage collector to the entry for
  // its object.
  void PassReferencesToEntry(Entry* e);

  // Flush all collector references to the object in an entry.
  void FlushEntryReferences(Entry* e);

private:
  vtkGarbageCollectorImpl(const vtkGarbageCollectorImpl&) VTK_DELETE_FUNCTION;
  void operator=(const vtkGarbageCollectorImpl&) VTK_DELETE_FUNCTION;
};

//----------------------------------------------------------------------------
vtkGarbageCollectorImpl::vtkGarbageCollectorImpl()
{
  // Set debugging state.
  this->SetDebug(vtkGarbageCollectorGlobalDebugFlag);

  // Take references from the singleton only in the main thread.
  if(vtkGarbageCollectorIsMainThread())
  {
    this->Singleton = vtkGarbageCollectorSingletonInstance;
  }
  else
  {
    this->Singleton = 0;
  }

  // Initialize reference graph walk implementation.
  this->VisitCount = 0;
  this->Current = 0;
  this->NumberOfComponents = 0;
}

//----------------------------------------------------------------------------
vtkGarbageCollectorImpl::~vtkGarbageCollectorImpl()
{
  // The collector implementation should have left these empty.
  assert(this->Current == 0);
  assert(this->Stack.empty());
  assert(this->LeakedComponents.empty());

  // Clear component list.
  for(ComponentsType::iterator c = this->ReferencedComponents.begin(), cend = this->ReferencedComponents.end();
      c != cend; ++c)
  {
    delete *c;
  }
  this->ReferencedComponents.clear();

  // Clear visited list.
  for(VisitedType::iterator v = this->Visited.begin(), vend = this->Visited.end();
      v != vend;)
  {
    // Increment the iterator before deleting because the hash table
    // compare function dereferences the pointer.
    delete *v++;
  }
  this->Visited.clear();

  // Disable debugging to avoid destruction message.
  this->SetDebug(false);
}

//----------------------------------------------------------------------------
void vtkGarbageCollectorImpl::Register(vtkObjectBase*)
{
}

//----------------------------------------------------------------------------
void vtkGarbageCollectorImpl::UnRegister(vtkObjectBase*)
{
}

//----------------------------------------------------------------------------
void vtkGarbageCollectorImpl::CollectInternal(vtkObjectBase* root)
{
  // Identify strong components.
  this->FindComponents(root);

  // Delete all the leaked components.
  while(!this->LeakedComponents.empty())
  {
    // Get the next leaked component.
    ComponentType* c = this->LeakedComponents.front();
    this->LeakedComponents.pop();

    // Subtract this component's references to other components.  This
    // may cause others to be queued.
    this->SubtractExternalReferences(c);

    // Collect the members of this component.
    this->CollectComponent(c);

    // We are done with this component.
    delete c;
  }

#ifndef NDEBUG
  // Print remaining referenced components for debugging.
  for(ComponentsType::iterator i = this->ReferencedComponents.begin(), iend = this->ReferencedComponents.end();
      i != iend; ++i)
  {
    this->PrintComponent(*i);
  }
#endif

  // Flush remaining references owned by entries in referenced
  // components.
  for(ComponentsType::iterator c = this->ReferencedComponents.begin(), cend = this->ReferencedComponents.end();
      c != cend; ++c)
  {
    for(ComponentType::iterator j = (*c)->begin(), jend = (*c)->end();
        j != jend; ++j)
    {
      this->FlushEntryReferences(*j);
    }
  }
}

//----------------------------------------------------------------------------
void vtkGarbageCollectorImpl::FindComponents(vtkObjectBase* root)
{
  // Walk the references from the given object, if any.
  if(root)
  {
    this->MaybeVisit(root);
  }
}

//----------------------------------------------------------------------------
vtkGarbageCollectorImpl::Entry*
vtkGarbageCollectorImpl::MaybeVisit(vtkObjectBase* obj)
{
  // Check for an existing entry.
  assert(obj != 0);
  Entry e(obj);
  VisitedType::iterator i = this->Visited.find(&e);
  if(i == this->Visited.end())
  {
    // Visit the object to create the entry.
    return this->VisitTarjan(obj);
  }
  // else Return the existing entry.
  return *i;
}

//----------------------------------------------------------------------------
vtkGarbageCollectorImpl::Entry*
vtkGarbageCollectorImpl::VisitTarjan(vtkObjectBase* obj)
{
  // Create an entry for the object.
  Entry* v = new Entry(obj);
  this->Visited.insert(v);

  // Initialize the entry and push it onto the stack of graph nodes.
  v->Root = v;
  v->Component = 0;
  v->VisitOrder = ++this->VisitCount;
  this->PassReferencesToEntry(v);
  this->Stack.push(v);

  vtkDebugMacro("Requesting references from "
                << v->Object->GetClassName() << "("
                << v->Object << ") with reference count "
                << (v->Object->GetReferenceCount()-v->GarbageCount));

  // Process the references from this node.
  Entry* saveCurrent = this->Current;
  this->Current = v;
  vtkGarbageCollectorToObjectBaseFriendship::ReportReferences(this, v->Object);
  this->Current = saveCurrent;

  // Check if we have found a component.
  if(v->Root == v)
  {
    // Found a new component.
    ComponentType* c = new ComponentType;
    c->Identifier = ++this->NumberOfComponents;
    Entry* w;
    do
    {
      // Get the next member of the component.
      w = this->Stack.top();
      this->Stack.pop();

      // Assign the member to the component.
      w->Component = c;
      w->Root = v;
      c->push_back(w);

      // Include this member's reference count in the component total.
      c->NetCount += w->Count;
    } while(w != v);

    // Save the component.
    this->ReferencedComponents.insert(c);

    // Print the component for debugging.
    this->PrintComponent(c);

    // Remove internal references from the component.
    this->SubtractInternalReferences(c);
  }

  return v;
}

//----------------------------------------------------------------------------
#ifdef NDEBUG
void vtkGarbageCollectorImpl::Report(vtkObjectBase* obj, void* ptr,
                                     const char*)
{
  // All calls should be given the pointer.
  assert(ptr != 0);

  // Forward call to the internal implementation.
  if(obj)
  {
    this->Report(obj, ptr);
  }
}
#else
void vtkGarbageCollectorImpl::Report(vtkObjectBase* obj, void* ptr,
                                     const char* desc)
{
  // All calls should be given the pointer.
  assert(ptr != 0);

  if(obj)
  {
    // Report debugging information if requested.
    if(this->Debug && vtkObject::GetGlobalWarningDisplay())
    {
      vtkObjectBase* current = this->Current->Object;
      std::ostringstream msg;
      msg << "Report: "
          << current->GetClassName() << "(" << current << ") "
          << (desc?desc:"")
          << " -> " << obj->GetClassName() << "(" << obj << ")";
      vtkDebugMacro(<< msg.str().c_str());
    }

    // Forward call to the internal implementation.
    this->Report(obj, ptr);
  }
}
#endif

//----------------------------------------------------------------------------
void vtkGarbageCollectorImpl::Report(vtkObjectBase* obj, void* ptr)
{
  // Get the source and destination of this reference.
  Entry* v = this->Current;
  Entry* w = this->MaybeVisit(obj);

  // If the destination has not yet been assigned to a component,
  // check if it is a better potential root for the current object.
  if(!w->Component)
  {
    if(w->Root->VisitOrder < v->Root->VisitOrder)
    {
      v->Root = w->Root;
    }
  }

  // Save this reference.
  v->References.push_back(EntryEdge(w, ptr));
}

//----------------------------------------------------------------------------
void vtkGarbageCollectorImpl::CollectComponent(ComponentType* c)
{
  ComponentType::iterator e, eend;

  // Print out the component for debugging.
  this->PrintComponent(c);

  // Get an extra reference to all objects in the component so that
  // they are not deleted until all references are removed.
  for(e = c->begin(), eend = c->end(); e != eend; ++e)
  {
    vtkGarbageCollectorToObjectBaseFriendship::Register((*e)->Object, this);
  }

  // Disconnect the reference graph.
  for(e = c->begin(), eend = c->end(); e != eend; ++e)
  {
    // Loop over all references made by this entry's object.
    Entry* entry = *e;
    for(unsigned int i = 0; i < entry->References.size(); ++i)
    {
      // Get a pointer to the object referenced.
      vtkObjectBase* obj = entry->References[i].Reference->Object;

      // Get a pointer to the pointer holding the reference.
      void** ptr = static_cast<void**>(entry->References[i].Pointer);

      // Set the pointer holding the reference to NULL.  The
      // destructor of the object that reported this reference must
      // deal with this.
      *ptr = 0;

      // Remove the reference to the object referenced without
      // recursively collecting.  We already know about the object.
      vtkGarbageCollectorToObjectBaseFriendship::UnRegister(obj,
                                                            entry->Object);
    }
  }

  // Remove the Entries' references to objects.
  for(e = c->begin(), eend = c->end(); e != eend; ++e)
  {
    this->FlushEntryReferences(*e);
  }

  // Only our extra reference to each object remains.  Delete the
  // objects.
  for(e = c->begin(), eend = c->end(); e != eend; ++e)
  {
    assert((*e)->Object->GetReferenceCount() == 1);
    vtkGarbageCollectorToObjectBaseFriendship::UnRegister((*e)->Object, this);
  }
}

//----------------------------------------------------------------------------
#ifndef NDEBUG
void vtkGarbageCollectorImpl::PrintComponent(ComponentType* c)
{
  if(this->Debug && vtkObject::GetGlobalWarningDisplay())
  {
    std::ostringstream msg;
    msg << "Identified strongly connected component "
        << c->Identifier << " with net reference count "
        << c->NetCount << ":";
    for(ComponentType::iterator i = c->begin(), iend = c->end(); i != iend; ++i)
    {
      vtkObjectBase* obj = (*i)->Object;
      int count = (*i)->Count;
      msg << "\n  " << obj->GetClassName() << "(" << obj << ")"
          << " with " << count << " external "
          << ((count == 1)? "reference" : "references");
    }
    vtkDebugMacro(<< msg.str().c_str());
  }
}
#else
void vtkGarbageCollectorImpl::PrintComponent(ComponentType*)
{
}
#endif

//----------------------------------------------------------------------------
void vtkGarbageCollectorImpl::SubtractInternalReferences(ComponentType* c)
{
  // Loop over all members of the component.
  for(ComponentType::iterator i = c->begin(), iend = c->end(); i != iend; ++i)
  {
    Entry* v = *i;

    // Loop over all references from this member.
    for(Entry::ReferencesType::iterator r = v->References.begin(), rend = v->References.end();
        r != rend; ++r)
    {
      Entry* w = r->Reference;

      // If this reference points inside the component, subtract it.
      if(v->Component == w->Component)
      {
        this->SubtractReference(w);
      }
    }
  }
}

//----------------------------------------------------------------------------
void vtkGarbageCollectorImpl::SubtractExternalReferences(ComponentType* c)
{
  // Loop over all members of the component.
  for(ComponentType::iterator i = c->begin(), iend = c->end(); i != iend; ++i)
  {
    Entry* v = *i;

    // Loop over all references from this member.
    for(Entry::ReferencesType::iterator r = v->References.begin(), rend = v->References.end();
        r != rend; ++r)
    {
      Entry* w = r->Reference;

      // If this reference points outside the component, subtract it.
      if(v->Component != w->Component)
      {
        this->SubtractReference(w);
      }
    }
  }
}

//----------------------------------------------------------------------------
void vtkGarbageCollectorImpl::SubtractReference(Entry* e)
{
  // The component should not be leaked before we get here.
  assert(e->Component != 0);
  assert(e->Component->NetCount > 0);

  vtkDebugMacro("Subtracting reference to object "
                << e->Object->GetClassName() << "(" << e->Object << ")"
                << " in component " << e->Component->Identifier << ".");

  // Decrement the entry's reference count.
  --e->Count;

  // If the component's net count is now zero, move it to the queue of
  // leaked component.
  if(--e->Component->NetCount == 0)
  {
    this->ReferencedComponents.erase(e->Component);
    this->LeakedComponents.push(e->Component);
    vtkDebugMacro("Component " << e->Component->Identifier << " is leaked.");
  }
}

//----------------------------------------------------------------------------
void vtkGarbageCollectorImpl::PassReferencesToEntry(Entry* e)
{
  // Get the number of references the collector holds.
  e->GarbageCount = 0;
  if(this->Singleton)
  {
    ReferencesType::iterator i = this->Singleton->References.find(e->Object);
    if(i != this->Singleton->References.end())
    {
      // Pass these references from the singleton to the entry.
      e->GarbageCount = i->second;
      this->Singleton->References.erase(i);
      this->Singleton->TotalNumberOfReferences -= e->GarbageCount;
    }
  }

  // Make sure the entry has at least one reference to the object.
  // This ensures the object in components of size 1 is not deleted
  // until we delete the component.
  if(e->GarbageCount == 0)
  {
    vtkGarbageCollectorToObjectBaseFriendship::RegisterBase(e->Object);
    ++e->GarbageCount;
  }

  // Subtract the garbage count from the object's reference count.
  e->Count = e->Object->GetReferenceCount() - e->GarbageCount;
}

//----------------------------------------------------------------------------
void vtkGarbageCollectorImpl::FlushEntryReferences(Entry* e)
{
  while(e->GarbageCount > 0)
  {
    vtkGarbageCollectorToObjectBaseFriendship::UnRegisterBase(e->Object);
    --e->GarbageCount;
  }
}

//----------------------------------------------------------------------------
void vtkGarbageCollector::ClassInitialize()
{
  // Set default debugging state.
  vtkGarbageCollectorGlobalDebugFlag = false;

  // Record the id of the main thread.
  vtkGarbageCollectorMainThread = vtkMultiThreader::GetCurrentThreadID();

  // Allocate the singleton used for delayed collection in the main
  // thread.
  vtkGarbageCollectorSingletonInstance = new vtkGarbageCollectorSingleton;
}

//----------------------------------------------------------------------------
void vtkGarbageCollector::ClassFinalize()
{
  // We are done with the singleton.  Delete it and reset the pointer.
  // Other singletons may still cause garbage collection of VTK
  // objects, they just will not have the option of deferred
  // collection.  In order to get it they need only to include
  // vtkGarbageCollectorManager.h so that this singleton stays around
  // longer.
  delete vtkGarbageCollectorSingletonInstance;
  vtkGarbageCollectorSingletonInstance = 0;
}

//----------------------------------------------------------------------------
void vtkGarbageCollector::Report(vtkObjectBase*, void*, const char*)
{
  vtkErrorMacro("vtkGarbageCollector::Report should be overridden.");
}

//----------------------------------------------------------------------------
void vtkGarbageCollector::Collect()
{
  // This must be called only from the main thread.
  assert(vtkGarbageCollectorIsMainThread());

  // Keep collecting until no deferred checks exist.
  while(vtkGarbageCollectorSingletonInstance &&
        vtkGarbageCollectorSingletonInstance->TotalNumberOfReferences > 0)
  {
    // Collect starting from one deferred object at a time.  Each
    // check will remove at least the starting object and possibly
    // other objects from the singleton's references.
    vtkObjectBase* root =
      vtkGarbageCollectorSingletonInstance->References.begin()->first;
    vtkGarbageCollector::Collect(root);
  }
}

//----------------------------------------------------------------------------
void vtkGarbageCollector::Collect(vtkObjectBase* root)
{
  // Create a collector instance.
  vtkGarbageCollectorImpl collector;

  vtkDebugWithObjectMacro((&collector), "Starting collection check.");

  // Collect leaked objects.
  collector.CollectInternal(root);

  vtkDebugWithObjectMacro((&collector), "Finished collection check.");
}

//----------------------------------------------------------------------------
void vtkGarbageCollector::DeferredCollectionPush()
{
  // This must be called only from the main thread.
  assert(vtkGarbageCollectorIsMainThread());

  // Forward the call to the singleton.
  if(vtkGarbageCollectorSingletonInstance)
  {
    vtkGarbageCollectorSingletonInstance->DeferredCollectionPush();
  }
}

//----------------------------------------------------------------------------
void vtkGarbageCollector::DeferredCollectionPop()
{
  // This must be called only from the main thread.
  assert(vtkGarbageCollectorIsMainThread());

  // Forward the call to the singleton.
  if(vtkGarbageCollectorSingletonInstance)
  {
    vtkGarbageCollectorSingletonInstance->DeferredCollectionPop();
  }
}

//----------------------------------------------------------------------------
int vtkGarbageCollector::GiveReference(vtkObjectBase* obj)
{
  // We must have an object.
  assert(obj != 0);

  // See if the singleton will accept a reference.
  if(vtkGarbageCollectorIsMainThread() &&
     vtkGarbageCollectorSingletonInstance)
  {
    return vtkGarbageCollectorSingletonInstance->GiveReference(obj);
  }

  // Could not accept the reference.
  return 0;
}

//----------------------------------------------------------------------------
int vtkGarbageCollector::TakeReference(vtkObjectBase* obj)
{
  // We must have an object.
  assert(obj != 0);

  // See if the singleton has a reference.
  if(vtkGarbageCollectorIsMainThread() &&
     vtkGarbageCollectorSingletonInstance)
  {
    return vtkGarbageCollectorSingletonInstance->TakeReference(obj);
  }

  // No reference is available.
  return 0;
}

//----------------------------------------------------------------------------
vtkGarbageCollectorSingleton::vtkGarbageCollectorSingleton()
{
  this->TotalNumberOfReferences = 0;
  this->DeferredCollectionCount = 0;
}

//----------------------------------------------------------------------------
vtkGarbageCollectorSingleton::~vtkGarbageCollectorSingleton()
{
  // There should be no deferred collections left.
  assert(this->TotalNumberOfReferences == 0);
}

//----------------------------------------------------------------------------
int vtkGarbageCollectorSingleton::GiveReference(vtkObjectBase* obj)
{
  // Check if we can store a reference to the object in the map.
  if(this->CheckAccept())
  {
    // Create a reference to the object.
    ReferencesType::iterator i = this->References.find(obj);
    if(i == this->References.end())
    {
      // This is a new object.  Create a map entry for it.
      this->References.insert(ReferencesType::value_type(obj, 1));
    }
    else
    {
      ++i->second;
    }
    ++this->TotalNumberOfReferences;
    return 1;
  }

  // We did not accept the reference.
  return 0;
}

//----------------------------------------------------------------------------
int vtkGarbageCollectorSingleton::TakeReference(vtkObjectBase* obj)
{
  // If we have a reference to the object hand it back to the caller.
  ReferencesType::iterator i = this->References.find(obj);
  if(i != this->References.end())
  {
    // Remove our reference to the object.
    --this->TotalNumberOfReferences;
    if(--i->second == 0)
    {
      // If we have no more references to the object, remove its map
      // entry.
      this->References.erase(i);
    }
    return 1;
  }

  // We do not have a reference to the object.
  return 0;
}

//----------------------------------------------------------------------------
vtkTypeBool vtkGarbageCollectorSingleton::CheckAccept()
{
  // Accept the reference only if deferred collection is enabled.  It
  // is tempting to put a check against TotalNumberOfReferences here
  // to collect every so many deferred calls, but this will NOT work.
  // Some objects call UnRegister on other objects during
  // construction.  We do not want to perform deferred collection
  // while an object is under construction because the reference walk
  // might call ReportReferences on a partially constructed object!
  return this->DeferredCollectionCount > 0;
}

//----------------------------------------------------------------------------
void vtkGarbageCollectorSingleton::DeferredCollectionPush()
{
  if(++this->DeferredCollectionCount <= 0)
  {
    // Deferred collection is disabled.  Collect immediately.
    vtkGarbageCollector::Collect();
  }
}

//----------------------------------------------------------------------------
void vtkGarbageCollectorSingleton::DeferredCollectionPop()
{
  if(--this->DeferredCollectionCount <= 0)
  {
    // Deferred collection is disabled.  Collect immediately.
    vtkGarbageCollector::Collect();
  }
}

//----------------------------------------------------------------------------
void vtkGarbageCollectorReportInternal(vtkGarbageCollector* collector,
                                       vtkObjectBase* obj, void* ptr,
                                       const char* desc)
{
  collector->Report(obj, ptr, desc);
}

//----------------------------------------------------------------------------
void vtkGarbageCollectorReport(vtkGarbageCollector* collector,
                               vtkSmartPointerBase& ptr,
                               const char* desc)
{
  ptr.Report(collector, desc);
}