Java 服务设计模式
我有一个java应用程序,它必须作为Linux进程运行。它通过套接字连接到远程系统。我有两个线程,它们贯穿程序的整个生命周期。这是我的应用程序入口点的简要版本:Java 服务设计模式,java,multithreading,executorservice,Java,Multithreading,Executorservice,我有一个java应用程序,它必须作为Linux进程运行。它通过套接字连接到远程系统。我有两个线程,它们贯穿程序的整个生命周期。这是我的应用程序入口点的简要版本: public class SMPTerminal { private static java.util.concurrent.ExcecutorService executor; public static void main(String[] args) { executor = Executors.
public class SMPTerminal {
private static java.util.concurrent.ExcecutorService executor;
public static void main(String[] args) {
executor = Executors.newFixedThreadPool(2);
Runtime.getRuntime().addShutdownHook(new Thread(new ShutdownHook()));
run(new SMPConsumer());
run(new SMPMaintainer());
}
public static void run(Service callableService) {
try {
Future<Callable> future = executor.submit(callableService);
run(future.get().restart());
} catch (InterruptedException | ExcecutionException e) {
// Program will shutdown
}
}
}
这是服务
接口的一个实现:
public interface Service() {
public Service restart();
}
public class SMPConsumer implements Callable<Service>, Service {
@Override
public Service call() throws Exception {
// ...
try {
while(true) {
// Perform the service
}
} catch (InterruptedException | IOException e) {
// ...
}
return this; // Returns this instance to run again
}
public Service restart() {
// Perform the initialization
return this;
}
}
公共类SMPConsumer实现了可调用的服务{
@凌驾
公共服务调用()引发异常{
// ...
试一试{
while(true){
//执行服务
}
}捕获(中断异常| IOE异常){
// ...
}
返回此;//返回此实例以再次运行
}
公共服务重启(){
//执行初始化
归还这个;
}
}
当一个临时IO故障或其他问题导致我的应用程序关闭时,我遇到了麻烦,之后我就达到了这种结构。现在,如果我的程序遇到问题,它不会完全关闭,而是从头开始初始化并继续。但我认为这有点奇怪,我违反了OOP设计规则。我的问题
- 这种故障处理是正确的还是有效的
- 我将来可能会遇到什么问题李>
- 我是否需要为我的问题研究任何特殊的设计模式
- 这种故障处理是正确的还是有效的?这取决于应用程序的上下文以及如何使用错误处理
- 可能会遇到I/O故障等未正确处理的情况
- 看起来您已经在使用适配器类型设计模式。看看适配器设计模式
run
方法等待callableService
完成执行,然后返回。因此,您无法同时启动两个服务。这是因为
此代码段只是基本的,您可能希望对其进行扩展以处理异常情况。您可能希望研究使用充当负载平衡器的
BlockingQueue
,您可能只是将您的ExcecutorService
超载到无法跟上所有请求的程度。@如果线程由于IO中断,请确认ExecutorService
服务只运行到线程,我运行每个线程(服务
接口实现),无法从线程内处理的etc异常。我还在SMPConsumer
中使用消息队列。哦,是的,这使得ExecutorService
无法使用!
public static void run(Service callableService) {
try {
Future<Callable> future = executor.submit(callableService);
run(future.get().restart()); // <=== will block until task completes!
} catch (InterruptedException | ExcecutionException e) {
// Program will shutdown
}
}
public static void run(Service callableService) {
executor.submit(() -> {
Service result = callableService.call();
run(result.restart());
return result;
});
}