How mixing weak and strong announcement subscriptions leaks memory

With Pharo's SubscriptionRegistry Object << #SubscriptionRegistry slots: { #subscriptions . #monitor }; tag: 'Subscription'; package: 'Announcements-Core' , an announcer that has both strong and weak subscribers can keep its strong subscribers alive for as long as some other weak subscriber lives, and unsubscribing does not stop the leak. GtMixedSubscriptionRegistry Object << #GtMixedSubscriptionRegistry slots: { #monitor . #strongSubscriptions . #weakSubscriptions . #lastChange }; tag: 'Mixed-Core'; package: 'GToolkit-PharoBasePatch-Subscriptions' is a registry an announcer can use instead, in which this cannot happen. This page explains the leak and how the mixed registry avoids it; the leak itself is explored in more detail on the Glamorous Toolkit Book page Exploring memory leaks when mixing weak and strong subscriptions in announcers.

An ephemeron is a key/value pair whose value is kept alive only while its key is reachable from somewhere else; in Pharo it is a WeakKeyAssociation Association << #WeakKeyAssociation layout: EphemeronLayout; slots: { #container }; tag: 'Dictionaries'; package: 'Collections-Weak' . When nothing else references the key any more, the garbage collector fires the ephemeron, and shortly after the collection the finalization process mourns it, which runs its cleanup.

