com.zusmart.basic.cycle.support.AbstractEventable Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of zusmart-basic Show documentation
Show all versions of zusmart-basic Show documentation
基础模块,提供配置,日志,SPI,图排序,路径匹配,资源扫描,包扫描,常用工具类
package com.zusmart.basic.cycle.support;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;
import com.zusmart.basic.cycle.Eventable;
import com.zusmart.basic.cycle.EventableCallBack;
import com.zusmart.basic.cycle.EventableEvent;
import com.zusmart.basic.cycle.EventableListener;
import com.zusmart.basic.toolkit.StringUtils;
public class AbstractEventable> implements Eventable {
private ReentrantLock locker = new ReentrantLock();
private Map> eventListeners = new ConcurrentHashMap>();
@Override
public void attachEventListener(String eventName, L eventListener) {
if (StringUtils.isBlank(eventName)) {
return;
}
if (null == eventListener) {
return;
}
try {
this.locker.lock();
Set listeners = this.eventListeners.get(eventName);
if (null == listeners) {
this.eventListeners.put(eventName, new LinkedHashSet());
listeners = this.eventListeners.get(eventName);
}
listeners.add(eventListener);
} finally {
this.locker.unlock();
}
}
@Override
public void detachEventListener(String eventName, L eventListener) {
if (StringUtils.isBlank(eventName)) {
return;
}
if (null == eventListener) {
return;
}
try {
this.locker.lock();
if (this.eventListeners.containsKey(eventName)) {
this.eventListeners.get(eventName).remove(eventListener);
}
} finally {
this.locker.unlock();
}
}
@Override
public void detachEventListener(String eventName) {
if (StringUtils.isBlank(eventName)) {
return;
}
try {
this.locker.lock();
this.eventListeners.remove(eventName);
} finally {
this.locker.unlock();
}
}
@Override
public void fireEvent(String eventName, E event) {
this.fireEvent(eventName, event, null);
}
@Override
public void fireEvent(String eventName, E event, EventableCallBack callback) {
if (StringUtils.isBlank(eventName)) {
return;
}
try {
this.locker.lock();
Set listeners = this.eventListeners.get(eventName);
if (null != listeners && listeners.size() > 0) {
for (L l : listeners) {
l.execute(event);
}
}
if (null != callback) {
callback.execute(event);
}
} finally {
this.locker.unlock();
}
}
}