Skip to content

AtomicBoolean: add compare_and_set API #540

Open
@vemv

Description

@vemv

Compare-and-set is a useful functionality (that's why it exists in the Java API). It can save one from race conditions, as explained below.

Use case

  • Assume an atomicboolean called LOCKED, set to false.
  • Multiple concurrent threads run the following code:
if !LOCKED.value
  LOCKED.value = true
  # do something ....
  LOCKED.value = false
end

In this scenario, concurrent threads can read a false in if !LOCKED.value, and enter the if block. That defeats the purpose of an atomicboolean-backed lock.

If there was a CAS API, the fixed code would look like this:

if LOCKED.compare_and_set(false, true)

Furthermore

Ruby has no "tryLock" either. So it's not immediately obvious how to create non-blocking synchronized code. Boolean CAS would offer a nice alternative which Java programmers (and others) already are familiar with.

What do you think?

Cheers - Victor

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementAdding features, adding tests, improving documentation.looking-for-contributorWe are looking for a contributor to help with this issue.medium-priorityShould be done soon.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions