Objective
In the example of the previous article, it should also be noted thatFrogThe object has its own member object.FrogObject creates its own member objects and knows how long they survive (as long asFrogsurvived), soFrogObject knows when to callDispose ()To release its member object. However, if these member objects exist in one or more of the other objects, the problem becomes more complex, and you cannot simply assume that you can invoke theDispose ()The In this case, it is also necessary to use reference counting to track the number of objects that still have access to the shared object. The following is the relevant code:
Sample source Code
Package Com.mufeng.theeighthchapter;class Shared {private int refcount = 0;private static Long counter = 0;private final L Ong id = counter++;p ublic Shared () {//TODO auto-generated constructor stubSystem.out.println ("Creating" + This);} public void AddRef () {refcount++;} protected void Dispose () {if (--refcount = = 0) {System.out.println ("Disposing" + This);}} @Overridepublic String toString () {//TODO auto-generated method Stubreturn "Shared" + ID;} Class Composing {private Shared shared;private static long counter = 0;private final Long id = counter++;p ublic Composing ( Shared shared) {//TODO auto-generated constructor stubSystem.out.println ("creating" + this); this.shared = SHARED;THIS.S Hared.addref ();} protected void Dispose () {System.out.println ("disposing" + this); Shared.dispose ();} @Overridepublic String toString () {//TODO auto-generated method Stubreturn "composing" + ID;} public class Referencecount {public static void main (string[] args) {shared shared = new Shared (); Composing[] composing = {new composing (shared), new composing (shared), new composing (shared), new composing (shared), new composing ( Shared)};for (composing c:composing) {c.dispose ();}}}
Output results
Creating Shared 0creating composing 0creating composing 1creating composing 2creating composing 3creating composing 4dispo Sing composing 0disposing composing 1disposing composing 2disposing composing 3disposing composing 4Disposing Shared 0
SOURCE parsing
Static Long counterTrack the creation of theSharedThe number of examples, you can also considerIDProvide a value.counteris of typeLongInstead ofintTo prevent overflow.IDIsFinal, because we do not want its value to be changed in the object life cycle. When attaching a shared object to a class, you must remember to call theAddRef ()ButDispose ()Method will track the number of references and decide when to perform cleanup. Using this technique requires a lot of care, but if you're sharing objects that need to be cleaned up, you don't have much to choose from.
Creation and destruction of shared objects in Java (with source code)