简体   繁体   中英

Is it safe to use OSGi EventAdmin within EDT?

Is EventAdmin safe to use in a Swing environment? I'm asking because I've got the following sequence:

  • Receive an ActionListener notification from a JButton
  • Create a JPanel and put it in the properties of my Event
  • Use EventAdmin#sendEvent(Event) to send my event synchronously
  • Receive the event in my subscriber
  • Retrieve the JPanel from the properties and, using SwingUtilities#InvokeAndWait if not in EDT, put some JComponents inside
  • In the caller of EventAdmin#sendEvent(), the method returns, the JPanel has been filled, I can then add it to my dialog and display it.

The purpose of this is to let any subscriber install what it needs to a JPanel that will displayed once every subscriber has been invoked.

The first time I click on my button, everything goes fine as everything is executed in the EDT. The second time, my subscriber is invoked in a thread that is not the EDT. I hence execute the JComponent installation in a runnable launched by invokeAndWait. This call blocks for 5022ms (5000ms being the default EventAdmin timeout duration). Once unblocked, my dialog is shown. The following times, my subscriber is not called anymore. It must have been blacklisted by the EventAdmin.

Why is my subscriber not invoked from in the EDT the second time around?

No. Event Admin does not guarantee which thread the event will be delivered on, and it is pretty much certain NOT to be the original sending thread.

Since your handler does not know what thread it is on, it cannot directly manipulate the GUI. Instead it must use SwingUtilities.invokeLater() to push a Runnable onto the event queue, and in that Runnable you can make the GUI changes. For example:

class MyEventHandler implements EventHandler {
    public void handleEvent(final Event event) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                // here you can make the UI changes in response to the event data
            }
        });
    }
}

EventAdmin spec does not require the event be delivered on the same thread that it was published. You would need to use an EventAdmin implementation which added this guarantee since you must receive the event on the same thread that it was published.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM