concurrency

ruby
module ConnectionHealth
  extend ActiveSupport::Concern

  def with_fresh_connection
    conn = ActiveRecord::Base.connection
    conn.verify! # pings and reconnects if the socket is dead

Keep DB Connections Healthy in Long Jobs

rails activerecord background-jobs
by codesnips 3 tabs
java
public final class Debouncer implements AutoCloseable {

    private final ScheduledExecutorService scheduler;
    private final long delayMillis;
    private final AtomicReference<ScheduledFuture<?>> pending = new AtomicReference<>();

Debouncing Rapid Method Calls in Java with a Scheduler and Cancellable Futures

java concurrency debounce
by codesnips 3 tabs
rust
use std::sync::{Arc, Mutex};
use std::thread;

fn main() {
    let counter = Arc::new(Mutex::new(0));
    let mut handles = vec![];

Arc and Mutex for safe shared mutable state across threads

rust concurrency threading
by Marcus Chen 1 tab
ruby
class Current < ActiveSupport::CurrentAttributes
  attribute :tenant, :request_id

  def tenant=(tenant)
    super
    Rails.logger.tagged("tenant=#{tenant&.id}") if tenant

Tenant Isolation in Rails with CurrentAttributes and an around_action

rails multi-tenancy current-attributes
by codesnips 4 tabs
java
import com.github.benmanes.caffeine.cache.CacheLoader;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

Time-Based Caffeine Cache for Expensive Currency Rate Lookups in Spring

caffeine caching spring
by codesnips 3 tabs
ruby
module BoundedFanOut
  Result = Struct.new(:value, :error) do
    def ok?
      error.nil?
    end
  end

Parallelize Independent External Calls (in a bounded way)

concurrency threads http
by codesnips 3 tabs
python
import errno
import fcntl
import os
import time

File-Based Locking to Prevent Concurrent Cron Job Runs in Python

locking concurrency fcntl
by codesnips 3 tabs
python
import functools
import threading


def debounce(wait):
    def decorator(func):

Debounce Repeated Function Calls With a Thread-Safe Python Decorator

python decorators debounce
by codesnips 2 tabs
rust
use std::collections::HashMap;
use std::sync::{Arc, Mutex, PoisonError};

#[derive(Default)]
struct Metrics {
    per_endpoint: HashMap<String, u64>,

Thread-Safe Request Metrics with Arc, Mutex, and a Poison-Recovery Guard

rust concurrency arc
by codesnips 3 tabs
typescript
import { Pool } from "pg";

async function keyFor(pool: Pool, name: string): Promise<string> {
  const { rows } = await pool.query<{ key: string }>(
    "SELECT hashtextextended($1, 0) AS key",
    [name]

Postgres advisory lock for one-at-a-time work

postgres concurrency reliability
by codesnips 3 tabs
rust
use tokio::time::{sleep, Duration};

#[tokio::main]
async fn main() {
    let handle = tokio::spawn(async {
        sleep(Duration::from_millis(100)).await;

tokio::spawn for concurrent task execution

rust async tokio
by Marcus Chen 1 tab
ruby
class Order < ApplicationRecord
  include TransactionalEnqueue

  belongs_to :customer
  has_many :line_items, dependent: :destroy

Transaction-Safe After-Commit Hook (Avoid Ghost Jobs)

rails activerecord background-jobs
by codesnips 4 tabs