A strong subscription (AnnouncementSubscription AbstractAnnouncementSubscription << #AnnouncementSubscription slots: { #subscriber }; tag: 'Subscription'; package: 'Announcements-Core' ) references its subscriber, so the announcer keeps the subscriber alive. A weak subscription (WeakAnnouncementSubscription AbstractAnnouncementSubscription << #WeakAnnouncementSubscription layout: WeakLayout; slots: { #next }; tag: 'Subscription'; package: 'Announcements-Core' ) holds its subscriber in a weak slot, and to learn when the subscriber dies it registers an ephemeron in the global FinalizationRegistry Object << #FinalizationRegistry slots: { #semaphore . #errorHandler . #ephemeronList }; sharedVariables: { #Default }; tag: 'Registry'; package: 'System-Finalization' (WeakAnnouncementSubscription>>#register register self finalizationRegistry add: self subscriber finalizer: self ): key the subscriber, value the subscription. The subscription references its announcer strongly, because WeakAnnouncementSubscription>>#finalize finalize announcer removeSubscription: self needs it.

While a weak subscriber Y lives, its global ephemeron keeps its subscription alive, and with it the announcer and everything subscribed strongly to that announcer: FinalizationRegistry Object << #FinalizationRegistry slots: { #semaphore . #errorHandler . #ephemeronList }; sharedVariables: { #Default }; tag: 'Registry'; package: 'System-Finalization' #selector default ^ Default ifNil: [ Default := self new ] → ephemeron (key Y, alive) → weak subscription of Y → announcer → registry → strong subscription → X

The typical case: a graphical element holds its model and subscribes strongly to the model's announcer, while some other long-lived object subscribes weakly to the same announcer. Model and element then stay alive as long as that other object does: GtMixedSubscriptionRegistryExamples>>#elementOfModelLeaksWithPlainRegistry elementOfModelLeaksWithPlainRegistry <gtExample> | anExtraSubscriber theSurvivors | anExtraSubscriber := self newSubscriber. theSurvivors := self modelAndElementWithStrongSubscriptionOn: Announcer new extraWeakSubscriber: anExtraSubscriber. self garbageCollect. self assert: (theSurvivors at: 1) notNil. self assert: (theSurvivors at: 2) notNil. self assert: anExtraSubscriber announcements isEmpty. ^theSurvivors

Two cases do not leak a subscriber:

  • The same object subscribed both strongly and weakly does not leak by itself: the only path to it starts at its own ephemeron, and an ephemeron does not keep its key alive.
  • An announcer with only weak subscriptions does not keep its subscribers alive, but a live weak subscriber still keeps the announcer itself and its registry alive.

The leak needs a strong subscription plus a weak subscription of a different, longer-lived object. Weak block subscriptions are not weak. A SubscriptionRegistry Object << #SubscriptionRegistry slots: { #subscriptions . #monitor }; tag: 'Subscription'; package: 'Announcements-Core' holds a weak subscription strongly, and the subscription holds its action strongly. A block passed to #selector weak "announcer weak subscribe: foo" "GT patch: my registry chooses the weak builder, see implementors of #weakSubscriptionBuilderFor:" <gtPharoPatch: #Pharo> ^registry weakSubscriptionBuilderFor: self #selector when: anAnnouncementClass do: aValuable for: receiver "Do not use this message on weak announcer because it does not work. The block will hold strongly the receiver and more. We need ephemerons for that'" "aValuable isBlock ifTrue: [ self error: 'Do not use this message on weak and block because it does not work. We need ephemerons for that']." ^ announcer basicSubscribe: ( WeakAnnouncementSubscription new announcer: announcer; announcementClass: anAnnouncementClass; action: aValuable; subscriber: receiver; yourself) that refers to its subscriber therefore keeps the subscriber alive as long as the announcer lives; Pharo's own WeakSubscriptionBuilder>>#when:do:for: when: anAnnouncementClass do: aValuable for: receiver "Do not use this message on weak announcer because it does not work. The block will hold strongly the receiver and more. We need ephemerons for that'" "aValuable isBlock ifTrue: [ self error: 'Do not use this message on weak and block because it does not work. We need ephemerons for that']." ^ announcer basicSubscribe: ( WeakAnnouncementSubscription new announcer: announcer; announcementClass: anAnnouncementClass; action: aValuable; subscriber: receiver; yourself) warns about this. The subscription graphs of GtAnnouncerGraphExamples Object << #GtAnnouncerGraphExamples slots: {}; package: 'GToolkit-Utility-Announcements-Visualization' draw these chains for each case, with a plain and with a mixed registry.

The global entry is removed only when the subscriber dies. #selector unsubscribe: anObject "Unsubscribe all subscriptions of anObject from the receiver" registry removeSubscriber: anObject sends WeakAnnouncementSubscription>>#unregister unregister GtWeakSubscriptionDisableFinalizationFlag isEnabled ifTrue: [ ^ self ]. self subscriber ifNotNil: [:sub | self finalizationRegistry remove: sub ifAbsent: ["I will ignore if the subscription has been already removed"]] , which in GT does nothing while GtWeakSubscriptionDisableFinalizationFlag>>#isEnabled isEnabled ^ enabled ifNil: [ true ] answers true (the default); the real removal, FinalizationRegistry>>#remove:ifAbsent: remove: aKey ifAbsent: aBlock | ephemeron | ephemeron := self ephemeronAtKey: aKey ifAbsent: [ ^ aBlock value ]. ^ self removeEphemeron: ephemeron , would scan all entries and remove the first one with that key. #selector removeSubscription: subscription "Remove the given subscription from the receiver" ^ registry remove: subscription never unregisters. So an unsubscribed weak subscription keeps its entry, and the entry keeps the announcer reachable, until the subscriber dies. An element that is added to and removed from the scene several times collects one stale entry per subscription each time. In one GT image, 98,419 of 223,386 global entries for weak subscriptions (44 %) belonged to subscriptions that were no longer in their announcer, most of them from Bloc text elements and editors.

GtMixedSubscriptionRegistry Object << #GtMixedSubscriptionRegistry slots: { #monitor . #strongSubscriptions . #weakSubscriptions . #lastChange }; tag: 'Mixed-Core'; package: 'GToolkit-PharoBasePatch-Subscriptions' keeps strong subscriptions as before, but stores weak subscriptions (GtEphemeronAnnouncementSubscription AbstractAnnouncementSubscription << #GtEphemeronAnnouncementSubscription slots: { #subscriberReference }; tag: 'Mixed-Core'; package: 'GToolkit-PharoBasePatch-Subscriptions' ) itself: for each weak subscriber it holds one ephemeron, keyed on the subscriber, whose value is the set of that subscriber's subscriptions. Nothing global references these ephemerons; the only path to them goes through the announcer.

  • A live weak subscriber no longer keeps the announcer alive. There is no chain from a global root to the announcer, so the element and its model from the example above are collected while the other weak subscriber lives. Compare GtMixedSubscriptionRegistryExamples>>#elementOfModelLeaksWithPlainRegistryelementOfModelLeaksWithPlainRegistry <gtExample> | anExtraSubscriber theSurvivors | anExtraSubscriber := self newSubscriber. theSurvivors := self modelAndElementWithStrongSubscriptionOn: Announcer new extraWeakSubscriber: anExtraSubscriber. self garbageCollect. self assert: (theSurvivors at: 1) notNil. self assert: (theSurvivors at: 2) notNil. self assert: anExtraSubscriber announcements isEmpty. ^theSurvivors with:

GtMixedSubscriptionRegistryExamples>>#elementOfModelIsCollectedDespiteLiveWeakSubscriber elementOfModelIsCollectedDespiteLiveWeakSubscriber <gtExample> | anExtraSubscriber theSurvivors | anExtraSubscriber := self newSubscriber. theSurvivors := self modelAndElementWithStrongSubscriptionOn: self newAnnouncer extraWeakSubscriber: anExtraSubscriber. self assert: (self garbageCollectUntil: [(theSurvivors at: 1) isNil and: [(theSurvivors at: 2) isNil]]). self assert: anExtraSubscriber announcements isEmpty. ^theSurvivors

  • Unsubscribing removes everything. The subscriber's entry, with its ephemeron, leaves the registry; nothing stays behind anywhere (GtMixedSubscriptionRegistryExamples>>#unsubscribedWeakSubscriberDoesNotKeepElementAliveunsubscribedWeakSubscriberDoesNotKeepElementAlive <gtExample> | anExtraSubscriber theSurvivors | anExtraSubscriber := self newSubscriber. theSurvivors := self modelAndElementWithStrongSubscriptionOn: self newAnnouncer unsubscribedWeakSubscriber: anExtraSubscriber. self assert: (self garbageCollectUntil: [(theSurvivors at: 1) isNil and: [(theSurvivors at: 2) isNil]]). self assert: (self hasFinalizationRegistryEntryFor: anExtraSubscriber) not. ^theSurvivors).
  • A dead weak subscriber is removed by the registry itself. When the subscriber is collected, the VM fires its ephemeron and the registry drops the whole group (GtMixedSubscriptionRegistryExamples>>#weakSubscriberIsGarbageCollectedweakSubscriberIsGarbageCollected <gtExample> | anAnnouncer theSurvivors | anAnnouncer := self newAnnouncer. theSurvivors := self subscribeWeakSubscriberTo: anAnnouncer. self assert: anAnnouncer subscriptions numberOfWeakSubscribers equals: 1. self assert: (self garbageCollectUntil: [(theSurvivors at: 1) isNil]). self assert: anAnnouncer subscriptions isEmpty. self assert: anAnnouncer subscriptions numberOfWeakSubscribers equals: 0. ^anAnnouncer). An announcer that is no longer used is simply garbage, ephemerons included (GtMixedSubscriptionRegistryExamples>>#announcerIsCollectedWhileWeakSubscriberLivesannouncerIsCollectedWhileWeakSubscriberLives <gtExample> | aSubscriber theSurvivors | aSubscriber := self newSubscriber. theSurvivors := self announcerWithWeakSubscriber: aSubscriber. self assert: (self garbageCollectUntil: [(theSurvivors at: 1) isNil]). self assert: aSubscriber announcements isEmpty. ^theSurvivors).
  • Weak block subscriptions are weak. A block that refers to its subscriber sits in the value of the subscriber's ephemeron, which does not keep the subscriber alive (GtMixedSubscriptionRegistryExamples>>#weakSubscriberCapturedByItsBlockIsCollectedweakSubscriberCapturedByItsBlockIsCollected <gtExample> | anAnnouncer theSurvivors | anAnnouncer := self newAnnouncer. theSurvivors := self subscribeWeakBlockSubscriberTo: anAnnouncer. self assert: (self garbageCollectUntil: [(theSurvivors at: 1) isNil]). self assert: (self waitUntil: [anAnnouncer subscriptions isEmpty]). ^anAnnouncer).

Strong and weak subscribers can therefore be mixed freely on one announcer: for example a page keeps its history as a strong subscriber and widgets subscribe weakly (GtMixedSubscriptionRegistryExamples>>#ownedStrongSubscriberLivesAsLongAsItsOwner ownedStrongSubscriberLivesAsLongAsItsOwner <gtExample> | aWidget theSurvivors | aWidget := self newSubscriber. theSurvivors := self pageWithStrongHistoryAndWeakWidget: aWidget. self garbageCollect. self assert: (theSurvivors at: 1) notNil. self assert: (theSurvivors at: 2) notNil. (theSurvivors at: 1) heldObject first announce: JobStart new. self assert: (theSurvivors at: 2) announcements size equals: 1. self assert: aWidget announcements size equals: 1. aWidget := nil. self assert: (self garbageCollectUntil: [(theSurvivors at: 1) isNil and: [(theSurvivors at: 2) isNil]]). ^theSurvivors ).

  • Strong subscriptions still keep their subscribers alive, as they should.
  • A weak subscriber that has died can still receive announcements until the finalization process has removed it, shortly after the garbage collection that notices its death, exactly as with Pharo's weak subscriptions.

Old-style WeakAnnouncementSubscription AbstractAnnouncementSubscription << #WeakAnnouncementSubscription layout: WeakLayout; slots: { #next }; tag: 'Subscription'; package: 'Announcements-Core' s moved into a mixed registry, for example when an announcer switches registries after it already has subscriptions, keep their global entry and therefore the old behaviour; the registry reports such a mix through GtMixedSubscriptionRegistry>>#hasLeakProneSubscriptionMix hasLeakProneSubscriptionMix ^self protected: [(strongSubscriptions contains: [:each | each isWeakSubscription]) and: [strongSubscriptions contains: [:each | each isWeakSubscription not]]] .

How to use the registry is described on the page Mixed subscription registry: overview, how it works inside on the page Mixed subscription registry: design.