/*
 * JBoss, the OpenSource J2EE webOS
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */
package org.jboss.mx.notification;

import javax.management.Notification;
import javax.management.NotificationBroadcasterSupport;
import javax.management.NotificationListener;

import org.jboss.logging.Logger;
import org.jboss.mx.util.ThreadPool;

/**
 * A notification broadcaster with asynch notifications
 * 
 * @author  <a href="mailto:Adrian.Brock@HappeningTimes.com">Adrian Brock</a>.
 * @version $Revision: 1.3.2.3 $
 */
public class AsynchNotificationBroadcasterSupport
   extends NotificationBroadcasterSupport
{
   // Attributes ----------------------------------------------------

   private static Logger log = Logger.getLogger(AsynchNotifier.class);

   private static ThreadPool pool = new ThreadPool(true);

   // Constructor ---------------------------------------------------

   /**
    * Construct a new Asyncrhonous broadcaster
    */
   public AsynchNotificationBroadcasterSupport()
   {
      super();
   }

   // Public --------------------------------------------------------

   // NotificationBroadcasterSupport overrides ----------------------

   /**
    * Handle the notification, asynchronously invoke the listener.
    *
    * @param listener the listener to notify
    * @param notification the notification
    * @param handback the handback object
    */
   protected void handleNotification(NotificationListener listener,
                                     Notification notification,
                                     Object handback)
   {
      pool.run(new AsynchNotifier(listener, notification, handback));
   }

   // Inner classes -------------------------------------------------

   public static class AsynchNotifier
      implements Runnable
   {
      NotificationListener listener;
      Notification notification;
      Object handback;
      public AsynchNotifier(NotificationListener listener,
                            Notification notification,
                            Object handback)
      {
         this.listener = listener;
         this.notification = notification;
         this.handback = handback;
      }

      public void run()
      {
         try
         {
            listener.handleNotification(notification, handback);
         }
         catch (Throwable throwable)
         {
            log.error("Error processing notification=" + notification +
                      " listener=" + listener +
                      " handback=" + handback,
                      throwable);
         }
      }
   }
}
