Hide the hidden output of WeakReferences or force the client to use them

If I use WeakReferenceto allow listeners not to stay on the surrounding object. Should my client encounter an API using weak links, or is it something that I should have internally and not subject to this complication? Also what is the impact of testing. that is, I could mock the listener, but if I “updated” the weak link inside the listener, I would not be able to test the stream when it WeakRefernecebecomes zero.

WeakReference JavaDoc

For example:

interface TaskListener {
    void callback();
}

Do not expose WeakReference

class MyClass {

    private TaskListener;

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

            @Override
            public void callback() {

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

}

realizing:

class Task {

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

}

Highlight WeakReference:

class MyClass {

    private WeakReference<TaskListener>;

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

            @Override
            public void callback() {

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

}

realizing:

class Task {

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

}
+4
source share
1 answer

- API - . , .

, , , , , , . , , - , GC.

, , , . , .

0

Source: https://habr.com/ru/post/1524510/


All Articles