سؤال

If I am using WeakReferences to allow listeners to not hold onto the surrounding object. Should my client facing API enforce the use of weak references, or is it something I should deal with internally and not expose this complication? Also what is the impact of testing. i.e. I could mock a listener but if I 'new up' the weak reference inside the listener I wouldn't be able to test the flow when the WeakRefernece becomes null.

WeakReference JavaDoc

For instance:

interface TaskListener {
    void callback();
}

Don't expose the WeakReference

class MyClass {

    private TaskListener;

    public void runTask() {
        taskListener = new TaskListener(){

            @Override
            public void callback() {

            }
        }
        task.setListener(taskListener);
        task.run();
    }

}

impl:

class Task {

    public void setListener(TaskListener listener) {
        this.listener = new WeakReference<TaskListener>(listener);    
    }

}

Do expose the WeakReference:

class MyClass {

    private WeakReference<TaskListener>;

    public void runTask() {
        taskListener = new WeakReference<TaskListener>(new TaskListener(){

            @Override
            public void callback() {

            }
        })
        task.setListener(taskListener);
        task.run();
    }

}

impl:

class Task {

    public void setListener(WeakReference<TaskListener> listener) {
        this.listener = listener;
    }

}
هل كانت مفيدة؟

المحلول

The weak reference is an implementation detail and just adds complication for the API users for no reason. Unless they are every going to do with the weak reference just have them pass the object in and do the weak reference yourself.

Be aware though that there are limitations with this pattern, I tried it myself before and discovered it was actually more hindrance than help. Because the weak references get dropped I couldn't actually just add a listener and then forget about it - I had to also keep a reference to that listener elsewhere just to stop it getting GC.

This may not apply to your use-case but in many cases listeners are implemented as anonymous inner classes and they are attached to listen but no other reference is then kept to them. That is not possible if you store them using weak references.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top