Ensure thread-safe access to shared state by using appropriate synchronization mechanisms and atomic operations. Avoid race conditions by: 1. Using atomic operations or locks when modifying shared state
Ensure thread-safe access to shared state by using appropriate synchronization mechanisms and atomic operations. Avoid race conditions by:
Example of unsafe code:
class StateManager {
private cachedInfo: ModelInfo | null = null;
async getInfo() {
if (!this.cachedInfo) { // Race condition: multiple threads might pass this check
this.cachedInfo = await fetchModelInfo(); // Multiple simultaneous fetches possible
}
return this.cachedInfo;
}
}
Safe version:
class StateManager {
private cachedInfo: ModelInfo | null = null;
private fetchPromise: Promise<ModelInfo> | null = null;
async getInfo() {
if (this.fetchPromise) {
return this.fetchPromise; // Reuse in-flight request
}
if (!this.cachedInfo) {
this.fetchPromise = fetchModelInfo();
try {
this.cachedInfo = await this.fetchPromise;
} finally {
this.fetchPromise = null; // Clear promise reference
}
}
return this.cachedInfo;
}
}
This pattern prevents multiple simultaneous fetches, handles errors gracefully, and maintains state consistency across async operations.
Enter the URL of a public GitHub repository