From 4b8438b9720928b9d97eca4577ff0d7789934379 Mon Sep 17 00:00:00 2001 From: stong <498327580@qq.com> Date: Tue, 19 Sep 2023 09:49:31 +0800 Subject: [PATCH] Clean up resources related to the topic if there are no subscribers (#391) --- pubsub/gochannel/pubsub.go | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/pubsub/gochannel/pubsub.go b/pubsub/gochannel/pubsub.go index 0d4fc61c7..5dd5a02fd 100644 --- a/pubsub/gochannel/pubsub.go +++ b/pubsub/gochannel/pubsub.go @@ -205,7 +205,14 @@ func (g *GoChannel) Subscribe(ctx context.Context, topic string) (<-chan *messag s.Close() g.subscribersLock.Lock() - defer g.subscribersLock.Unlock() + defer func() { + // if there are no subscribers, clean up any resources related to the topic + if len(g.subscribers[topic]) == 0 { + delete(g.subscribers, topic) + g.subscribersByTopicLock.Delete(topic) + } + g.subscribersLock.Unlock() + }() subLock, _ := g.subscribersByTopicLock.Load(topic) subLock.(*sync.Mutex).Lock()