我有一个责任链的 Rest 服务调用,为了更好的性能,我们添加了多线程但无法处理异常请查找代码示例:从 Rest Service 方法开始
@POST
@Path("/dispatch")
public Response dispatchEvent(){
Thread steps = new Thread(new HandlerExecutor());
steps.start();
}
HandlerExecutor.java:
public class HandlerExecutor implements Runnable {
@Override
public void run() {
Handler first = HandlerLocator.getHandler();
if (first != null) {
first.process();
}
}
}
处理程序定位器.java:
public class HandlerLocator {
public static Map<String, List<Handler>> allHandlers = null;
public static Handler getHandler() {
Handler first = null;
List<Handler>> h = new HashMap<String, List<Handler>>();
List<Handler> list = new ArrayList<Handler>();
list.add(new ConsoleHandler());
list.add(new FileHandler());
list.add(new FinalHandler());
h.put("1", list);
List<Handler> clientHandlers = h.get("1");
if (clientHandlers != null) {
int size = clientHandlers.size();
Handler h1, prev = null;
for (int i = 0; i < size; i++) {
h1 = (Handler) clientHandlers.get(i);
if (first == null) {
first = h1;
} else {
prev.setNext(h1);
}
prev = h1;
}
}
return first;
}
}
处理程序.java:
public interface Handler extends Serializable {
Handler setNext(Handler next);
void process();
}
基本处理程序.java
public abstract class BasicHandler implements Handler {
private Handler next;
public BasicHandler() {
this.next = null;
}
@Override
public Handler setNext(Handler next) {
this.next = next;
return next;
}
@Override
public void process() {
doProcess();
if (next != null) {
next.process();
} else {
// done
}
}
public abstract void doProcess() ;
}
public class ConsoleHandler extends BasicHandler {
@Override
public void doProcess() {
System.out.println("processed ConsoleHandler");
}
}
与 ConsoleHandler 相同,我们有 FileHandler、FinalHandlers
所以,问题是这些:
- run 方法返回 void 所以,如果
ConsoleHandler
抛出异常,有什么方法可以处理异常吗? - 如果执行的第二个处理程序失败,如何回滚?