You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
db.update(|d|*d=json!({"message":"Hello from async save!"}))?;
174
164
175
-
db.update(|d|*d=json!({"message":"Hello from async save!"}))?;
165
+
println!("Triggering async save...");
166
+
db.save_async()?; // Returns immediately
176
167
177
-
println!("Triggering async save...");
178
-
db.save_async()?; // Returns immediately
168
+
println!("Main thread doing other work...");
169
+
thread::sleep(Duration::from_millis(100));
179
170
180
-
println!("Main thread doing other work...");
181
-
// In a real app, the main thread continues here.
182
-
// We sleep just to allow the save to likely complete for the example.
183
-
thread::sleep(Duration::from_millis(100));
171
+
println!("Checking file...");
172
+
letcontent=std::fs::read_to_string(db_path)?;
173
+
println!("File content:\n{}", content);
174
+
assert!(content.contains("\"message\":"));// Check for pretty printing
184
175
185
-
println!("Checking file...");
186
-
letcontent=std::fs::read_to_string(db_path)?;
187
-
println!("File content:\n{}", content);
188
-
assert!(content.contains("\"message\":")); // Check for pretty printing
176
+
std::fs::remove_file(db_path).ok();
189
177
190
-
std::fs::remove_file(db_path).ok();
191
-
# Ok(())
192
-
# }
193
-
# modjsonmutexdb { pubusecrate::{JsonMutexDB, DbError}; } // Shim for example
194
-
# usejsonmutexdb::{JsonMutexDB, DbError}; // Shim for example
178
+
Ok(())
179
+
}
195
180
```
196
181
197
182
## Performance Notes ⚡️
198
183
199
184
* Atomic Sync Saves (`save_sync`): No longer deep-clones the JSON data to avoid extra allocations and copying. Instead, holds a read lock during serialization into a thread-local buffer, reducing memory operations at the cost of blocking concurrent updates during the save.
200
-
* Asynchronous Saves (`save_async`): Clones the entire JSON data for background saving to avoid blocking the main thread during the save operation.
185
+
* Asynchronous Saves (`save_async`): No longer deep-clones the JSON data; holds a read lock during serialization into a thread-local buffer in the background thread, reducing memory operations at the cost of blocking concurrent updates until the save completes.
201
186
* Serialization Buffer: The thread-local buffer is pre-allocated based on initial file size to minimize reallocations.
202
187
* I/O: Saves serialize into a thread-local in-memory buffer and issue a single `write_all` + `flush`, drastically reducing the number of write syscalls. Atomic saves still involve writing to a temporary file and renaming.
203
188
* Async Updates: Updates are non-blocking and queued to a background thread. Multiple rapid updates are coalesced into a single disk write, reducing redundant I/O.
0 commit comments