Mixed subscription registry: overview

GtMixedSubscriptionRegistry Object << #GtMixedSubscriptionRegistry slots: { #monitor . #strongSubscriptions . #weakSubscriptions . #lastChange }; tag: 'Mixed-Core'; package: 'GToolkit-PharoBasePatch-Subscriptions' is a subscription registry an Announcer Object << #Announcer slots: { #registry . #preventedAnnouncements . #storedAnnouncements . #suspendedCount }; tag: 'Base'; package: 'Announcements-Core' can use instead of Pharo's SubscriptionRegistry Object << #SubscriptionRegistry slots: { #subscriptions . #monitor }; tag: 'Subscription'; package: 'Announcements-Core' . It understands the same messages and accepts the same subscriptions, and it lets one announcer have strong and weak subscribers at the same time without leaking:

  • Strong subscriptions behave as before: the announcer keeps their subscribers alive.
  • Weak subscriptions reference their subscriber weakly. Instead of one entry per subscription in the global FinalizationRegistryObject << #FinalizationRegistry slots: { #semaphore . #errorHandler . #ephemeronList }; sharedVariables: { #Default }; tag: 'Registry'; package: 'System-Finalization', the registry keeps one ephemeron per weak subscriber itself, so a live weak subscriber can no longer keep the announcer and its strong subscribers alive, and unsubscribing leaves nothing behind.

Why Pharo's registries leak in this situation, and how this one avoids it, is explained on the page "How mixing weak and strong announcement subscriptions leaks memory".

The registry keeps its strong subscriptions in a set, as Pharo does. Its weak subscriptions are grouped by subscriber, and each group is held behind one ephemeron, keyed on the subscriber, that only the registry references. When a weak subscriber is garbage collected, the registry drops its whole group; unsubscribing simply removes the group. Announcers without weak subscribers share one empty weak part, so they pay nothing for it. How the registry locks, matches and delivers is described on the design page.

Install the registry when the announcer is created, then subscribe as with any announcer. Strong subscriptions are made as usual, weak ones through #selector weak "announcer weak subscribe: foo" "GT patch: my registry chooses the weak builder, see implementors of #weakSubscriptionBuilderFor:" <gtPharoPatch: #Pharo> ^registry weakSubscriptionBuilderFor: self ; a weak block subscription always names its subscriber with #selector when: anAnnouncementClass do: aValuable for: aSubscriber | aSubscription aBuilderOfTheCurrentRegistry | aSubscription := self subscriptionTo: anAnnouncementClass do: aValuable for: aSubscriber. aBuilderOfTheCurrentRegistry := announcer subscriptions weakSubscriptionBuilderFor: announcer. ^announcer basicSubscribe: (aSubscription subscriptionToMoveWith: aBuilderOfTheCurrentRegistry) , and lives as long as that object.

In this snippet the model is subscribed strongly and the element weakly, once with a message and once with a block; after #selector unsubscribe: anObject "Unsubscribe all subscriptions of anObject from the receiver" registry removeSubscriber: anObject only the model's subscription remains:

| announcer aModel anElement |
announcer := Announcer new useMixedSubscriptionRegistry.
aModel := OrderedCollection new.
anElement := OrderedCollection new.
announcer when: Announcement send: #add: to: aModel.
announcer weak when: Announcement send: #add: to: anElement.
announcer weak
	when: Announcement
	do: [ :anAnnouncement | anElement add: anAnnouncement ]
	for: anElement.
announcer announce: Announcement new.
announcer unsubscribe: anElement.
announcer
  

The block refers to anElement. With a plain registry this weak block subscription would keep anElement alive as long as the announcer lives; with the mixed registry it does not.

