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

Make Resettable lazy again #7222

Merged
Merged
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
38 changes: 23 additions & 15 deletions src/rust/engine/resettable/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,19 +65,33 @@ where
T: Send + Sync,
{
pub fn new<F: Fn() -> T + 'static>(make: F) -> Resettable<T> {
let val = (make)();
Resettable {
val: Arc::new(RwLock::new(Some(val))),
val: Arc::new(RwLock::new(None)),
make: Arc::new(make),
}
}

///
/// Execute f with the value in the Resettable.
/// May lazily initialize the value in the Resettable.
///
/// TODO Explore the use of parking_lot::RWLock::upgradable_read
/// to avoid reacquiring the lock for initialization.
/// This can be used if we are sure that a deadlock won't happen
/// when two readers are trying to upgrade at the same time.
///
pub fn with<O, F: FnOnce(&T) -> O>(&self, f: F) -> O {
let val_opt = self.val.read();
let val = val_opt
.as_ref()
.unwrap_or_else(|| panic!("A Resettable value cannot be used while it is shutdown."));
f(val)
{
let val_opt = self.val.read();
if let Some(val) = val_opt.as_ref() {
return f(val);
}
}
let mut val_write_opt = self.val.write();
if val_write_opt.as_ref().is_none() {
*val_write_opt = Some((self.make)())
}
f(val_write_opt.as_ref().unwrap())
}

///
Expand All @@ -89,9 +103,7 @@ where
{
let mut val = self.val.write();
*val = None;
let t = f();
*val = Some((self.make)());
t
f()
}
}

Expand All @@ -106,10 +118,6 @@ where
/// be sure that dropping it will actually deallocate the resource.
///
pub fn get(&self) -> T {
let val_opt = self.val.read();
let val = val_opt
.as_ref()
.unwrap_or_else(|| panic!("A Resettable value cannot be used while it is shutdown."));
val.clone()
self.with(T::clone)
}
}