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

Implements get_or_insert for write once workloads. #293

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 67 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ use once_cell::sync::OnceCell;
pub use read_only::ReadOnlyView;
pub use set::DashSet;
use std::collections::hash_map::RandomState;
use std::ptr;
pub use t::Map;
use try_result::TryResult;

Expand Down Expand Up @@ -573,6 +574,25 @@ impl<'a, K: 'a + Eq + Hash, V: 'a, S: BuildHasher + Clone> DashMap<K, V, S> {
self._get(key)
}

/// Get an immutable reference to an entry in the map, inserting the value if it doesn't exist.
///
/// **Locking behaviour:** May deadlock if called when holding a mutable reference into the map.
///
/// # Examples
///
/// ```
/// use dashmap::DashMap;
///
/// let youtubers = DashMap::new();
/// youtubers.get_or_insert("Bosnian Bill", |_| 457000);
/// assert_eq!(*youtubers.get("Bosnian Bill").unwrap(), 457000);
/// youtubers.get_or_insert("Bosnian Bill", |_| 458000);
/// assert_eq!(*youtubers.get("Bosnian Bill").unwrap(), 457000);
/// ```
pub fn get_or_insert(&'a self, key: K, value: impl FnOnce(&K) -> V) -> Ref<'a, K, V, S> {
self._get_or_insert(key, value)
}

/// Get a mutable reference to an entry in the map
///
/// **Locking behaviour:** May deadlock if called when holding any sort of reference into the map.
Expand Down Expand Up @@ -1025,6 +1045,37 @@ impl<'a, K: 'a + Eq + Hash, V: 'a, S: 'a + BuildHasher + Clone> Map<'a, K, V, S>
}
}

fn _get_or_insert(&'a self, key: K, value: impl FnOnce(&K) -> V) -> Ref<'a, K, V, S> {
let hash = self.hash_usize(&key);

let idx = self.determine_shard(hash);

let shard = unsafe { self._yield_read_shard(idx) };

if let Some((kptr, vptr)) = shard.get_key_value(&key) {
unsafe {
let kptr: *const K = kptr;
let vptr: *const V = vptr.get();
Ref::new(shard, kptr, vptr)
}
} else {
drop(shard);

unsafe {
let c: K = ptr::read(&key);
let mut shard = self._yield_write_shard(idx);

shard.insert(key, SharedValue::new(value(&c)));
Copy link

@ryoqun ryoqun Apr 2, 2024

Choose a reason for hiding this comment

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

i think there could be a race here? when multiple threads are racing with get_or_insert() for the same missing key, all threads could reach here, resulting replacing writes from other threads? That's because it's not atomic to drop the read shard above and yield write shard here?


let (k, v) = shard.get_key_value(&c).unwrap();

let k = util::change_lifetime_const(k);
let v: *const V = v.get();

Ref::new(RwLockWriteGuard::downgrade(shard), k, v)
}
}
}
fn _get_mut<Q>(&'a self, key: &Q) -> Option<RefMut<'a, K, V, S>>
where
K: Borrow<Q>,
Expand Down Expand Up @@ -1441,6 +1492,22 @@ mod tests {
}
}

#[test]
fn test_try_get_or_insert() {
let map = DashMap::new();
map.get_or_insert("Johnny", |_| 21);

assert_eq!(*map.try_get("Johnny").unwrap(), 21);

map.get_or_insert("Johnny", |_| 22);

assert_eq!(*map.try_get("Johnny").unwrap(), 21);

let _result1_locking = map.get_mut("Johnny");

let result2 = map.try_get("Johnny");
assert!(result2.is_locked());
}
#[test]
fn test_try_reserve() {
let mut map: DashMap<i32, i32> = DashMap::new();
Expand Down
2 changes: 2 additions & 0 deletions src/t.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,8 @@ pub trait Map<'a, K: 'a + Eq + Hash, V: 'a, S: 'a + Clone + BuildHasher> {
K: Borrow<Q>,
Q: Hash + Eq + ?Sized;

fn _get_or_insert(&'a self, key: K, value: impl FnOnce(&K) -> V) -> Ref<'a, K, V, S>;

fn _get_mut<Q>(&'a self, key: &Q) -> Option<RefMut<'a, K, V, S>>
where
K: Borrow<Q>,
Expand Down
Loading