Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimize MemoryDB getOrCreateBlockStore with atomic operation 'computeIfAbsent' #1695

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

mpalriwal-Netflix
Copy link

The separate get and computeIfAbsent calls can introduce race conditions in a multithreaded environment. If multiple threads check for the presence of the blkStore at the same time, they might all find it null and proceed to create new instances, leading to inconsistencies.

CHMap computeIfAbsent is atomic, ensuring that only one thread creates the blkStore if it is absent. This makes the operation thread-safe without additional synchronization.

// Create a new block store and update the index
blkStore = data.computeIfAbsent(id, _ => new MemoryBlockStore(step, blockSize, numBlocks))
data.computeIfAbsent(id, _ => {
val blkStore = new MemoryBlockStore(step, blockSize, numBlocks)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updates are single threaded so there shouldn't be a race for updating the entry. Would need to verify this doesn't result in a lambda allocation per call, will check when I get some time.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If its single threaded we can simply avoid double checking and remove computeIfAbsent completely

private def getOrCreateBlockStore(id: ItemId, tags: Map[String, String]): BlockStore = {
  var blkStore = data.get(id)
  if (blkStore == null) {
    blkStore = new MemoryBlockStore(step, blockSize, numBlocks)
    data.put(id, blkStore)
    index.update(BlockStoreItem.create(id, tags, blkStore))
  }
  blkStore
}

@brharrington brharrington added this to the 1.8.0 milestone Sep 26, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants