Mixed subscription registry: design
This page explains how GtMixedSubscriptionRegistry
Object << #GtMixedSubscriptionRegistry
slots: { #monitor . #strongSubscriptions . #weakSubscriptions . #lastChange };
tag: 'Mixed-Core';
package: 'GToolkit-PharoBasePatch-Subscriptions'
works and why it is built this way. What it is for is on the page Mixed subscription registry: overview, the leak it removes on the page How mixing weak and strong announcement subscriptions leaks memory. The statements below are backed by examples in GtMixedSubscriptionRegistryExamples
Object << #GtMixedSubscriptionRegistryExamples
slots: {};
tag: 'Mixed-Examples';
package: 'GToolkit-PharoBasePatch-Subscriptions'
or by measurements made while the registry was built.
|
Component
|
Role
|
GtMixedSubscriptionRegistry
Object << #GtMixedSubscriptionRegistry
slots: { #monitor . #strongSubscriptions . #weakSubscriptions . #lastChange };
tag: 'Mixed-Core';
package: 'GToolkit-PharoBasePatch-Subscriptions'
|
The registry: strong subscriptions in an IdentitySet
Set << #IdentitySet
slots: {};
tag: 'Sets';
package: 'Collections-Unordered'
, weak ones in a separate weak part, a reentrant lock.
|
GtNoWeakSubscriptions
GtAbstractWeakSubscriptions << #GtNoWeakSubscriptions
slots: {};
sharedVariables: { #UniqueInstance };
tag: 'Mixed-Core';
package: 'GToolkit-PharoBasePatch-Subscriptions'
/ GtWeakSubscriptions
GtAbstractWeakSubscriptions << #GtWeakSubscriptions
slots: { #ephemerons };
tag: 'Mixed-Core';
package: 'GToolkit-PharoBasePatch-Subscriptions'
|
The weak part: a stateless shared empty part, or a dictionary of one ephemeron per weak subscriber.
|
GtEphemeronAnnouncementSubscription
AbstractAnnouncementSubscription << #GtEphemeronAnnouncementSubscription
slots: { #subscriberReference };
tag: 'Mixed-Core';
package: 'GToolkit-PharoBasePatch-Subscriptions'
|
A weak subscription: its subscriber in a one-slot WeakArray
Array << #WeakArray
layout: WeakLayout;
slots: {};
tag: 'Base';
package: 'Collections-Weak'
, its action usually a WeakMessageSend
MessageSend << #WeakMessageSend
layout: WeakLayout;
slots: { #shouldBeNil };
tag: 'Messaging';
package: 'Kernel'
.
|
GtEphemeronSubscriptionBuilder
Object << #GtEphemeronSubscriptionBuilder
slots: { #announcer };
tag: 'Mixed-Core';
package: 'GToolkit-PharoBasePatch-Subscriptions'
|
Answered by #selector
weak
"announcer weak subscribe: foo"
"GT patch: my registry chooses the weak builder, see implementors of #weakSubscriptionBuilderFor:"
<gtPharoPatch: #Pharo>
^registry weakSubscriptionBuilderFor: self
; builds weak subscriptions.
|
GtEphemeronSubscriptionsMourner
Object << #GtEphemeronSubscriptionsMourner
slots: { #registry . #ephemeron };
tag: 'Mixed-Core';
package: 'GToolkit-PharoBasePatch-Subscriptions'
|
The container of one ephemeron; when it is mourned it asks the registry to remove exactly that ephemeron.
|
Announcer>>#weak
weak
"announcer weak subscribe: foo"
"GT patch: my registry chooses the weak builder, see implementors of #weakSubscriptionBuilderFor:"
<gtPharoPatch: #Pharo>
^registry weakSubscriptionBuilderFor: self
, AnnouncementSubscription>>#makeWeak
makeWeak
"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)
|
GT patches that ask the announcer's registry for its weak builder, so Pharo's registries keep their exact behaviour.
|
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, with its subscriptions, to another registry.
|
An announcer holds its registry, a GtMixedSubscriptionRegistry
Object << #GtMixedSubscriptionRegistry
slots: { #monitor . #strongSubscriptions . #weakSubscriptions . #lastChange };
tag: 'Mixed-Core';
package: 'GToolkit-PharoBasePatch-Subscriptions'
, which has four parts:
strongSubscriptions: an IdentitySetSet << #IdentitySet
slots: {};
tag: 'Sets';
package: 'Collections-Unordered' with the strong subscriptions, as in a plain registry. Old-style WeakAnnouncementSubscriptionAbstractAnnouncementSubscription << #WeakAnnouncementSubscription
layout: WeakLayout;
slots: { #next };
tag: 'Subscription';
package: 'Announcements-Core's added to the registry are kept here too.weakSubscriptions: the weak part. As long as there is no weak subscriber, it is GtNoWeakSubscriptionsGtAbstractWeakSubscriptions << #GtNoWeakSubscriptions
slots: {};
sharedVariables: { #UniqueInstance };
tag: 'Mixed-Core';
package: 'GToolkit-PharoBasePatch-Subscriptions', one stateless object shared by all registries. With the first weak subscriber it becomes a GtWeakSubscriptionsGtAbstractWeakSubscriptions << #GtWeakSubscriptions
slots: { #ephemerons };
tag: 'Mixed-Core';
package: 'GToolkit-PharoBasePatch-Subscriptions' of this registry.monitor: the reentrant MutexObject << #Mutex
slots: { #semaphore . #owner };
tag: 'Processes';
package: 'Kernel' that every change and every query takes.lastChange: a new object after every change, so that delivery notices when matching code changed the registry (decision 7).
A GtWeakSubscriptions
GtAbstractWeakSubscriptions << #GtWeakSubscriptions
slots: { #ephemerons };
tag: 'Mixed-Core';
package: 'GToolkit-PharoBasePatch-Subscriptions'
holds an IdentityDictionary
Dictionary << #IdentityDictionary
slots: {};
tag: 'Dictionaries';
package: 'Collections-Unordered'
with one ephemeron, a WeakKeyAssociation
Association << #WeakKeyAssociation
layout: EphemeronLayout;
slots: { #container };
tag: 'Dictionaries';
package: 'Collections-Weak'
, per weak subscriber. The ephemeron is itself the entry of the dictionary, so the dictionary reaches the subscriber only through the ephemeron's key:
- the key is the subscriber;
- the value is an
IdentitySetSet << #IdentitySet
slots: {};
tag: 'Sets';
package: 'Collections-Unordered' with that subscriber's GtEphemeronAnnouncementSubscriptionAbstractAnnouncementSubscription << #GtEphemeronAnnouncementSubscription
slots: { #subscriberReference };
tag: 'Mixed-Core';
package: 'GToolkit-PharoBasePatch-Subscriptions's; - the container is a
GtEphemeronSubscriptionsMournerObject << #GtEphemeronSubscriptionsMourner
slots: { #registry . #ephemeron };
tag: 'Mixed-Core';
package: 'GToolkit-PharoBasePatch-Subscriptions', which knows the registry and this ephemeron. When the ephemeron is mourned, it asks the registry to remove exactly this ephemeron.
A weak subscription, a GtEphemeronAnnouncementSubscription
AbstractAnnouncementSubscription << #GtEphemeronAnnouncementSubscription
slots: { #subscriberReference };
tag: 'Mixed-Core';
package: 'GToolkit-PharoBasePatch-Subscriptions'
, references:
- its subscriber weakly, through a one-slot
WeakArrayArray << #WeakArray
layout: WeakLayout;
slots: {};
tag: 'Base';
package: 'Collections-Weak'; - its action, usually a
WeakMessageSendMessageSend << #WeakMessageSend
layout: WeakLayout;
slots: { #shouldBeNil };
tag: 'Messaging';
package: 'Kernel', which references its receiver weakly, or a block, which references what it captures strongly; - its announcer strongly, like every Pharo subscription.
So, unless another object holds a weak subscription itself, the only path to it goes through the announcer. Nothing global references the ephemerons: when the announcer becomes garbage, its ephemerons are garbage too and are never mourned. The mourner points at the registry, not at the weak part, so a mourn always reaches the part the registry holds at that moment.
- Subscribe. The builder creates the subscription and the registry adds it to its subscriber's set, installing a fresh ephemeron for that subscriber (
GtMixedSubscriptionRegistry>>#addWeakSubscription:addWeakSubscription: aSubscription
| aSubscriber theSubscriptions |
aSubscriber := aSubscription subscriber.
aSubscriber ifNil: [^aSubscription].
theSubscriptions := self weakPart subscriptionsOf: aSubscriber
ifAbsent: [IdentitySet new].
theSubscriptions add: aSubscription.
self installGroupOf: aSubscriber holding: theSubscriptions.
^aSubscription).
- Deliver.
GtMixedSubscriptionRegistry>>#deliver:deliver: anAnnouncement
| theInterestedSubscriptions |
self isEmpty ifTrue: [^self].
theInterestedSubscriptions := self subscriptionsHandling: anAnnouncement.
theInterestedSubscriptions ifEmpty: [^self].
anAnnouncement prepareForDelivery.
self deliver: anAnnouncement to: theInterestedSubscriptions matches the announcement under the lock, collecting only the subscriptions that handle it (GtMixedSubscriptionRegistry>>#subscriptionsHandling:subscriptionsHandling: anAnnouncement
"Answer the subscriptions that handle anAnnouncement, matched under my lock as in SubscriptionRegistry.
Matching runs code of the subscriptions, such as a where: condition, and that code can change me while I iterate over my own collections, which can skip or repeat subscriptions. Every change stores a new object in lastChange (see #noteChange). If lastChange is no longer the object it was before matching, a change happened during matching, so I match again on a copy of my subscriptions as they are now."
^self protected:
[| aLastChange theInterested |
aLastChange := lastChange.
theInterested := OrderedCollection new: 4.
self subscriptionsDo:
[:each |
(each handlesAnnouncement: anAnnouncement)
ifTrue: [theInterested add: each]].
aLastChange == lastChange
ifTrue: [theInterested]
ifFalse:
[self subscriptions
select: [:each | each handlesAnnouncement: anAnnouncement]]]), and delivers to them outside the lock, strong subscriptions first. The collected subscriptions do not keep their subscribers alive during the delivery, because subscriptions reference them weakly (GtMixedSubscriptionRegistryExamples>>#weakSubscriberIsMournedByAScavengeDuringDeliveryweakSubscriberIsMournedByAScavengeDuringDelivery
<gtExample>
| anAnnouncer aTrigger theSurvivors |
anAnnouncer := self newAnnouncer.
aTrigger := self newSubscriber.
anAnnouncer
when: JobStart
do: [:anAnnouncement | Smalltalk garbageCollectMost]
for: aTrigger.
theSurvivors := self subscribeWeakSubscriberTo: anAnnouncer.
anAnnouncer announce: JobStart new.
self assert: (self
waitUntil: [anAnnouncer subscriptions numberOfWeakSubscribers = 0]).
self assert: anAnnouncer numberOfSubscriptions equals: 1.
^anAnnouncer).
- The subscriber dies. At the next collection that examines it (a scavenge if it is young, a full collection if it is old) the VM fires the ephemeron, and right after the collection the finalization process mourns it: the mourner calls
GtMixedSubscriptionRegistry>>#removeEphemeron:removeEphemeron: anEphemeron
self protectedChange:
[self weakPart: (self weakPart withoutEphemeron: anEphemeron)], which removes the group if this ephemeron is still the current one. The subscriber itself is freed one collection later (GtMixedSubscriptionRegistryExamples>>#firstCollectionMournsTheEntryfirstCollectionMournsTheEntry
<gtExample>
| anAnnouncer theSurvivors |
anAnnouncer := self newAnnouncer.
theSurvivors := self subscribeWeakSubscriberTo: anAnnouncer.
Smalltalk garbageCollect.
self assert: (self
waitUntil: [anAnnouncer subscriptions numberOfWeakSubscribers = 0]).
self assert: anAnnouncer subscriptions isEmpty.
self assert: (self garbageCollectUntil: [(theSurvivors at: 1) isNil]).
^anAnnouncer).
- Unsubscribe.
#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 subscription and, with the last one, the subscriber's entry. The ephemeron becomes garbage and is never mourned.
1. Ephemerons held by the registry, not by the global FinalizationRegistryObject << #FinalizationRegistry
slots: { #semaphore . #errorHandler . #ephemeronList };
sharedVariables: { #Default };
tag: 'Registry';
package: 'System-Finalization'. The VM recognises an ephemeron by its class layout, not by registration; any reachable WeakKeyAssociation
Association << #WeakKeyAssociation
layout: EphemeronLayout;
slots: { #container };
tag: 'Dictionaries';
package: 'Collections-Weak'
whose key dies is mourned. Held inside the registry, the ephemerons are reachable only through the announcer, so a live weak subscriber cannot keep the announcer alive (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
), removal is a dictionary operation, and a dead announcer costs no finalization work.
2. One ephemeron per subscriber. The ephemeron's key is the object whose death matters, and its value is the set of that subscriber's subscriptions (GtMixedSubscriptionRegistryExamples>>#weakSubscriptionsOfOneSubscriberShareOneEphemeron
weakSubscriptionsOfOneSubscriberShareOneEphemeron
<gtExample>
| anAnnouncer aSubscriber |
anAnnouncer := self announcerWithMixedRegistry.
aSubscriber := self newSubscriber.
(anAnnouncer weak)
when: JobStart send: #onAnnouncement: to: aSubscriber;
when: JobEnd send: #onAnnouncement: to: aSubscriber;
when: JobStart , JobEnd
send: #onAnnouncement:
to: aSubscriber.
self assert: anAnnouncer numberOfSubscriptions equals: 3.
self assert: anAnnouncer subscriptions numberOfWeakSubscribers equals: 1.
anAnnouncer announce: JobEnd new.
self assert: aSubscriber announcements size equals: 2.
^anAnnouncer
). This gives fewer ephemerons (about 54,000 subscriber/announcer pairs for 100,000 weak subscriptions in an image with many large Lepiter databases) and makes #selector
unsubscribe: anObject
"Unsubscribe all subscriptions of anObject from the receiver"
registry removeSubscriber: anObject
a single lookup. It also cleans up faster: when several ephemerons share a dead key, firing one makes the key reachable again for the rest of that collection, so only one of them fires per collection; seven subscriptions of one subscriber with seven ephemerons need seven scavenges, one group needs one (see the cleanup row under Performance). The price is that delivery walks two levels, subscribers and then their subscriptions.
3. Weak subscriptions reference their subscriber weakly. If a subscription held its subscriber strongly, anything holding the subscription, including the list of subscriptions a delivery is working through, would keep the subscriber alive, and a dying subscriber could survive scavenges and keep receiving announcements. With a WeakArray
Array << #WeakArray
layout: WeakLayout;
slots: {};
tag: 'Base';
package: 'Collections-Weak'
and a WeakMessageSend
MessageSend << #WeakMessageSend
layout: WeakLayout;
slots: { #shouldBeNil };
tag: 'Messaging';
package: 'Kernel'
, the ephemeron is the only thing that tracks the subscriber's death.
4. A fresh ephemeron for every weak add, removed only by identity. A fired ephemeron cannot be reused, and its mourn can arrive late, after the subscriber was unsubscribed and subscribed again. WeakKeyAssociation
Association << #WeakKeyAssociation
layout: EphemeronLayout;
slots: { #container };
tag: 'Dictionaries';
package: 'Collections-Weak'
's #selector
mourn
container removeKey: key ifAbsent: [
"Do Nothing. Probably somebody removed the key while I was in the mourn queue" ]
removes by key, so every add installs a new ephemeron, and the mourner removes an entry only while it is still that ephemeron (GtWeakSubscriptions>>#withoutEphemeron:
withoutEphemeron: anEphemeron
(ephemerons associationAt: anEphemeron key ifAbsent: [nil]) == anEphemeron
ifTrue: [ephemerons removeKey: anEphemeron key].
^self releasedWhenEmpty
, GtMixedSubscriptionRegistryExamples>>#staleMournKeepsTheEntryOfAResubscription
staleMournKeepsTheEntryOfAResubscription
<gtExample>
| anAnnouncer aSubscriber aStaleEphemeron |
anAnnouncer := self announcerWithMixedRegistry.
aSubscriber := self newSubscriber.
anAnnouncer weak when: JobStart send: #onAnnouncement: to: aSubscriber.
aStaleEphemeron := anAnnouncer subscriptions ephemeronOf: aSubscriber.
anAnnouncer unsubscribe: aSubscriber.
anAnnouncer weak when: JobStart send: #onAnnouncement: to: aSubscriber.
self assert: (anAnnouncer subscriptions ephemeronOf: aSubscriber)
~~ aStaleEphemeron.
aStaleEphemeron mourn.
self assert: (anAnnouncer hasSubscriber: aSubscriber).
self assert: anAnnouncer subscriptions numberOfWeakSubscribers equals: 1.
anAnnouncer announce: JobStart new.
self assert: aSubscriber announcements size equals: 1.
^anAnnouncer
). WeakKeyAssociation
Association << #WeakKeyAssociation
layout: EphemeronLayout;
slots: { #container };
tag: 'Dictionaries';
package: 'Collections-Weak'
's #selector
mourn
container removeKey: key ifAbsent: [
"Do Nothing. Probably somebody removed the key while I was in the mourn queue" ]
sends #selector
removeKey: aSubscriber ifAbsent: aBlock
registry removeEphemeron: ephemeron
to the ephemeron's container, so a small container object, the mourner, is enough to remove exactly this ephemeron; no subclass of WeakKeyAssociation
Association << #WeakKeyAssociation
layout: EphemeronLayout;
slots: { #container };
tag: 'Dictionaries';
package: 'Collections-Weak'
is needed.
5. A reentrant lock. The lock is a Mutex
Object << #Mutex
slots: { #semaphore . #owner };
tag: 'Processes';
package: 'Kernel'
because BlHandlerAnnouncerRegistry
BlHandlerRegistry << #BlHandlerAnnouncerRegistry
slots: { #announcer };
tag: 'Events-Dispatcher';
package: 'Bloc'
sends #selector
subscriptions
^self protected:
[Array
streamContents: [:aStream | self subscriptionsDo: [:each | aStream nextPut: each]]]
inside #selector
protected: aBlock
^monitor critical: aBlock
(GtMixedSubscriptionRegistryExamples>>#lockIsReentrant
lockIsReentrant
<gtExample>
| anAnnouncer aSubscriber theSubscriptions |
anAnnouncer := self announcerWithMixedRegistry.
aSubscriber := self newSubscriber.
anAnnouncer weak when: JobStart send: #onAnnouncement: to: aSubscriber.
theSubscriptions := anAnnouncer subscriptions
protected: [anAnnouncer subscriptions subscriptions copy asArray].
self assert: theSubscriptions size equals: 1.
^anAnnouncer
).
6. Matching under the lock, as in Pharo. Like SubscriptionRegistry
Object << #SubscriptionRegistry
slots: { #subscriptions . #monitor };
tag: 'Subscription';
package: 'Announcements-Core'
, delivery matches the announcement under the lock and collects only the subscriptions that handle it, then delivers outside the lock (GtMixedSubscriptionRegistry>>#subscriptionsHandling:
subscriptionsHandling: anAnnouncement
"Answer the subscriptions that handle anAnnouncement, matched under my lock as in SubscriptionRegistry.
Matching runs code of the subscriptions, such as a where: condition, and that code can change me while I iterate over my own collections, which can skip or repeat subscriptions. Every change stores a new object in lastChange (see #noteChange). If lastChange is no longer the object it was before matching, a change happened during matching, so I match again on a copy of my subscriptions as they are now."
^self protected:
[| aLastChange theInterested |
aLastChange := lastChange.
theInterested := OrderedCollection new: 4.
self subscriptionsDo:
[:each |
(each handlesAnnouncement: anAnnouncement)
ifTrue: [theInterested add: each]].
aLastChange == lastChange
ifTrue: [theInterested]
ifFalse:
[self subscriptions
select: [:each | each handlesAnnouncement: anAnnouncement]]]
, GtMixedSubscriptionRegistryExamples>>#matchingHoldsTheLockAndDeliveryDoesNot
matchingHoldsTheLockAndDeliveryDoesNot
<gtExample>
| anAnnouncer aSubscriber theStatesWhileMatching wasFreeWhileDelivering |
anAnnouncer := self announcerWithMixedRegistry.
aSubscriber := self newSubscriber.
theStatesWhileMatching := OrderedCollection new.
anAnnouncer
when: (JobStart where:
[:anAnnouncement |
theStatesWhileMatching isEmpty
ifTrue:
[theStatesWhileMatching
add: (self forkChangeOf: anAnnouncer) isTerminated not].
true])
do: [:anAnnouncement | wasFreeWhileDelivering := (self forkChangeOf: anAnnouncer) isTerminated]
for: aSubscriber.
anAnnouncer announce: JobStart new.
self assert: theStatesWhileMatching asArray equals: #(true).
self assert: wasFreeWhileDelivering.
self assert: anAnnouncer numberOfSubscriptions equals: 3.
^anAnnouncer
). Only the interested subscriptions are copied, so delivery allocates no more than with a plain registry, also when subscriptions come and go between announcements. When nothing changes, a condition is evaluated as often as with a plain registry: once while matching and once more by the subscription's own AbstractAnnouncementSubscription>>#deliver:
deliver: anAnnouncement
"Deliver an announcement to receiver. In case of failure, it will be handled in separate process"
(self handlesAnnouncement: anAnnouncement) ifTrue: [
[ action cull: anAnnouncement cull: announcer ]
on: UnhandledError
fork: [ :ex | ex pass ] ]
(GtMixedSubscriptionRegistryExamples>>#conditionIsEvaluatedAsOftenAsInAPlainRegistry
conditionIsEvaluatedAsOftenAsInAPlainRegistry
<gtExample>
| theMixedEvaluations |
theMixedEvaluations := self
evaluationsOfAConditionAnnouncedIn: self announcerWithMixedRegistry.
self assert: theMixedEvaluations
equals: (self evaluationsOfAConditionAnnouncedIn: Announcer new).
^theMixedEvaluations
).
7. A change marker. Matching runs code of the subscriptions, such as #selector
where: instancesFilterBlock
^AnnouncementDeliveryCondition for: self where: instancesFilterBlock
conditions and Bloc's #selector
wantsEvent: anEvent
^ false
, and that code can change the registry while it is matched. Every change runs through GtMixedSubscriptionRegistry>>#protectedChange:
protectedChange: aBlock
^ self
protected: [ self noteChange.
aBlock value ]
, which takes the lock and stores a new marker object (GtMixedSubscriptionRegistry>>#noteChange
noteChange
lastChange := Object new
). When the marker changed during matching, matching is repeated on a copy of the subscriptions as they are then, so the announcement reaches exactly the subscriptions present after matching. The marker is an object rather than a counter, so registries that already exist when the code is loaded need no migration: a marker that is still nil just means no change yet. Examples:
GtMixedSubscriptionRegistryExamples>>#everyChangeOfTheRegistryIsNotedeveryChangeOfTheRegistryIsNoted
<gtExample>
| anAnnouncer aRegistry aSubscriber anotherSubscriber aSubscription aStrongSubscription |
anAnnouncer := self announcerWithMixedRegistry.
aRegistry := anAnnouncer subscriptions.
aSubscriber := self newSubscriber.
anotherSubscriber := self newSubscriber.
self
assertChange:
[anAnnouncer weak when: JobStart send: #onAnnouncement: to: aSubscriber]
named: 'The first weak subscription'
isNotedBy: aRegistry.
self
assertChange:
[aSubscription := anAnnouncer weak
when: JobEnd
send: #onAnnouncement:
to: aSubscriber]
named: 'A second weak subscription of the same subscriber'
isNotedBy: aRegistry.
self
assertChange: [anAnnouncer removeSubscription: aSubscription]
named: 'Removing a weak subscription that is not the last of its subscriber'
isNotedBy: aRegistry.
self
assertChange:
[aStrongSubscription := anAnnouncer
when: JobStart
send: #onAnnouncement:
to: anotherSubscriber]
named: 'A strong subscription'
isNotedBy: aRegistry.
self
assertChange: [anAnnouncer removeSubscription: aStrongSubscription]
named: 'Removing a strong subscription'
isNotedBy: aRegistry.
anAnnouncer when: JobStart send: #onAnnouncement: to: anotherSubscriber.
self
assertChange: [anAnnouncer unsubscribe: anotherSubscriber]
named: 'Unsubscribing a strong subscriber'
isNotedBy: aRegistry.
aSubscription := anAnnouncer weak
when: JobEnd
send: #onAnnouncement:
to: aSubscriber.
self
assertChange: [aSubscription subscriber: anotherSubscriber]
named: 'Changing the subscriber'
isNotedBy: aRegistry.
self
assertChange: [aSubscription makeStrong]
named: 'Making a weak subscription strong'
isNotedBy: aRegistry.
aStrongSubscription := anAnnouncer
when: JobEnd
send: #onAnnouncement:
to: self newSubscriber.
self
assertChange: [aStrongSubscription makeWeak]
named: 'Making a strong subscription weak'
isNotedBy: aRegistry.
self
assertChange: [(aRegistry ephemeronOf: aSubscriber) mourn]
named: 'Mourning a weak subscriber'
isNotedBy: aRegistry.
self
assertChange: [anAnnouncer unsubscribe: anotherSubscriber]
named: 'Unsubscribing a subscriber'
isNotedBy: aRegistry.
self
assertChange: [aRegistry reset]
named: 'Resetting the registry'
isNotedBy: aRegistry.
anAnnouncer when: JobStart send: #onAnnouncement: to: aSubscriber.
self
assertQuery: [anAnnouncer announce: JobStart new]
named: 'Delivering an announcement'
isNotNotedBy: aRegistry.
self
assertQuery:
[aRegistry subscriptions.
aRegistry numberOfSubscriptions.
aRegistry subscriptionsHandling: JobStart new]
named: 'Querying the subscriptions'
isNotNotedBy: aRegistry.
self assert: aSubscriber announcements size equals: 1.
^anAnnouncerGtMixedSubscriptionRegistryExamples>>#conditionThatChangesTheRegistryIsMatchedAgainconditionThatChangesTheRegistryIsMatchedAgain
<gtExample>
| anAnnouncer aSubscriber anotherSubscriber theEvaluations |
anAnnouncer := self announcerWithMixedRegistry.
aSubscriber := self newSubscriber.
anotherSubscriber := self newSubscriber.
theEvaluations := 0.
anAnnouncer when: JobStart send: #onAnnouncement: to: anotherSubscriber.
anAnnouncer weak
when: (JobStart where:
[:anAnnouncement |
theEvaluations := theEvaluations + 1.
theEvaluations = 1
ifTrue:
[anAnnouncer
when: JobEnd
send: #onAnnouncement:
to: self newSubscriber].
true])
send: #onAnnouncement:
to: aSubscriber.
anAnnouncer announce: JobStart new.
self assert: theEvaluations
equals: (self
evaluationsOfAConditionAnnouncedIn: self announcerWithMixedRegistry) + 1.
self assert: aSubscriber announcements size equals: 1.
self assert: anotherSubscriber announcements size equals: 1.
self assert: anAnnouncer numberOfSubscriptions equals: 3.
^anAnnouncerGtMixedSubscriptionRegistryExamples>>#conditionThatUnsubscribesAnotherSubscriberIsRespectedconditionThatUnsubscribesAnotherSubscriberIsRespected
<gtExample>
| anAnnouncer aSubscriber aLeavingSubscriber |
anAnnouncer := self announcerWithMixedRegistry.
aSubscriber := self newSubscriber.
aLeavingSubscriber := self newSubscriber.
anAnnouncer when: JobStart send: #onAnnouncement: to: aLeavingSubscriber.
anAnnouncer weak
when: (JobStart where:
[:anAnnouncement |
anAnnouncer unsubscribe: aLeavingSubscriber.
true])
send: #onAnnouncement:
to: aSubscriber.
anAnnouncer announce: JobStart new.
self assert: aSubscriber announcements size equals: 1.
self assert: aLeavingSubscriber announcements isEmpty.
self assert: anAnnouncer numberOfSubscriptions equals: 1.
^anAnnouncerGtMixedSubscriptionRegistryExamples>>#whereConditionThatSubscribesDoesNotHideOtherSubscriberswhereConditionThatSubscribesDoesNotHideOtherSubscribers
<gtExample>
| anAnnouncer theSubscribers aLateSubscriber |
anAnnouncer := self announcerWithMixedRegistry.
theSubscribers := (1 to: 20) collect: [:each | self newSubscriber].
theSubscribers
do: [:each | anAnnouncer weak when: JobStart send: #onAnnouncement: to: each].
aLateSubscriber := self newSubscriber.
anAnnouncer weak
when: (JobStart where:
[:anAnnouncement |
1 to: 50
do:
[:each |
anAnnouncer weak
when: JobEnd
send: #onAnnouncement:
to: self newSubscriber].
true])
send: #onAnnouncement:
to: aLateSubscriber.
anAnnouncer announce: JobStart new.
self
assert: (theSubscribers allSatisfy: [:each | each announcements size = 1]).
self assert: aLateSubscriber announcements size equals: 1.
^anAnnouncer
8. The subscription decides its part. #selector
add: aSubscription
^self
protectedChange: [aSubscription addToMixedSubscriptionRegistry: self]
sends #selector
addToMixedSubscriptionRegistry: aRegistry
^aRegistry addStrongSubscription: self
; the default on Object
ProtoObject << #Object
slots: {};
tag: 'Objects';
package: 'Kernel'
files any object in the strong part, so Bloc's handler subscriptions and old-style WeakAnnouncementSubscription
AbstractAnnouncementSubscription << #WeakAnnouncementSubscription
layout: WeakLayout;
slots: { #next };
tag: 'Subscription';
package: 'Announcements-Core'
s keep working (GtMixedSubscriptionRegistryExamples>>#subscriptionOfAnyClassGoesToStrongPart
subscriptionOfAnyClassGoesToStrongPart
<gtExample>
| aRegistry aSubscriptionLikeObject |
aRegistry := self emptyRegistry.
aSubscriptionLikeObject := Object new.
self
assert: (aRegistry add: aSubscriptionLikeObject) == aSubscriptionLikeObject.
self assert: aRegistry allStrongSubscriptions
equals: (Array with: aSubscriptionLikeObject).
self assert: aRegistry numberOfWeakSubscribers equals: 0.
self assert: (aRegistry remove: aSubscriptionLikeObject)
== aSubscriptionLikeObject.
self assert: aRegistry isEmpty.
^aRegistry
). Old-style weak subscriptions are not converted, because their global entry would remain anyway.
9. Builders own the conversions. #selector
weak
"announcer weak subscribe: foo"
"GT patch: my registry chooses the weak builder, see implementors of #weakSubscriptionBuilderFor:"
<gtPharoPatch: #Pharo>
^registry weakSubscriptionBuilderFor: self
, #selector
makeWeak
"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)
and moves between registries ask the builder of the target registry, so Pharo's registries keep their behaviour. A builder hands each new subscription to the builder of the registry its announcer uses at that moment (GtMixedSubscriptionRegistryExamples>>#weakBuilderKeptAcrossASwitchSubscribesInTheCurrentRegistry
weakBuilderKeptAcrossASwitchSubscribesInTheCurrentRegistry
<gtExample>
| anAnnouncer aBuilder aSubscriber aSubscription |
anAnnouncer := self announcerWithMixedRegistry.
aBuilder := anAnnouncer weak.
anAnnouncer useSubscriptionRegistry: SubscriptionRegistry new.
aSubscriber := self newSubscriber.
aSubscription := aBuilder
when: JobStart
send: #onAnnouncement:
to: aSubscriber.
self assert: aSubscription class equals: WeakAnnouncementSubscription.
self
assert: (anAnnouncer subscriptions subscriptions
collect: [:each | each class]) asArray
equals: (Array with: WeakAnnouncementSubscription).
anAnnouncer announce: JobStart new.
self assert: aSubscriber announcements size equals: 1.
aSubscription makeStrong.
self assert: anAnnouncer numberOfSubscriptions equals: 1.
anAnnouncer unsubscribe: aSubscriber.
self assert: anAnnouncer subscriptions isEmpty.
^anAnnouncer
).
10. Identity is kept where Pharo keeps it. #selector
makeStrong
| aSubscriber |
aSubscriber := self subscriber.
aSubscriber
ifNil: [^self error: 'Subscriber is nil, cannot make strong subscription'].
^announcer subscriptions makeStrong: self for: aSubscriber
and moves to another kind of registry #selector
becomeForward: otherObject
"Primitive. All variables in the entire system that used to point
to the receiver now point to the argument.
Fails if either argument is a SmallInteger."
<reflection: 'Chasing and swapping pointers - Bulk pointer swapping'>
{self} elementsForwardIdentityTo: {otherObject}
the old subscription to the new one, as WeakAnnouncementSubscription>>#makeStrong
makeStrong
| sub |
sub := self subscriber.
sub ifNil: [ ^ self error: 'Subscriber is nil, cannot make strong subscription' ].
self unregister.
^ self becomeForward: (AnnouncementSubscription new
announcer: announcer;
action: action asMessageSend;
subscriber: sub;
announcementClass: announcementClass)
does, so references to subscriptions stay valid. #selector
makeWeak
"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 subscription and leaves the old object as it is, as in Pharo. #selector
subscriber: aSubscriber
announcer
ifNil: [self basicSubscriber: aSubscriber]
ifNotNil:
[self class assertSubscriber: aSubscriber canBeWeakFor: action.
announcer subscriptions changeSubscriberOf: self to: aSubscriber]
re-files a weak subscription under the new subscriber, because helpers such as TGtWithWeakAnnouncer>>#when:send:to:for:
when: anAnnouncementClass send: aSelector to: anObject for: aSubscriber
"Declare that when anAnnouncementClass is raised, anObject should receive the message aSelector.
When the message expects one argument (eg #fooAnnouncement:) the announcement is passed as argument.
When the message expects two arguments (eg #fooAnnouncement:announcer:) both the announcement and
the announcer are passed as argument"
^ (self when: anAnnouncementClass send: aSelector to: anObject)
subscriber: aSubscriber
set the subscriber after subscribing.
11. Subscriptions that cannot work weakly are refused. A nil subscriber can never be collected, and a valuable that is its own subscriber would vanish at the next collection; both signal an error, in the builder and in #selector
subscriber: aSubscriber
announcer
ifNil: [self basicSubscriber: aSubscriber]
ifNotNil:
[self class assertSubscriber: aSubscriber canBeWeakFor: action.
announcer subscriptions changeSubscriberOf: self to: aSubscriber]
(GtEphemeronAnnouncementSubscription>>#assertSubscriber:canBeWeakFor:
assertSubscriber: aSubscriber canBeWeakFor: aValuable
aSubscriber
ifNil: [ self
error: 'A weak subscription needs a subscriber that can be garbage collected' ].
aValuable == aSubscriber
ifTrue: [ self
error: 'A valuable that is its own subscriber cannot be subscribed weakly' ]
). There is no weak when:do:; the subscriber of a weak block subscription is given 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)
. A weak subscription whose subscriber is already gone, for example one added again after its subscriber was collected, is not added, because its group could never be mourned (GtMixedSubscriptionRegistryExamples>>#weakSubscriptionWithoutSubscriberIsNotKept
weakSubscriptionWithoutSubscriberIsNotKept
<gtExample>
| anAnnouncer aSubscription |
anAnnouncer := self announcerWithMixedRegistry.
aSubscription := (GtEphemeronAnnouncementSubscription new)
announcer: anAnnouncer;
announcementClass: JobStart;
action: [:anAnnouncement | ];
yourself.
self assert: aSubscription subscriber isNil.
anAnnouncer basicSubscribe: aSubscription.
self assert: anAnnouncer numberOfSubscriptions equals: 0.
self assert: (self hasNoWeakPart: anAnnouncer subscriptions).
^anAnnouncer
).
12. Fuel and copies. Fuel skips the weak part, the lock and the change marker (GtMixedSubscriptionRegistry>>#fuelIgnoredInstanceVariableNames
fuelIgnoredInstanceVariableNames
^#('monitor' 'weakSubscriptions' 'lastChange')
), so a materialized registry has only its strong subscriptions. A shallow #selector
copy
"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
gets its own lock, a copy of the strong set and fresh ephemerons for the same weak subscriptions (GtMixedSubscriptionRegistry>>#postCopy
postCopy
| theWeakGroups |
theWeakGroups := self protected:
[strongSubscriptions := strongSubscriptions copy.
self weakPart subscribersWithSubscriptions].
monitor := Mutex new.
self weakPart: GtNoWeakSubscriptions uniqueInstance.
theWeakGroups do:
[:aGroup |
self installGroupOf: aGroup key
holding: (IdentitySet withAll: aGroup value)]
, GtMixedSubscriptionRegistryExamples>>#copiedRegistryIsIndependent
copiedRegistryIsIndependent
<gtExample>
| anAnnouncer aStrongSubscriber aWeakSubscriber aCopy anotherAnnouncer aLateSubscriber |
anAnnouncer := self newAnnouncer.
aStrongSubscriber := self newSubscriber.
aWeakSubscriber := self newSubscriber.
anAnnouncer when: JobStart send: #onAnnouncement: to: aStrongSubscriber.
anAnnouncer weak when: JobStart send: #onAnnouncement: to: aWeakSubscriber.
aCopy := anAnnouncer subscriptions copy.
anotherAnnouncer := Announcer new useSubscriptionRegistry: aCopy.
self assert: aCopy numberOfSubscriptions equals: 2.
self assert: aCopy numberOfWeakSubscribers equals: 1.
self assert: aCopy weakPart ~~ anAnnouncer subscriptions weakPart.
self assert: (aCopy ephemeronOf: aWeakSubscriber)
~~ (anAnnouncer subscriptions ephemeronOf: aWeakSubscriber).
anotherAnnouncer announce: JobStart new.
self assert: aStrongSubscriber announcements size equals: 1.
self assert: aWeakSubscriber announcements size equals: 1.
anotherAnnouncer unsubscribe: aWeakSubscriber.
self assert: (self hasNoWeakPart: aCopy).
self assert: (anAnnouncer hasSubscriber: aWeakSubscriber).
aLateSubscriber := self newSubscriber.
anAnnouncer weak when: JobStart send: #onAnnouncement: to: aLateSubscriber.
self assert: (anotherAnnouncer hasSubscriber: aLateSubscriber) not.
anotherAnnouncer unsubscribe: aStrongSubscriber.
self assert: (anAnnouncer hasSubscriber: aStrongSubscriber).
self assertWeakPartInvariantOf: aCopy.
self assertWeakPartInvariantOf: anAnnouncer subscriptions.
^aCopy
); the subscription objects themselves are shared with the original.
13. Read-only queries wait for the lock. GtMixedSubscriptionRegistry>>#subscriptions
subscriptions
^self protected:
[Array
streamContents: [:aStream | self subscriptionsDo: [:each | aStream nextPut: each]]]
, GtMixedSubscriptionRegistry>>#allStrongSubscriptions
allStrongSubscriptions
^self protected:
[(strongSubscriptions reject: [:each | each isWeakSubscription]) asArray]
, GtMixedSubscriptionRegistry>>#allWeakSubscriptions
allWeakSubscriptions
^self protected:
[Array streamContents:
[:aStream |
strongSubscriptions
do: [:each | each isWeakSubscription ifTrue: [aStream nextPut: each]].
self weakPart subscriptionsDo: [:each | aStream nextPut: each]]]
, GtMixedSubscriptionRegistry>>#weakSubscribersWithSubscriptions
weakSubscribersWithSubscriptions
^self protected: [self weakPart subscribersWithSubscriptions]
and the views copy the subscriptions under the lock (GtMixedSubscriptionRegistry>>#protected:
protected: aBlock
^monitor critical: aBlock
). SubscriptionRegistry>>#subscriptions
subscriptions
^ subscriptions
answers its live set without the lock, so a reader that interrupts a change sees a half-done set: while a set grows, HashedCollection
Collection << #HashedCollection
slots: { #tally . #array };
package: 'Collections-Unordered'
's #selector
grow
"Grow the elements array and reinsert the old elements"
| oldElements |
oldElements := array.
array := Array new: (HashTableSizes atLeast: oldElements size * 2).
tally := 0.
oldElements
do:
[ :each |
each ifNotNil: [ self noCheckAdd: each ] ]
empties it and adds every element again. In a measurement, a process at priority 30 kept adding 5,000 subscriptions and resetting, and a process at priority 35 read all subscriptions about every millisecond. With a plain registry 496 of 1,879 reads (26 %) missed subscriptions, without any error; with the mixed registry none of 1,756 did. The price is that a query waits while another process holds the lock, for example a process stopped in the debugger inside a #selector
where: instancesFilterBlock
^AnnouncementDeliveryCondition for: self where: instancesFilterBlock
condition; deliveries, subscribing and unsubscribing wait in that case with a plain registry too. Only the size queries, #selector
numberOfSubscriptions
^strongSubscriptions size + self weakPart numberOfSubscriptions
and #selector
isEmpty
^strongSubscriptions isEmpty and: [self weakPart isEmpty]
, do not take the lock, because a slightly stale count does no harm.
Most announcers never get a weak subscriber (11,845 of 12,529 Lepiter announcers in a load of the Glamorous Toolkit Book at the moment when this was added), so the weak part is an object of its own:
GtNoWeakSubscriptionsGtAbstractWeakSubscriptions << #GtNoWeakSubscriptions
slots: {};
sharedVariables: { #UniqueInstance };
tag: 'Mixed-Core';
package: 'GToolkit-PharoBasePatch-Subscriptions' has no state; all registries without weak subscribers share GtNoWeakSubscriptions>>#uniqueInstanceuniqueInstance
^UniqueInstance ifNil: [UniqueInstance := self new], and nothing can change it.GtWeakSubscriptionsGtAbstractWeakSubscriptions << #GtWeakSubscriptions
slots: { #ephemerons };
tag: 'Mixed-Core';
package: 'GToolkit-PharoBasePatch-Subscriptions' holds the dictionary of ephemerons and is never empty.- Every change is made in place and answers the part the registry keeps from then on: adding to the empty part answers a new
GtWeakSubscriptionsGtAbstractWeakSubscriptions << #GtWeakSubscriptions
slots: { #ephemerons };
tag: 'Mixed-Core';
package: 'GToolkit-PharoBasePatch-Subscriptions' (GtNoWeakSubscriptions>>#withEphemeron:withEphemeron: anEphemeron
^GtWeakSubscriptions new withEphemeron: anEphemeron), removing the last subscriber answers the shared empty part again (GtWeakSubscriptions>>#withoutSubscriber:withoutSubscriber: aSubscriber
ephemerons removeKey: aSubscriber ifAbsent: [].
^self releasedWhenEmpty). GtMixedSubscriptionRegistryExamples>>#randomChangesKeepTheWeakPartConsistentrandomChangesKeepTheWeakPartConsistent
<gtExample>
| anAnnouncer aRegistry aRandom theSubscribers theExpected theSubscriptions |
anAnnouncer := self newAnnouncer.
aRegistry := anAnnouncer subscriptions.
aRandom := Random seed: 42.
theSubscribers := (1 to: 6) collect: [:each | self newSubscriber].
theExpected := IdentityDictionary new.
theSubscriptions := OrderedCollection new.
2000 timesRepeat:
[| aSubscriber anOperation |
aSubscriber := theSubscribers atRandom: aRandom.
anOperation := (1 to: 5) atRandom: aRandom.
anOperation = 1
ifTrue:
[theSubscriptions
add: (anAnnouncer weak when: JobStart send: #onAnnouncement: to: aSubscriber).
theExpected at: aSubscriber
put: (theExpected at: aSubscriber ifAbsent: [0]) + 1].
anOperation = 2
ifTrue:
[anAnnouncer unsubscribe: aSubscriber.
theSubscriptions
removeAllSuchThat: [:each | each subscriber == aSubscriber].
theExpected removeKey: aSubscriber ifAbsent: []].
(anOperation = 3 and: [theSubscriptions notEmpty])
ifTrue:
[| aSubscription |
aSubscription := theSubscriptions
removeAt: ((1 to: theSubscriptions size) atRandom: aRandom).
anAnnouncer removeSubscription: aSubscription.
self decrease: aSubscription subscriber in: theExpected].
(anOperation = 4 and: [theSubscriptions notEmpty])
ifTrue:
[| aSubscription |
aSubscription := theSubscriptions
removeAt: ((1 to: theSubscriptions size) atRandom: aRandom).
self decrease: aSubscription subscriber in: theExpected.
aSubscription makeStrong.
anAnnouncer removeSubscription: aSubscription].
(anOperation = 5 and: [theSubscriptions notEmpty])
ifTrue:
[| aSubscription |
aSubscription := theSubscriptions atRandom: aRandom.
self decrease: aSubscription subscriber in: theExpected.
aSubscription subscriber: aSubscriber.
theExpected at: aSubscriber
put: (theExpected at: aSubscriber ifAbsent: [0]) + 1].
self assertWeakPartInvariantOf: aRegistry.
self assert: aRegistry numberOfWeakSubscribers equals: theExpected size.
self assert: aRegistry numberOfSubscriptions equals: theSubscriptions size.
theSubscribers do:
[:each |
self
assert: (aRegistry weakPart subscriptionsOf: each ifAbsent: [#()]) size
equals: (theExpected at: each ifAbsent: [0])]].
theSubscribers do: [:each | anAnnouncer unsubscribe: each].
self assert: (self hasNoWeakPart: aRegistry).
self assert: aRegistry isEmpty.
^anAnnouncer checks this after each of 2,000 random changes.
All changes and the matching of announcements run under the registry's lock; delivery to the matched subscriptions and the size queries (#selector
numberOfSubscriptions
^strongSubscriptions size + self weakPart numberOfSubscriptions
, #selector
isEmpty
^strongSubscriptions isEmpty and: [self weakPart isEmpty]
) do not. The GT views and the announcer graph read the subscriptions under the lock too.
The cleanup of dead subscribers also takes the lock, and it runs in the finalization process. While a lower-priority process holds the lock, for example while matching code such as a #selector
where: instancesFilterBlock
^AnnouncementDeliveryCondition for: self where: instancesFilterBlock
condition runs or halts in a debugger, the finalization process waits, and with it all finalization in the image. Pharo's registries have the same exposure: WeakAnnouncementSubscription>>#finalize
finalize
announcer removeSubscription: self
takes the registry's lock as well.
GtMixedSubscriptionRegistryExamples>>#everyChangeOfTheRegistryWaitsForItsLockeveryChangeOfTheRegistryWaitsForItsLock
<gtExample>
| anAnnouncer aSubscriber anotherSubscriber aSubscription anEphemeron |
anAnnouncer := self newAnnouncer.
aSubscriber := self newSubscriber.
anotherSubscriber := self newSubscriber.
self
assertChange:
[anAnnouncer weak when: JobStart send: #onAnnouncement: to: aSubscriber]
named: 'The first weak subscription'
waitsForTheLockOf: anAnnouncer.
self
assertChange:
[anAnnouncer when: JobStart send: #onAnnouncement: to: anotherSubscriber]
named: 'A strong subscription'
waitsForTheLockOf: anAnnouncer.
self
assertChange: [anAnnouncer unsubscribe: aSubscriber]
named: 'Unsubscribing the last weak subscriber'
waitsForTheLockOf: anAnnouncer.
aSubscription := anAnnouncer weak
when: JobStart
send: #onAnnouncement:
to: aSubscriber.
self
assertChange: [anAnnouncer removeSubscription: aSubscription]
named: 'Removing the last weak subscription'
waitsForTheLockOf: anAnnouncer.
aSubscription := anAnnouncer weak
when: JobStart
send: #onAnnouncement:
to: aSubscriber.
self
assertChange: [aSubscription subscriber: self newSubscriber]
named: 'Changing the subscriber'
waitsForTheLockOf: anAnnouncer.
self
assertChange: [aSubscription makeStrong]
named: 'Making the last weak subscription strong'
waitsForTheLockOf: anAnnouncer.
anAnnouncer weak when: JobStart send: #onAnnouncement: to: aSubscriber.
anEphemeron := anAnnouncer subscriptions ephemeronOf: aSubscriber.
self
assertChange: [anEphemeron mourn]
named: 'Mourning the last weak subscriber'
waitsForTheLockOf: anAnnouncer.
self
assertChange: [anAnnouncer subscriptions reset]
named: 'Resetting the registry'
waitsForTheLockOf: anAnnouncer.
self assert: (self hasNoWeakPart: anAnnouncer subscriptions).
self assert: anAnnouncer numberOfSubscriptions equals: 0.
^anAnnouncer holds the lock and starts each kind of change in a process of higher priority; each must wait. GtMixedSubscriptionRegistryExamples>>#matchingHoldsTheLockAndDeliveryDoesNotmatchingHoldsTheLockAndDeliveryDoesNot
<gtExample>
| anAnnouncer aSubscriber theStatesWhileMatching wasFreeWhileDelivering |
anAnnouncer := self announcerWithMixedRegistry.
aSubscriber := self newSubscriber.
theStatesWhileMatching := OrderedCollection new.
anAnnouncer
when: (JobStart where:
[:anAnnouncement |
theStatesWhileMatching isEmpty
ifTrue:
[theStatesWhileMatching
add: (self forkChangeOf: anAnnouncer) isTerminated not].
true])
do: [:anAnnouncement | wasFreeWhileDelivering := (self forkChangeOf: anAnnouncer) isTerminated]
for: aSubscriber.
anAnnouncer announce: JobStart new.
self assert: theStatesWhileMatching asArray equals: #(true).
self assert: wasFreeWhileDelivering.
self assert: anAnnouncer numberOfSubscriptions equals: 3.
^anAnnouncer does the same from inside a #selectorwhere: instancesFilterBlock
^AnnouncementDeliveryCondition for: self where: instancesFilterBlock condition and from inside a handler.GtMixedSubscriptionRegistryExamples>>#everyChangeOfTheRegistryIsNotedeveryChangeOfTheRegistryIsNoted
<gtExample>
| anAnnouncer aRegistry aSubscriber anotherSubscriber aSubscription aStrongSubscription |
anAnnouncer := self announcerWithMixedRegistry.
aRegistry := anAnnouncer subscriptions.
aSubscriber := self newSubscriber.
anotherSubscriber := self newSubscriber.
self
assertChange:
[anAnnouncer weak when: JobStart send: #onAnnouncement: to: aSubscriber]
named: 'The first weak subscription'
isNotedBy: aRegistry.
self
assertChange:
[aSubscription := anAnnouncer weak
when: JobEnd
send: #onAnnouncement:
to: aSubscriber]
named: 'A second weak subscription of the same subscriber'
isNotedBy: aRegistry.
self
assertChange: [anAnnouncer removeSubscription: aSubscription]
named: 'Removing a weak subscription that is not the last of its subscriber'
isNotedBy: aRegistry.
self
assertChange:
[aStrongSubscription := anAnnouncer
when: JobStart
send: #onAnnouncement:
to: anotherSubscriber]
named: 'A strong subscription'
isNotedBy: aRegistry.
self
assertChange: [anAnnouncer removeSubscription: aStrongSubscription]
named: 'Removing a strong subscription'
isNotedBy: aRegistry.
anAnnouncer when: JobStart send: #onAnnouncement: to: anotherSubscriber.
self
assertChange: [anAnnouncer unsubscribe: anotherSubscriber]
named: 'Unsubscribing a strong subscriber'
isNotedBy: aRegistry.
aSubscription := anAnnouncer weak
when: JobEnd
send: #onAnnouncement:
to: aSubscriber.
self
assertChange: [aSubscription subscriber: anotherSubscriber]
named: 'Changing the subscriber'
isNotedBy: aRegistry.
self
assertChange: [aSubscription makeStrong]
named: 'Making a weak subscription strong'
isNotedBy: aRegistry.
aStrongSubscription := anAnnouncer
when: JobEnd
send: #onAnnouncement:
to: self newSubscriber.
self
assertChange: [aStrongSubscription makeWeak]
named: 'Making a strong subscription weak'
isNotedBy: aRegistry.
self
assertChange: [(aRegistry ephemeronOf: aSubscriber) mourn]
named: 'Mourning a weak subscriber'
isNotedBy: aRegistry.
self
assertChange: [anAnnouncer unsubscribe: anotherSubscriber]
named: 'Unsubscribing a subscriber'
isNotedBy: aRegistry.
self
assertChange: [aRegistry reset]
named: 'Resetting the registry'
isNotedBy: aRegistry.
anAnnouncer when: JobStart send: #onAnnouncement: to: aSubscriber.
self
assertQuery: [anAnnouncer announce: JobStart new]
named: 'Delivering an announcement'
isNotNotedBy: aRegistry.
self
assertQuery:
[aRegistry subscriptions.
aRegistry numberOfSubscriptions.
aRegistry subscriptionsHandling: JobStart new]
named: 'Querying the subscriptions'
isNotNotedBy: aRegistry.
self assert: aSubscriber announcements size equals: 1.
^anAnnouncer goes through every kind of change and checks that each stores a new change marker, and that delivering and querying do not.GtMixedSubscriptionRegistryExamples>>#concurrentWeakSubscriptionsKeepTheRegistryConsistentconcurrentWeakSubscriptionsKeepTheRegistryConsistent
<gtExample>
| theAnnouncers aLock theDeliveries theAnnounced theRounds aDeadline aChurn theWorkers theErrors |
theAnnouncers := Array with: self newAnnouncer with: self newAnnouncer.
aLock := Mutex new.
theDeliveries := 0.
theAnnounced := 0.
theRounds := 0.
theAnnouncers do:
[:anAnnouncer |
anAnnouncer
when: JobStart
do: [:anAnnouncement | aLock critical: [theDeliveries := theDeliveries + 1]]
for: self].
aDeadline := Time millisecondClockValue + 3000.
aChurn :=
[:shouldPause |
| aRound |
aRound := 0.
[Time millisecondClockValue < aDeadline] whileTrue:
[| anAnnouncer aSubscriber theReceived |
aRound := aRound + 1.
anAnnouncer := theAnnouncers at: aRound \\ 2 + 1.
aSubscriber := Object new.
theReceived := 0.
anAnnouncer weak
when: JobStart
do: [:anAnnouncement | theReceived := theReceived + 1]
for: aSubscriber.
anAnnouncer announce: JobStart new.
aLock critical: [theAnnounced := theAnnounced + 1].
self assert: theReceived >= 1.
aRound \\ 3 = 0
ifFalse:
[anAnnouncer unsubscribe: aSubscriber.
self assert: (anAnnouncer hasSubscriber: aSubscriber) not].
self pauseBetweenRounds: shouldPause].
aLock critical: [theRounds := theRounds + aRound]].
theWorkers := OrderedCollection new.
2 timesRepeat: [theWorkers add: 31 -> [aChurn value: false]].
33 to: 35
do: [:aPriority | theWorkers add: aPriority -> [aChurn value: true]].
theWorkers add: 36 -> (self readerOf: theAnnouncers until: aDeadline).
theWorkers add: 36 -> (self copierOf: theAnnouncers until: aDeadline).
theWorkers add: 37 -> (self scavengerUntil: aDeadline).
theErrors := self runWorkers: theWorkers until: aDeadline.
self assert: theErrors isEmpty description: [theErrors printString].
self assert: theRounds > 1000.
self assert: theDeliveries equals: theAnnounced.
self
assert: (self garbageCollectUntil:
[theAnnouncers
allSatisfy: [:each | each subscriptions numberOfWeakSubscribers = 0]]).
theAnnouncers do:
[:each |
self assert: (self hasNoWeakPart: each subscriptions).
self assert: each numberOfSubscriptions equals: 1].
self assert: GtNoWeakSubscriptions uniqueInstance isEmpty.
^theAnnouncers and GtMixedSubscriptionRegistryExamples>>#concurrentMourningKeepsAResubscribingSubscriberconcurrentMourningKeepsAResubscribingSubscriber
<gtExample>
| anAnnouncer aLongLivedSubscriber aDeadline theWorkers theErrors |
anAnnouncer := self newAnnouncer.
aLongLivedSubscriber := self newSubscriber.
aDeadline := Time millisecondClockValue + 3000.
theWorkers := OrderedCollection new.
2 timesRepeat:
[theWorkers
add: 31 ->
[[Time millisecondClockValue < aDeadline] whileTrue:
[anAnnouncer weak
when: JobStart
send: #onAnnouncement:
to: self newSubscriber.
self pauseBetweenRounds: false]]].
theWorkers
add: 33 ->
[[Time millisecondClockValue < aDeadline] whileTrue:
[| aCount |
anAnnouncer weak
when: JobEnd
send: #onAnnouncement:
to: aLongLivedSubscriber.
aCount := aLongLivedSubscriber announcements size.
anAnnouncer announce: JobEnd new.
self assert: aLongLivedSubscriber announcements size equals: aCount + 1.
anAnnouncer unsubscribe: aLongLivedSubscriber.
self assert: (anAnnouncer hasSubscriber: aLongLivedSubscriber) not.
self pauseBetweenRounds: true].
anAnnouncer weak
when: JobEnd
send: #onAnnouncement:
to: aLongLivedSubscriber].
theWorkers
add: 36 -> (self readerOf: (Array with: anAnnouncer) until: aDeadline).
theWorkers add: 37 -> (self scavengerUntil: aDeadline).
theErrors := self runWorkers: theWorkers until: aDeadline.
self assert: theErrors isEmpty description: [theErrors printString].
self assert: (self
garbageCollectUntil: [anAnnouncer subscriptions numberOfWeakSubscribers = 1]).
self assert: (anAnnouncer hasSubscriber: aLongLivedSubscriber).
anAnnouncer announce: JobEnd new.
self assert: aLongLivedSubscriber announcements last class equals: JobEnd.
anAnnouncer unsubscribe: aLongLivedSubscriber.
self assert: anAnnouncer subscriptions isEmpty.
self assert: (self hasNoWeakPart: anAnnouncer subscriptions).
^anAnnouncer run busy and timer-driven workers at different priorities, a reader, a copier and a scavenger for three seconds. They are statistical; longer soak runs with random changes, deliveries and #selectorwhere: instancesFilterBlock
^AnnouncementDeliveryCondition for: self where: instancesFilterBlock conditions that change the registry did hundreds of thousands of rounds without an error, and every announcement reached each subscriber exactly once.
Measured against a plain SubscriptionRegistry
Object << #SubscriptionRegistry
slots: { #subscriptions . #monitor };
tag: 'Subscription';
package: 'Announcements-Core'
. #selector
microsecondsToRun
"Answer the number of milliseconds the receiver takes to return its value."
| initialMicroseconds |
initialMicroseconds := Time microsecondClockValue.
self value.
^ Time microsecondClockValue - initialMicroseconds
has only millisecond resolution in this VM, so blocks were repeated until they ran for tens of milliseconds; delivery times are the minimum of seven runs at priority 60, and allocation is the number of bytes allocated per operation.
|
Operation
|
Plain
|
Mixed
|
|
Weak subscription, 700 subscribers × 7, per subscription
|
2.7 µs
|
1.1 µs
|
|
The same with unsubscribing all, per subscription
|
15 µs
|
1.2 µs
|
|
683 page view models created on one page and unsubscribed, per view model
|
96 µs
|
10 µs
|
|
Strong subscribe and unsubscribe
|
720 ns
|
960 ns
|
|
Announcement handled by 1 strong subscriber
|
1.9 µs, 3.5 KB
|
1.9 µs, 2.8 KB
|
|
Announcement handled by 10 weak subscribers
|
12.7 µs, 11.7 KB
|
13.0 µs, 11.5 KB
|
|
Announcement nobody handles, 100 weak subscribers
|
4.4 µs, 2.7 KB
|
8.0 µs, 2.4 KB
|
|
Announcement handled by 1 of 1,000 weak subscribers
|
46 µs, 3.7 KB
|
86 µs, 3.5 KB
|
|
Weak subscribe, announce, unsubscribe, announce, with 2 weak subscribers
|
8.7 µs, 12.9 KB
|
7.3 µs, 12.0 KB
|
|
Cleanup of 700 dead young subscribers with 7 subscriptions each
|
7 scavenges, 48–71 ms
|
1 scavenge, 6 ms
|
Where the differences come from:
- A plain weak subscription adds an entry to the global
FinalizationRegistryObject << #FinalizationRegistry
slots: { #semaphore . #errorHandler . #ephemeronList };
sharedVariables: { #Default };
tag: 'Registry';
package: 'System-Finalization' (about 360 ns, under a global lock), and a plain #selectorunsubscribe: anObject
"Unsubscribe all subscriptions of anObject from the receiver"
registry removeSubscriber: anObject scans all subscriptions, so many elements coming and going is quadratic. The mixed registry has neither. - The reentrant
MutexObject << #Mutex
slots: { #semaphore . #owner };
tag: 'Processes';
package: 'Kernel' costs 85 ns per locked section against 40 ns for a semaphore, which shows on strong subscriptions. - Delivery walks the weak part under the lock, subscribers and then their sets; for large registries this walk is the expensive part (4.8 µs for 100 subscribers with one subscription each, against 0.8 µs for one flat set), which is why 100 or 1,000 weak subscribers take about twice as long as in a plain registry.
- Delivery allocates only for the subscriptions that handle the announcement, so the mixed registry allocates no more than the plain one. The rest is the lock (about 0.5–0.8 KB per locked section) and the delivery to each subscription.
Memory: an empty registry takes 184 bytes against 128; a registry's own weak part 88 bytes; a weak subscription 272 bytes for a subscriber's first and 144 bytes for each further one, against 192 bytes for a plain one with its global entry.
How these costs could be reduced is listed under "Possible improvements" below.
- Between the collection that fires an ephemeron and its mourn, a dying subscriber can still receive announcements.
- A lower-priority process that holds the registry's lock makes the finalization process wait (see Concurrency).
#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 and #selectorstoreString
"Answer a String representation of the receiver from which the receiver
can be reconstructed."
^ String streamContents: [:s | self storeOn: s] of an announcer, a registry or a subscription recurse forever: #selectorstoreOn: aStream
"Append to the argument aStream a sequence of characters that is an
expression whose evaluation creates an object similar to the receiver."
aStream nextPut: $(.
self class isVariable
ifTrue: [aStream
nextPut: $(;
nextPutAll: self class name;
nextPutAll:' basicNew: ';
store: self basicSize;
nextPutAll: ') ']
ifFalse: [aStream nextPutAll: self class name; nextPutAll:' basicNew'].
1 to: self class instSize do:
[:i |
aStream nextPutAll: ' instVarAt: ';
store: i;
nextPutAll: ' put: ';
store: (self instVarAt: i);
nextPut: $;].
1 to: self basicSize do:
[:i |
aStream nextPutAll: ' basicAt: ';
store: i;
nextPutAll: ' put: ';
store: (self basicAt: i);
nextPut: $;].
aStream nextPutAll: ' yourself)' and #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 do not handle cycles, and a registry with one subscription already has one (subscription → announcer → registry). Use #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 or #selectorveryDeepCopy
"Do a complete tree copy using a dictionary. An object in the tree twice is only copied once. All references to the object in the copy of the tree will point to the new copy."
| copier new |
copier := DeepCopier new initialize: 4096 "self initialDeepCopierSize".
new := self veryDeepCopyWith: copier.
copier references associationsDo: [:assoc |
assoc value veryDeepFixupWith: copier].
copier fixDependents.
^ new.
- Old-style weak subscriptions moved into a mixed registry keep their global entry; install the registry before subscribing.
Announcer>>#useSubscriptionRegistry:useSubscriptionRegistry: aSubscriptionRegistry
| aWeakSubscriptionBuilder |
aWeakSubscriptionBuilder := aSubscriptionRegistry
weakSubscriptionBuilderFor: self.
registry protected:
[registry subscriptions asArray do:
[:each |
aSubscriptionRegistry
add: (each subscriptionToMoveWith: aWeakSubscriptionBuilder)].
registry := aSubscriptionRegistry] locks only the old registry: a subscribe or unsubscribe made by another process during the switch can end up in the old registry. Moving to a plain registry turns weak block subscriptions into strong ones.- A process terminated in the middle of a change can lose that subscriber's group.
- A copy of a registry shares its subscription objects with the original:
#selectormakeStrong
| aSubscriber |
aSubscriber := self subscriber.
aSubscriber
ifNil: [^self error: 'Subscriber is nil, cannot make strong subscription'].
^announcer subscriptions makeStrong: self for: aSubscriber of one of them replaces it in both, and in the copy the strong subscription then sits in a weak group. - A weak subscription removed from its announcer before the announcer moved to a plain registry cannot be made strong or given another subscriber any more: the plain registry does not understand
#selectormakeStrong: anEphemeronSubscription for: aSubscriber
^self protectedChange:
[| isRegistered aStrongSubscription |
isRegistered := (self removeWeakSubscription: anEphemeronSubscription)
notNil.
aStrongSubscription := (AnnouncementSubscription new)
announcer: anEphemeronSubscription announcer;
announcementClass: anEphemeronSubscription announcementClass;
action: anEphemeronSubscription action asStrongSubscriptionAction;
subscriber: aSubscriber;
yourself.
anEphemeronSubscription becomeForward: aStrongSubscription.
isRegistered ifTrue: [self addStrongSubscription: aStrongSubscription].
aStrongSubscription] and #selectorchangeSubscriberOf: aSubscription to: aSubscriber
self protectedChange:
[| isRegistered |
isRegistered := (self removeWeakSubscription: aSubscription) notNil.
aSubscription basicSubscriber: aSubscriber.
isRegistered ifTrue: [self addWeakSubscription: aSubscription]].
None of these is implemented. The numbers come from measurements and simulations, not from implementations.
- Store small groups without a set. Of 19,744 weak subscriber/announcer pairs in a freshly started GT image, 59 % had one weak subscription and 37 % two (each Lepiter snippet subscribes twice to its coder). Holding the subscription itself as the ephemeron's value, or an immutable
ArrayArrayedCollection << #Array
layout: VariableLayout;
slots: {};
tag: 'Base';
package: 'Collections-Sequenceable' for two or more, instead of a set of its own makes walking the weak part about four times cheaper (1.2 µs instead of 4.8 µs for 100 subscribers) and saves about 48–72 bytes per subscriber.
- Index subscriptions by announcement class. Delivery would look up the subscriptions of the announcement's class and its superclasses instead of matching every subscription: in a simulation 0.26 µs instead of 7.7 µs for 100 weak subscribers that nobody listens to, and 1.3 µs instead of 79 µs for 1,000. Subscriptions to announcement sets,
#selectorwhere: instancesFilterBlock
^AnnouncementDeliveryCondition for: self where: instancesFilterBlock conditions or symbols would need a part that is matched as today, changing a subscription's #selectorannouncementClass: anObject
announcementClass := anObject would make the index stale, and every add, remove and mourn would have to keep it up to date. It only pays off for large registries, which are rare: an image with about 434,000 announcers had 29 with 101–1,000 subscriptions and 3 with more.
- A cached snapshot is not worth it. Keeping a
WeakArrayArray << #WeakArray
layout: WeakLayout;
slots: {};
tag: 'Base';
package: 'Collections-Weak' of all subscriptions until the next change (it must be weak, or a weak subscription whose block refers to its subscriber keeps the subscriber alive) would make delivery faster when subscriptions rarely change. But every change makes the next announcement rebuild it, so where subscriptions come and go between announcements it allocates more than matching under the lock (46 KB instead of 12 KB per subscribe, announce, unsubscribe, announce cycle with 2,000 weak subscribers, in a simulation), and every change would have to invalidate it.
- Share an empty strong part as the weak part is shared (
GtNoWeakSubscriptionsGtAbstractWeakSubscriptions << #GtNoWeakSubscriptions
slots: {};
sharedVariables: { #UniqueInstance };
tag: 'Mixed-Core';
package: 'GToolkit-PharoBasePatch-Subscriptions'): an empty registry would take 112 bytes instead of 184, less than the 128 of a plain registry. Most Lepiter snippet announcers have no subscriptions at all.
- A cheaper lock. The reentrant
MutexObject << #Mutex
slots: { #semaphore . #owner };
tag: 'Processes';
package: 'Kernel' costs 85 ns and 776 bytes of short-lived garbage per locked section, a semaphore 40 ns and 544 bytes; every announcement takes the lock once. A non-reentrant lock needs callers such as BlHandlerAnnouncerRegistryBlHandlerRegistry << #BlHandlerAnnouncerRegistry
slots: { #announcer };
tag: 'Events-Dispatcher';
package: 'Bloc' to stop sending #selectorsubscriptions
^self protected:
[Array
streamContents: [:aStream | self subscriptionsDo: [:each | aStream nextPut: each]]] inside #selectorprotected: aBlock
^monitor critical: aBlock.
- No lost changes during a switch.
#selectorbasicSubscribe: subscription
^ registry add: subscription, #selectorremoveSubscription: subscription
"Remove the given subscription from the receiver"
^ registry remove: subscription and #selectorunsubscribe: anObject
"Unsubscribe all subscriptions of anObject from the receiver"
registry removeSubscriber: anObject could check after the operation that the announcer's registry is still the same one and repeat the operation on the new one; repeating is harmless, because adding a subscription twice to the same registry or removing it twice changes nothing. A #selectorbecomeForward: otherObject
"Primitive. All variables in the entire system that used to point
to the receiver now point to the argument.
Fails if either argument is a SmallInteger."
<reflection: 'Chasing and swapping pointers - Bulk pointer swapping'>
{self} elementsForwardIdentityTo: {otherObject} of the old registry is not an option: a process waiting inside the old registry's method would continue that method on an object of another class.
- Convert old-style weak subscriptions when moving into a mixed registry. Their global entries would have to be removed exactly. Looking them up by key is a linear scan that can find the entry of another subscription, so a conversion should first index all global entries by their value once, then remove each with
FinalizationRegistryObject << #FinalizationRegistry
slots: { #semaphore . #errorHandler . #ephemeronList };
sharedVariables: { #Default };
tag: 'Registry';
package: 'System-Finalization''s #selectorremoveEphemeron: anEphemeron
<gtPharoPatch: #Pharo12>
self protected: [
anEphemeron link ifNotNil: [ :aLink | ephemeronList removeLink: aLink ].
anEphemeron link: nil ].
- Coder announcers. In an image with many large Lepiter databases there were about 30,000
GtCoderAnnouncerAnnouncer << #GtCoderAnnouncer
slots: { #suppressedAnnouncements . #monitor };
tag: 'Coders';
package: 'GToolkit-Coder's with no strong subscriptions and about 70,000 weak ones, most of them from code snippets, each with a global entry. With the mixed registry in GtCoderModel>>#initializeinitialize
super initialize.
id := UniqueIdGenerator generateUniqueId.
monitor := Mutex new.
announcer := GtCoderAnnouncer new those entries would go away; a doit that switched one coder delivered and collected as before. An alternative for the snippets is to let the coder call its snippet directly instead of announcing to it.
- Text announcers.
BlTextElement>>#text:text: aBlText
"Change a text I represent.
Note, that aTextModel should be an instance of BrText.
aTextModel must not be nil"
self
assert: [ aBlText isNotNil ]
description: [ 'A text must not be nil' ].
self
assert: [ aBlText isKindOf: BlText ]
description: [ 'A text must be an instance of Text' ].
text = aBlText
ifTrue: [ ^ self ].
text ifNotNil: [ :anOldText | self unsubscribeFromText: anOldText ].
text := aBlText.
defaultFontSize ifNotNil: [ :aDefaultFontSize | text defaultFontSize: aDefaultFontSize ].
self textChanged.
self subscribeToText: aBlText unsubscribes from the old text and subscribes weakly to the new one, so a reused list label that showed 200 texts leaves 200 stale global entries with a plain registry and none with the mixed one.