Skip to content

Commit

Permalink
Fix DubboShutdownHook Memory Leak (#2922)
Browse files Browse the repository at this point in the history
  • Loading branch information
LiZhenNet authored and beiwei30 committed Dec 10, 2018
1 parent c2a4c8d commit 833ba03
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ public abstract class AbstractConfig implements Serializable {
legacyProperties.put("dubbo.service.url", "dubbo.service.address");

// this is only for compatibility
Runtime.getRuntime().addShutdownHook(DubboShutdownHook.getDubboShutdownHook());
DubboShutdownHook.getDubboShutdownHook().register();
}

protected String id;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,14 +40,17 @@ public static DubboShutdownHook getDubboShutdownHook() {
return dubboShutdownHook;
}

/**
* Has it already been registered or not?
*/
private final AtomicBoolean registered = new AtomicBoolean(false);
/**
* Has it already been destroyed or not?
*/
private final AtomicBoolean destroyed;
private final AtomicBoolean destroyed= new AtomicBoolean(false);

private DubboShutdownHook(String name) {
super(name);
this.destroyed = new AtomicBoolean(false);
}

@Override
Expand All @@ -58,13 +61,33 @@ public void run() {
doDestroy();
}

/**
* Register the ShutdownHook
*/
public void register() {
if (!registered.get() && registered.compareAndSet(false, true)) {
Runtime.getRuntime().addShutdownHook(getDubboShutdownHook());
}
}

/**
* Unregister the ShutdownHook
*/
public void unregister() {
if (registered.get() && registered.compareAndSet(true, false)) {
Runtime.getRuntime().removeShutdownHook(getDubboShutdownHook());
}
}

/**
* Destroy all the resources, including registries and protocols.
*/
public void doDestroy() {
if (!destroyed.compareAndSet(false, true)) {
return;
}
// unregister the shutdownHook
unregister();
// destroy all the registries
AbstractRegistryFactory.destroyAll();
// destroy all the protocols
Expand All @@ -88,4 +111,5 @@ private void destroyProtocols() {
}
}


}
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ public class SpringExtensionFactory implements ExtensionFactory {

public static void addApplicationContext(ApplicationContext context) {
contexts.add(context);
Runtime.getRuntime().removeShutdownHook(DubboShutdownHook.getDubboShutdownHook());
DubboShutdownHook.getDubboShutdownHook().unregister();
BeanFactoryUtils.addApplicationListener(context, shutdownHookListener);
}

Expand Down

0 comments on commit 833ba03

Please sign in to comment.