The next example shows what a weak subscription is in this registry: #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 send: aSelector to: anObject ^self when: anAnnouncementClass do: (WeakMessageSend receiver: anObject selector: aSelector) for: anObject creates a GtEphemeronAnnouncementSubscription AbstractAnnouncementSubscription << #GtEphemeronAnnouncementSubscription slots: { #subscriberReference }; tag: 'Mixed-Core'; package: 'GToolkit-PharoBasePatch-Subscriptions' whose action is a WeakMessageSend MessageSend << #WeakMessageSend layout: WeakLayout; slots: { #shouldBeNil }; tag: 'Messaging'; package: 'Kernel' ; it is kept in the weak part (no strong subscriptions, one weak subscriber), and only announcements it handles reach the subscriber (a JobStart JobAnnouncement << #JobStart slots: {}; tag: 'Announcements'; package: 'Jobs' does, a JobEnd JobAnnouncement << #JobEnd slots: {}; tag: 'Announcements'; package: 'Jobs' does not). It answers the announcer, which can be inspected: GtMixedSubscriptionRegistryExamples>>#weakSubscriptionDelivers weakSubscriptionDelivers <gtExample> | anAnnouncer aSubscriber aSubscription | anAnnouncer := self announcerWithMixedRegistry. aSubscriber := self newSubscriber. aSubscription := anAnnouncer weak when: JobStart send: #onAnnouncement: to: aSubscriber. self assert: aSubscription class equals: GtEphemeronAnnouncementSubscription. self assert: aSubscription subscriber == aSubscriber. self assert: aSubscription action class equals: WeakMessageSend. self assert: aSubscription announcer == anAnnouncer. self assert: anAnnouncer subscriptions allStrongSubscriptions isEmpty. self assert: anAnnouncer subscriptions allWeakSubscriptions equals: (Array with: aSubscription). self assert: anAnnouncer subscriptions numberOfWeakSubscribers equals: 1. anAnnouncer announce: JobStart new. anAnnouncer announce: JobEnd new. self assert: aSubscriber announcements size equals: 1. ^anAnnouncer A weak subscription without a subscriber, or whose action is its own subscriber, is refused with an error, because it could never be collected or would vanish at the next garbage collection (GtMixedSubscriptionRegistryExamples>>#weakSubscriptionNeedsASubscriber weakSubscriptionNeedsASubscriber <gtExample> | anAnnouncer anErrorText | anAnnouncer := self announcerWithMixedRegistry. anErrorText := [anAnnouncer weak when: JobStart send: #yourself to: nil. nil] on: Error do: [:anError | anError messageText]. self assert: anErrorText equals: 'A weak subscription needs a subscriber that can be garbage collected'. self assert: anAnnouncer subscriptions isEmpty. ^anAnnouncer , GtMixedSubscriptionRegistryExamples>>#valuableThatIsItsOwnSubscriberCannotBeSubscribedWeakly valuableThatIsItsOwnSubscriberCannotBeSubscribedWeakly <gtExample> | anAnnouncer aBlock anErrorText | anAnnouncer := self announcerWithMixedRegistry. aBlock := [:anAnnouncement | anAnnouncement]. anErrorText := [anAnnouncer weak when: JobStart do: aBlock for: aBlock. nil] on: Error do: [:anError | anError messageText]. self assert: anErrorText equals: 'A valuable that is its own subscriber cannot be subscribed weakly'. self assert: anAnnouncer subscriptions isEmpty. ^anAnnouncer ).

SubscriptionRegistry Object << #SubscriptionRegistry slots: { #subscriptions . #monitor }; tag: 'Subscription'; package: 'Announcements-Core' FastSubscriptionRegistry Object << #FastSubscriptionRegistry slots: { #monitor . #subscriberMap }; tag: 'Core'; package: 'GToolkit-PharoBasePatch-Subscriptions' GtMixedSubscriptionRegistry Object << #GtMixedSubscriptionRegistry slots: { #monitor . #strongSubscriptions . #weakSubscriptions . #lastChange }; tag: 'Mixed-Core'; package: 'GToolkit-PharoBasePatch-Subscriptions'
Used by every new Announcer Object << #Announcer slots: { #registry . #preventedAnnouncements . #storedAnnouncements . #suspendedCount }; tag: 'Base'; package: 'Announcements-Core' SystemAnnouncer Announcer << #SystemAnnouncer slots: {}; tag: 'Core'; package: 'System-Announcements' in GT announcers that opt in
Strong subscription keeps its subscriber alive yes no yes
Global finalization entry per weak subscription yes yes no
A live weak subscriber keeps the announcer alive yes, with its strong subscribers yes no
A weak block subscription whose block refers to its subscriber keeps it alive yes no no
Something left behind after unsubscribing yes, until the subscriber dies yes, until the subscriber dies no

