What if a large number of objects are passed to my SwingWorker.process () method?

I just found an interesting situation. Suppose you have SwingWorker (I made it vaguely reminiscent of my own):

public class AddressTreeBuildingWorker extends SwingWorker<Void, NodePair> {
    private DefaultTreeModel model;
    public AddressTreeBuildingWorker(DefaultTreeModel model) {
    }

    @Override
    protected Void doInBackground() {
        // Omitted; performs variable processing to build a tree of address nodes.
    }

    @Override
    protected void process(List<NodePair> chunks) {
        for (NodePair pair : chunks) {
            // Actually the real thing inserts in order.
            model.insertNodeInto(parent, child, parent.getChildCount());
        }
    }

    private static class NodePair {
        private final DefaultMutableTreeNode parent;
        private final DefaultMutableTreeNode child;
        private NodePair(DefaultMutableTreeNode parent, DefaultMutableTreeNode child) {
            this.parent = parent;
            this.child = child;
        }
    }
}

If the work performed in the background is significant, then everything works well - it is process()called with relatively small lists of objects, and everyone is happy.

The problem is that if the work done in the background is suddenly negligible for any reason, it process()gets a huge list of objects (for example, I saw 1,000,000), and by the time you process each object, you spent 20 seconds on the topic The "Event Manager" is exactly what SwingWorker designed to avoid.

, , SwingWorker - .

? , , , .

+3
2

.

, . , process NodePairs, , :

@Override
protected Void doInBackground() {
    this.treeModelUpdater.execute();
    // Omitted; performs variable processing to build a tree of address nodes.
}

@Override
protected void process(List<NodePair> chunks) {
    this.queue.addAll( chunks ); // a blocking queue
}

@Override
protected void done() {
    // Null Object as sentinel value to unblock TreeModelUpdater
    // and signal it to end doInBackground.
    this.queue.put( new NullNodePair() );
}

TreeModelUpdater (this.treeModelUpdater) SwingWorker, doInBackground NodePairs .

+4

, , , . 1Mio chunk , ?:-)

, , , .

1Mio , , , .. , . .

+2

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


All Articles