Project

General

Profile

Actions

Feature #18127

closed

Ractor-local version of Singleton

Added by rm155 (Rohit Menon) about 3 years ago. Updated about 2 months ago.

Status:
Closed
Assignee:
-
Target version:
-
[ruby-core:105056]

Description

Background
When the Singleton module (from the Singleton library) is included in a class, that class will have only one instance. Since the instance can only be in one Ractor at once, Singleton is not Ractor-compatible. For example, the following code would fail upon trying to access Example.instance in the Ractor:

class Example
  def initialize
    @value = 1
  end
end
Example.include Singleton

Ractor.new do
  Example.instance
end.take
#=> can not access instance variables of classes/modules from non-main Ractors (Ractor::IsolationError)

In some cases, this may be the desired behavior, as it may be important that the class truly have only one instance. However, in many other cases, it would be more convenient for the class to have one instance per Ractor.

Proposal
The proposal is to create a RactorLocalSingleton module that can be included instead of Singleton to make the instance Ractor-local.
Here is how RactorLocalSingleton might be used in the situation above:

class Example
  def initialize
    @value = 1
  end
end
Example.include RactorLocalSingleton

Ractor.new do
  Example.instance
end.take

Discussion
The advantage of creating RactorLocalSingleton is that classes could have Singleton-like behavior while being usable in Ractors. Since some libraries, such as Prime, currently rely on the Singleton module, this would enable those libraries to have more flexibility with Ractors.
The disadvantage of creating this module is that it supports the continued use of the Singleton design pattern, which is sometimes considered harmful. An alternative to RactorLocalSingleton might be to simply use Thread-local variables as Singleton instances. Here is how Thread-local variables might be used in the given situation:

class Example
  def initialize
    @value = 1
  end
end

Ractor.new do
  Thread.current[:Example] = Example.new
  Thread.current[:Example]
end.take

Summary
Classes that include Singleton are currently incompatible with Ractors. By instead including a new module RactorLocalSingleton, classes can have Singleton-like properties while being used in Ractors. However, this may perpetuate the use of the Singleton design pattern, and using Thread-local variables may be a preferable solution.

Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0Like0Like0