Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should we use WeakReference in Observer Pattern? [duplicate]

I'm learning and trying to implement the Observer pattern in Java from this tutorial. I'm stuck at the point about whether I should use WeakReference for the subject to hold the observers.

For the implementation below, the Subject and the BinaryObserver are holding strong references to each other, which I'm afraid prevents GC from collecting the unused Subject.

So my question is, should I use List<WeakReference<Observer>> observers instead of List<Observer> observers?

Subject.java

public class Subject {

   private List<Observer> observers = new ArrayList<Observer>();
   private int state;

   public int getState() {
      return state;
   }

   public void setState(int state) {
      this.state = state;
      notifyAllObservers();
   }

   public void attach(Observer observer){
       observers.add(observer);
   }

   public void notifyAllObservers(){
       for (Observer observer : observers) {
           observer.update();
       }
   }
}

Observer.java

public abstract class Observer {
    protected Subject subject;
    public abstract void update();
}

BinaryObserver.java

public class BinaryObserver extends Observer{

    public BinaryObserver(Subject subject){
        this.subject = subject;
        this.subject.attach(this);
    }

    @Override
    public void update() {
        System.out.println("Binary String: " + Integer.toBinaryString());
    }
}

ObserverPatternDemo.java

public class ObserverPatternDemo {
    public static void main(String[] args) {
       Subject subject = new Subject();

       new BinaryObserver(subject);

       System.out.println("First state change: 15");
       subject.setState(15);
    }
}
like image 890
hackjutsu Avatar asked Oct 31 '22 16:10

hackjutsu


1 Answers

You don't have to use weak reference. What you are doing is fine. Java GC already handles Circular References. Java GC will collect an entire Circular References graph if the Circular References graph is an ISLAND (No incoming references to the graph from the Root - You can think the entire the graph is a big Object and the GC will collect this big object If there is no references to it)

Take a look at this: How does Java Garbage Collection work with Circular References?

like image 85
Loc Avatar answered Nov 15 '22 05:11

Loc