Java tutorial
/* * Copyright 2011-2016 MSUN.com All right reserved. This software is the confidential and proprietary information of * MSUN.com ("Confidential Information"). You shall not disclose such Confidential Information and shall use it only * in accordance with the terms of the license agreement you entered into with MSUN.com. */ package com.mmj.app.common.notify; import java.util.Map; import java.util.Queue; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import javax.annotation.PostConstruct; import org.springframework.stereotype.Service; import com.mmj.app.common.notify.NotifyUtils.MethodDescriptor; import com.mmj.app.common.notify.event.Event; import com.mmj.app.common.notify.event.EventType; import com.mmj.app.common.result.Result; /** * @author zxc Jul 24, 2014 4:55:57 PM */ @Service public class NotifyService implements INotify { private static Map<EventType, Set<MethodDescriptor>> container = new ConcurrentHashMap<EventType, Set<MethodDescriptor>>(); /** * */ private static Queue<Event> events = new ConcurrentLinkedQueue<Event>(); protected static int deplaySeconds = 10, corePoolSize = 10; protected static int fixRate = 10; @PostConstruct void init() { Executors.newScheduledThreadPool(corePoolSize).scheduleAtFixedRate(new Runnable() { @Override public void run() { try { // logger.debug("poll the queue..."); fireEvent(); } catch (Throwable e) { logger.error(e.getMessage(), e); } } }, deplaySeconds, fixRate, TimeUnit.MILLISECONDS); } /** * ????? ????? * * <pre> * * </pre> * * @param listener ??? * @return ??result? */ public Result regist(NotifyListener listener) { return NotifyUtils.getListenedEvent(container, listener); } /** * */ public void notify(Event event) { if (logger.isDebugEnabled()) { logger.debug("Receive a event " + event.summary()); } events.add(event); } /** * */ protected void fireEvent() { Event poll = events.poll(); if (poll == null) { return; } if (logger.isDebugEnabled()) { logger.debug("fire a event " + poll.summary()); } EventType eventType = poll.getEventType(); if (eventType == null) { logger.warn("A ERROR Event Found! " + poll.summary()); return; } // ??? Set<MethodDescriptor> listseners = container.get(eventType); if (listseners != null) { for (MethodDescriptor md : listseners) { try { md.invoke(poll); } catch (Exception e) { logger.error(e.getMessage(), e); } } } } }