Skip to content

should single_thread_executor be lazily initialized in SyncToAsync? #498

Closed
@allrob23

Description

@allrob23

Context

In SyncToAsync, single_thread_executor is currently initialized as a class attribute at line L369:

# Line 369
single_thread_executor = ThreadPoolExecutor(max_workers=1)

However, it seems that this executor is only used in a very specific case at line 444:

# Line 444
else:
    executor = self.single_thread_executor
    self.deadlock_context.set(True)

Given that this executor is not always needed, would it make sense to initialize it only when required inside the else block?

Potential Benefits

  • Avoids unnecessary resource allocation – If single_thread_executor is not needed, we don't create it at all.
  • Reduces memory footprint – While a single-thread executor is not extremely expensive, avoiding its allocation can contribute to more efficient resource usage.
  • Follows lazy initialization best practices – We would create resources only when they are actually required.

A possible alternative could be:

else:
    executor = ThreadPoolExecutor(max_workers=1)  # Create only when needed
    self.deadlock_context.set(True)

I’d love to hear your thoughts on this! If this idea makes sense, I'd be happy to submit a PR.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions