I am building a java application and i have implemented custom listeners and events. The problem now is that there are many events and listeners and the application GUI thread is being blocked while the listeners process the events. Can this be solved using event dispatch thread? If so how?
The code for listeners:
public class ProjectChangeObserver
{
private List<ProjectChangeListener> listeners = new ArrayList<ProjectChangeListener>();
public void addProjectChangeListener(ProjectChangeListener l)
{
listeners.add(l);
}
public void removeProjectChangeListener(ProjectChangeListener l)
{
listeners.remove(l);
}
public void removeAllProjectChangeListeners()
{
listeners.clear();
}
public void fireProjectChange(ProjectChangeEvent e)
{
if(listeners.size() > 0)
{
ArrayList<ProjectChangeListener> safeCopy = new ArrayList<ProjectChangeListener>(listeners);
for (ProjectChangeListener cl : safeCopy ) {
cl.onProjectChange(e);
}
}
}
}
One of the features of Swing is that it is single-threaded.
However, there is nothing stopping you from spawning your own threads to do background processing. As long as you only make calls to
revalidate()orrepaint()then all the drawing will still be handled in the Swing thread.(Remember that if you are going to be spawning other threads to do background work then ensure that your variables are declared
volatileif you expect the Swing thread to see the same values as in your threads. Or pass the information back through another listener.)If you are intending to do the painting itself (e.g. of custom components) in separate threads, then it is either not possible or very strongly discouraged depending on the situation. (Some exotic situations may permit multi-CPU generation of a scene in a custom thread-safe buffering class, but you’re unlikely to be doing that).
If you are finding that your
Listeners are CPU/network intensive, then you might want to think about the architecture of who is doing the majority of the shouting and who is doing the listening. I always try to minimise the amount of shouting in my “view” code so that it simply responds to events.Incidentally, I’ve found Project Lombok and its Beta sister Lombok PG to greatly reduce the boilerplate of implementing the
Listenerpattern with@ListenerSupport.