Track Bounded Evictions With container/list
Combine container/list with an index map to promote accessed entries in O(1) time and record evicted keys when inserting past max capacity.
Survive flaky dependencies: dedupe in-flight work, cancel cleanly, and classify what is worth retrying.
734 published examples — showing latest 48
Combine container/list with an index map to promote accessed entries in O(1) time and record evicted keys when inserting past max capacity.
Attach a cancel hook with context.AfterFunc to close an in-flight resource, and unregister the hook via defer stop() when work finishes early.
Build a nested multi-error tree with errors.Join and fmt.Errorf %w, then traverse both Unwrap() []error and Unwrap() error branches recursively.
Order pending retry jobs by earliest deadline and ID tie-breaker using container/heap, popping due work and pushing backed-off attempts.
Copy bytes from a producer goroutine through io.Pipe and propagate failures explicitly via CloseWithError instead of a silent EOF.
Combine a runtime slice of channels into []reflect.SelectCase using reflect.Select, handling default fallback and pruning closed channels safely.
Maintain a fixed-capacity latency window in container/ring, overwriting the oldest slot and ignoring unfilled nil nodes during summary scans.
Coordinate concurrent goroutines with sync.Map.LoadOrStore so only one winner initializes each shared key while peers receive the existing value.
Stop an active or expired time.Timer and drain its channel with a non-blocking select before Reset so stale ticks never fire early.
CompletableFuture.anyOf settles on the first completed stage even if it failed, so wrap noisy mirrors with exceptionally before racing them.
Keep ConcurrentHashMap clean when computeIfAbsent returns null or throws: failed loads leave the key absent so a subsequent retry can succeed.
Deduplicate event handlers with CopyOnWriteArraySet and iterate over a point-in-time snapshot so listeners can unsubscribe mid-dispatch safely.
Coordinate concurrent workers with two CountDownLatch gates: a one-count start gun to launch together and a worker-count latch to await finish.
Use the arrival index returned by CyclicBarrier.await to elect one thread per round without extra locks, then reuse the barrier across phases.
Swap reusable list buffers between producer and consumer with Exchanger, and enforce a bounded wait using timed exchange with TimeoutException.
Override Phaser.onAdvance to summarize each completed phase and return true once the final stage finishes, cleanly marking the phaser terminated.
Acquire multiple Semaphore permits at once for heavy tasks, then call drainPermits to seize remaining capacity before releasing them back.
Register async teardown hooks with AsyncDisposableStack use, adopt, and defer, then transfer ownership with move so cleanup runs reliably in reverse.
Subscribe to node:diagnostics_channel tracingChannel lifecycle events around traceSync and tracePromise without coupling hooks to business logic.
Inspect registered callbacks across both Node EventEmitter and AbortSignal EventTarget objects via events.getEventListeners to verify cleanup.
Catch SuppressedError thrown when both an operation and DisposableStack cleanup fail, then inspect error and suppressed links across the full chain.
Use contextlib.nullcontext as a drop-in no-op context manager when a lock, trace, or writer is optional, avoiding duplicated with-block bodies.
Use BTreeMap::first_entry and last_entry to read, mutate, and evict minimum or maximum key buckets in place through OccupiedEntry without re-lookup.
Combine Cell for Copy counters and RefCell for heap buffers so an immutable &self handle can record metrics and events safely at runtime.
Build a RAII scope guard implementing Drop so uncommitted mutations roll back to a checkpoint on early return unless commit is called.
Recover an Arc<Mutex<T>> lock after a worker thread panics using PoisonError::into_inner, then inspect and repair the partial mutation safely.
Wrap counter and budget fields in std::num::Saturating<T> so +, -, *, and += operators clamp cleanly at type bounds without panicking on overflow.
Transfer ownership of a pending queue via Option::take so repeated flushes are no-ops, then pair drained jobs with worker slots using Iterator::zip.
Clean temporary tables, prepared statements, GUCs, and LISTEN channels with DISCARD ALL before returning pooled connections, outside transactions.
Index only failed jobs with CREATE INDEX ... INCLUDE (...) WHERE so error queue queries run index-only scans while healthy rows stay unindexed.
Show why TypeScript resets narrowing on mutable let bindings inside callbacks, and preserve narrowed types by capturing a const snapshot before deferral.
Combine ordered predicates and type guards inside switch (true) to narrow union events and numeric thresholds without deeply nested if-else chains.
Define package-level errors with errors.New, wrap them through layers, and match the sentinel with errors.Is even when the message has changed.
Show that a panic in one goroutine crashes the whole process, and demonstrate the recover-in-worker pattern that contains it.
Race a slow channel receive against a closed done channel so a cancelled waiter exits immediately instead of blocking forever.
Adding an abort listener after the signal already aborted does not throw and does not fire, so cleanup paths must check signal.aborted before subscribing.
Convert an owned Vec into a static-lifetime slice with Vec::leak, trading the deallocation path for data that lives for the whole program.
queueMicrotask callbacks run after the current task in FIFO order interleaved with promise reactions, so all microtasks drain before any timer fires.
Classify context errors with errors.Is: canceled callers, exceeded deadlines, and healthy contexts each report a distinct outcome.
Turn panics into errors by recovering in a deferred function and switching on the panic value: runtime errors implement error, strings stay strings.
Files.list and Files.walk return DirectoryStream-backed streams that terminal ops never close; wrap every walk in try-with-resources or leak handles.
A blocked channel read on a socket responds to interrupt by closing the channel and raising ClosedByInterruptException instead of returning.
shutdownOutput closes only the write direction: the peer sees a clean EOF, finishes its read loop, and can still send its final reply back.
Show that an instance monitor never blocks the class monitor: code holding one object lock runs while the static critical section proceeds concurrently.
Bound virtual thread concurrency with a Semaphore: tasks fan out cheaply while the permit count caps simultaneous in-flight downstream calls.
Each request records a sequence ticket and responses check it before applying, so type-ahead searches drop stale results instead of flashing old data.
Long-running loops cannot be interrupted from outside, so cooperative work calls signal.throwIfAborted() between steps to stop cleanly on abort.
Split CPU-heavy work into chunks and await a setTimeout macrotask between them so timers and I/O run; await Promise.resolve() only drains microtasks.
Showing 48 of 734 verified Resilience examples. Filter the full catalog by language, framework, or keyword in Explore.
Browse & filter all 734 examples in Explore →