Singleton: Difference between revisions

Content added Content deleted
Line 1,157: Line 1,157:
In Oforth, singleton is an anti-pattern because it needs synchronisation in order to be safe between tasks.
In Oforth, singleton is an anti-pattern because it needs synchronisation in order to be safe between tasks.


If the objective is to keep and update a value in a safe way, a channel can be used.
If the goal is to keep and update a value in a safe way, a channel can be used.


For instance, this Sequence class creates instances that increment an integer and send it. If a task tries to get the next value before it is incremented, it will wait until the channel is no more empty and holds the new value. This won't work if the value is a mutable value (you will get an exception if you try to send a mutable object into channel). A mutable object can't be shared between tasks. Here we send a new integer each time.
For instance, this Sequence class creates instances that increment an integer and send it. If a task tries to get the next value before it is incremented, it will wait until the channel is no more empty and holds the new value. This won't work if the value is a mutable value (you will get an exception if you try to send a mutable object into channel). A mutable object can't be shared between tasks. Here we send a new integer each time.