开发者

How can one overcome a concurrent modification exception in a GUI mediator?

FYI I have adopted the mediator pattern for my GUI in Swing on Java.

Unfortunately, a concurrent modification exception is always thrown if user input requires a new window.

It's because my code attempts to add a new colleague (a new window) to the mediator's list of colleagues in the course of handling user input from an existing colleague (window).

e.g.

public MainScreenColleague implements GuiColleague, ActionListener {
    private GuiMediator mediator;
    public MainScreenColleague(GuiMediator medi) {
        mediator = medi;
        // implement JFrame with JButtons
    }
    public conveyInputToMediator(EventObject event) {
        mediator.conveyInputToColleagues(event);
    }
    public receiveInputFromMediator(EventObject event) {
        if (event.getSource() = particularBtn) {
            GuiColleague particularColleague = new ParticularConcreteColleague(mediator);
            //THIS IS THE CODE THAT THROWS CONCURRENCY EXCEPTION
            mediator.addGuiColleague(particularColleague);
        }       
}

Is 开发者_Go百科there some other structure of handling adding new colleagues that I can adopt? Thanks in advance for any suggestions or ideas.


One option might be to adopt a Swing-esque model and have your mediator store an "event queue" of updates that it needs to make when the time is right. That way, when you're adding new windows while processing events from some other object, that window doesn't gum up the logic. It just gets added to a "handle this when you're done" queue that gets processed after the mediation is done.

Another option would be to make a copy of the list before iterating over it, so that changes made to the raw structure during iteration don't show up in the list being iterated over.

Yet another idea would be to use some non-iterator technique for visiting elements. For example, if you had the windows stored in a list, you could use a for loop like this one:

for (int i = 0; i < elems.size(); ++i)
    /* ... */

which will not throw these sorts of exceptions.


If the traversals far outnumber the modifications, a copy-on-write datastructure like CopyOnWriteArrayList may fit.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