SubscriptionRegistry Object << #SubscriptionRegistry slots: { #subscriptions . #monitor }; tag: 'Subscription'; package: 'Announcements-Core' is Pharo's registry. FastSubscriptionRegistry Object << #FastSubscriptionRegistry slots: { #monitor . #subscriberMap }; tag: 'Core'; package: 'GToolkit-PharoBasePatch-Subscriptions' is the registry GT installs for the SystemAnnouncer Announcer << #SystemAnnouncer slots: {}; tag: 'Core'; package: 'System-Announcements' ; it keys all subscriptions by subscriber in a weak-key dictionary, so not even its strong subscriptions keep their subscribers alive.

Measured against a plain SubscriptionRegistry Object << #SubscriptionRegistry slots: { #subscriptions . #monitor }; tag: 'Subscription'; package: 'Announcements-Core' :

  • Subscribing and unsubscribing weakly is faster: a weak subscription takes 1.1 µs instead of 2.7 µs, and when many subscribers come and go the mixed registry is about 10 times faster (683 page view models created on one page and unsubscribed: 10 µs instead of 96 µs per view model). A plain weak subscription creates a global finalization entry, and a plain #selectorunsubscribe: anObject "Unsubscribe all subscriptions of anObject from the receiver" registry removeSubscriber: anObject scans all subscriptions.
  • Strong subscriptions are a little slower: subscribing and unsubscribing takes 960 ns instead of 720 ns, partly because the lock is reentrant.
  • Delivering an announcement takes about as long as with a plain registry for a few subscribers (1.9 µs for one strong subscriber in both), and about twice as long for 100 or more weak subscribers, because the weak part is walked in two levels, subscribers and then their subscriptions. It never allocates more than the plain registry (2.8 KB instead of 3.5 KB for one strong subscriber, 3.5 KB instead of 3.7 KB for 1,000 weak subscribers), because only the subscriptions that handle the announcement are collected.
  • Memory: an empty registry takes 184 bytes instead of 128. Most announcers never get a weak subscriber and pay nothing more; weak subscriptions take about as much memory as plain ones.

