gpt4 book ai didi

java - 在 Java 中安全地启动/停止服务实例

转载 作者:行者123 更新时间:2023-11-29 04:46:28 25 4
gpt4 key购买 nike

我正在开发一个使用 LDAP 服务器作为持久存储的多线程应用程序。我创建了以下服务类以在需要时启动和停止 LDAP 服务:

public class LdapServiceImpl implements LdapService {

public void start() {
if (!isRunning()) {
//Initialize LDAP connection pool
}
}

public void stop() {
if (isRunning()) {
//Release LDAP resources
}
}

private boolean isRunning() {
//What should go in here?
}

}

我们目前使用 Google Guice 将服务实现作为单例实例注入(inject):

public class ServiceModule extends AbstractModule {

@Override
protected void configure() {
}

@Provides @Singleton
LdapService providesLdapService() {
return new LdapServiceImpl();
}

}

这样我们就可以在应用程序启动时设置连接池,对连接做一些事情,然后在应用程序关闭时释放资源:

public static void main(String[] args) throws Exception {
Injector injector = Guice.createInjector(new ServiceModule());

Service ldapService = injector.getInstance(LdapService.class));
ldapService.start();
addShutdownHook(ldapService);

//Use connections

}

private static void addShutdownHook(final LdapService service) {
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
service.stop();
}
});
}

我面临的问题是我想确保服务只启动/停止一次。出于这个原因,我在服务实现中添加了一个“isRunning()”方法,但我不确定如何实现它。

考虑到应用程序是多线程的并且我的服务实例是单例,实现“isRunning()”方法的最佳方式是什么?

此外,是否有更好/更清洁的方法来实现这一点?

提前致谢。

最佳答案

如果LdapServiceImpl 是单例的,又担心多个线程同时调用start 或stop 方法,可以简单地在start 和stop 方法中加上synchronized 关键字。到那时,您可以只使用一个简单的 boolean 标志来存储当前运行状态,只要访问该状态的所有方法都是同步的,您就应该是安全的。

public class LdapServiceImpl implements LdapService {

private boolean isRunning = false;

public synchronized void start() {
if (!isRunning()) {
//Initialize LDAP connection pool
isRunning = true;
}
}

public synchronized void stop() {
if (isRunning()) {
//Release LDAP resources
isRunning = false;
}
}

private boolean isRunning() {
return isRunning;
}
}

关于java - 在 Java 中安全地启动/停止服务实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36921866/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com