The measurements and where the overhead comes from are on the page "Mixed subscription registry: design".

  • #selectorunsubscribe: anObject "Unsubscribe all subscriptions of anObject from the receiver" registry removeSubscriber: anObject and #selectorremoveSubscription: subscription "Remove the given subscription from the receiver" ^ registry remove: subscription remove the subscriptions completely (GtMixedSubscriptionRegistryExamples>>#unsubscribeRemovesStrongAndWeakSubscriptionsunsubscribeRemovesStrongAndWeakSubscriptions <gtExample> | anAnnouncer aSubscriber anotherSubscriber theRemoved | anAnnouncer := self announcerWithMixedRegistry. aSubscriber := self newSubscriber. anotherSubscriber := self newSubscriber. anAnnouncer when: JobStart send: #onAnnouncement: to: aSubscriber. anAnnouncer weak when: JobStart send: #onAnnouncement: to: aSubscriber. anAnnouncer weak when: JobStart send: #onAnnouncement: to: anotherSubscriber. theRemoved := anAnnouncer subscriptions removeSubscriber: aSubscriber. self assert: theRemoved size equals: 2. self assert: anAnnouncer numberOfSubscriptions equals: 1. self assert: (anAnnouncer hasSubscriber: aSubscriber) not. self assert: anAnnouncer subscriptions numberOfWeakSubscribers equals: 1. anAnnouncer unsubscribe: anotherSubscriber. self assert: anAnnouncer subscriptions isEmpty. self assert: anAnnouncer subscriptions numberOfWeakSubscribers equals: 0. anAnnouncer announce: JobStart new. self assert: aSubscriber announcements isEmpty. self assert: anotherSubscriber announcements isEmpty. ^anAnnouncer).
  • #selectormakeStrong | aSubscriber | aSubscriber := self subscriber. aSubscriber ifNil: [^self error: 'Subscriber is nil, cannot make strong subscription']. ^announcer subscriptions makeStrong: self for: aSubscriber moves a weak subscription to the strong part; as in Pharo, the weak subscription becomes the strong one, so references to it stay valid (GtMixedSubscriptionRegistryExamples>>#makeStrongMovesWeakSubscriptionToStrongPartmakeStrongMovesWeakSubscriptionToStrongPart <gtExample> | anAnnouncer aSubscriber aSubscription aStrongSubscription | anAnnouncer := self announcerWithMixedRegistry. aSubscriber := self newSubscriber. aSubscription := anAnnouncer weak when: JobStart send: #onAnnouncement: to: aSubscriber. aStrongSubscription := aSubscription makeStrong. self assert: aSubscription == aStrongSubscription. self assert: aStrongSubscription class equals: AnnouncementSubscription. self assert: aStrongSubscription subscriber == aSubscriber. self assert: aStrongSubscription action class equals: MessageSend. self assert: anAnnouncer subscriptions allStrongSubscriptions equals: (Array with: aStrongSubscription). self assert: anAnnouncer subscriptions numberOfWeakSubscribers equals: 0. anAnnouncer announce: JobStart new. self assert: aSubscriber announcements size equals: 1. anAnnouncer removeSubscription: aSubscription. self assert: anAnnouncer subscriptions isEmpty. ^anAnnouncer).
  • #selectormakeWeak "GT patch: the weak builder of my announcer builds the subscription that replaces me, see implementors of #weakSubscriptionFrom:" <gtPharoPatch: #Pharo> ^announcer replace: self with: (announcer weak weakSubscriptionFrom: self) answers a new weak subscription in the weak part; as in Pharo, the old strong subscription object is not changed, so use the answered one (GtMixedSubscriptionRegistryExamples>>#makeWeakInMixedRegistryBuildsEphemeronSubscriptionmakeWeakInMixedRegistryBuildsEphemeronSubscription <gtExample> | anAnnouncer aSubscriber aStrongSubscription aWeakSubscription | anAnnouncer := self announcerWithMixedRegistry. aSubscriber := self newSubscriber. aStrongSubscription := anAnnouncer when: JobStart send: #onAnnouncement: to: aSubscriber. aWeakSubscription := aStrongSubscription makeWeak. self assert: aWeakSubscription class equals: GtEphemeronAnnouncementSubscription. self assert: aWeakSubscription subscriber == aSubscriber. self assert: aWeakSubscription action class equals: WeakMessageSend. self assert: aWeakSubscription action receiver == aSubscriber. self assert: anAnnouncer subscriptions allStrongSubscriptions isEmpty. self assert: anAnnouncer subscriptions allWeakSubscriptions equals: (Array with: aWeakSubscription). anAnnouncer announce: JobStart new. self assert: aSubscriber announcements size equals: 1. ^anAnnouncer).
  • #selectorsubscriber: aSubscriber announcer ifNil: [self basicSubscriber: aSubscriber] ifNotNil: [self class assertSubscriber: aSubscriber canBeWeakFor: action. announcer subscriptions changeSubscriberOf: self to: aSubscriber] files a weak subscription under its new subscriber (GtMixedSubscriptionRegistryExamples>>#changingTheSubscriberRefilesTheSubscriptionchangingTheSubscriberRefilesTheSubscription <gtExample> | anAnnouncer aFirstSubscriber aSecondSubscriber aSubscription | anAnnouncer := self announcerWithMixedRegistry. aFirstSubscriber := self newSubscriber. aSecondSubscriber := self newSubscriber. aSubscription := anAnnouncer weak when: JobStart send: #onAnnouncement: to: aFirstSubscriber. self assert: (aSubscription subscriber: aSecondSubscriber) == aSubscription. self assert: aSubscription subscriber == aSecondSubscriber. self assert: (anAnnouncer hasSubscriber: aSecondSubscriber). self assert: (anAnnouncer hasSubscriber: aFirstSubscriber) not. self assert: (anAnnouncer subscriptions ephemeronOf: aFirstSubscriber) isNil. self assert: anAnnouncer subscriptions numberOfWeakSubscribers equals: 1. anAnnouncer announce: JobStart new. self assert: aFirstSubscriber announcements size equals: 1. anAnnouncer unsubscribe: aSecondSubscriber. self assert: anAnnouncer subscriptions isEmpty. ^anAnnouncer).
  • Announcer>>#useSubscriptionRegistry:useSubscriptionRegistry: aSubscriptionRegistry | aWeakSubscriptionBuilder | aWeakSubscriptionBuilder := aSubscriptionRegistry weakSubscriptionBuilderFor: self. registry protected: [registry subscriptions asArray do: [:each | aSubscriptionRegistry add: (each subscriptionToMoveWith: aWeakSubscriptionBuilder)]. registry := aSubscriptionRegistry] moves an announcer to another registry with its subscriptions. Moved to a plain registry, weak subscriptions become WeakAnnouncementSubscriptionAbstractAnnouncementSubscription << #WeakAnnouncementSubscription layout: WeakLayout; slots: { #next }; tag: 'Subscription'; package: 'Announcements-Core's, and those with a block action become strong subscriptions. Moved into a mixed registry, old-style weak subscriptions keep their behaviour, so install the registry before subscribing.
  • A dead weak subscriber can still receive announcements until the finalization process has removed it, shortly after the garbage collection that notices its death (a scavenge for young objects, a full collection for old ones), as with Pharo's weak subscriptions.
  • Holding a weak subscription does not keep its subscriber alive, unless its action references the subscriber, for example a block that captures it.
  • #selectorsubscriptions ^self protected: [Array streamContents: [:aStream | self subscriptionsDo: [:each | aStream nextPut: each]]] answers a copy, an ArrayArrayedCollection << #Array layout: VariableLayout; slots: {}; tag: 'Base'; package: 'Collections-Sequenceable'; delivery reaches strong subscribers before weak ones.
  • As in Pharo's registry, announcements are matched under the registry's lock, so matching code such as a #selectorwhere: instancesFilterBlock ^AnnouncementDeliveryCondition for: self where: instancesFilterBlock condition should be short. If such code changes the registry while it is matched, the registry matches again on its subscriptions as they are then.
  • A shallow #selectorcopy "Answer another instance just like the receiver. Subclasses typically override postCopy; they typically do not override shallowCopy. Copy is a template method in the sense of Design Patterns. So do not override it. Override postCopy instead. Pay attention that normally you should call postCopy of your superclass too." ^ self shallowCopy postCopy of a registry gets its own sets and ephemerons but shares the subscription objects with the original.
  • Never send #selectordeepCopy "Answer a copy of the receiver with its own copy of each instance variable. deepCopy does a deep copy. It should never be overridden and only be used if you want to get these very specific semantics. It doesn't handle cycles, #veryDeepCopy does. In the future we will make it handle cycles and deprecate veryDeepCopy" | newObject class index | class := self class. (class == Object) ifTrue: [^self]. class isVariable ifTrue: [index := self basicSize. newObject := class basicNew: index. [index > 0] whileTrue: [newObject basicAt: index put: (self basicAt: index) deepCopy. index := index - 1]] ifFalse: [newObject := class basicNew]. index := class instSize. [index > 0] whileTrue: [newObject instVarAt: index put: (self instVarAt: index) deepCopy. index := index - 1]. ^newObject or #selectorstoreString "Answer a String representation of the receiver from which the receiver can be reconstructed." ^ String streamContents: [:s | self storeOn: s] to an announcer, a registry or a subscription: they contain cycles, and both recurse until memory runs out. This is the same with Pharo's registries.

Lepiter models (pages, snippets, databases and their store monitors) create their announcers through LeUseMixedSubscriptionRegistryFlag>>#newAnnouncer newAnnouncer ^self isEnabled ifTrue: [Announcer new useMixedSubscriptionRegistry] ifFalse: [Announcer new] . The flag LeUseMixedSubscriptionRegistryFlag Object << #LeUseMixedSubscriptionRegistryFlag slots: {}; sharedVariables: { #Enabled }; package: 'Lepiter-Core' is disabled by default; when it is enabled, models created afterwards use the mixed registry, so it must be enabled before the databases are loaded. With the flag enabled, a load of the Glamorous Toolkit Book needs 2,051 fewer global finalization entries, one per model subscription. LeUseMixedSubscriptionRegistryFlag>>#usePlainSubscriptionRegistriesIn: usePlainSubscriptionRegistriesIn: aLepiterModel aLepiterModel withAllAnnouncersDo: [:each | each useSubscriptionRegistry: SubscriptionRegistry new] moves the announcers of a loaded database back to plain registries if needed.

How the registry works inside, why it is built this way, its performance and its limitations are described on the page Mixed subscription registry: design.