← 中文资源

简体中文版本

活锁与饥饿

活锁让线程忙而无效——彼此反复检测冲突又完美同步地退避;饥饿则是在系统整体前进的同时,特定任务始终得不到调度或资源。

阅读英文原文

概念定义

“没有进展”背后藏着两种失败:死锁原地等待;活锁不停运动——重试、退避、让渡——却永远完不成;饥饿则让整个系统照常运转,唯独选中的任务永远轮不到。

工作机制

活锁源自对称协议:双方都检测到冲突、都让路、以相同节奏重试。修复靠打破对称——随机指数退避、差异化优先级、决胜资源。饥饿源自不公平调度或资源策略;“老化”(随等待提升有效优先级)恢复最终服务。

使用场景

乐观锁重试循环、分布式租约交接、竞争消费者之间的消息重投、无公平性或老化的调度配置。告警要看“操作年龄”,不只看线程状态。

常见误区

活锁不是死锁的一种——死锁阻塞、活锁烧 CPU 什么都不成,这正是活性探针漏报的原因:CPU 与可运行线程都正常。退避不加抖动会保留同步性。分布式活锁横跨服务,本地线程转储看不到卡死——必须跨边界关联重试。饥饿不等于系统停摆:系统在前进,只是特定工作在无声地错过截止时间。

代码示例

#!/usr/bin/env bash
set -euo pipefail

# Custom exit codes
E_SUCCESS=0
E_NO_ARGS=1
E_FILE_NOT_FOUND=2
E_PERMISSION=3
E_DEPENDENCY=4

# Check dependencies
check_dependency() {
    if ! command -v "$1" &>/dev/null; then
        echo "Error: $1 is required but not installed" >&2
        exit "$E_DEPENDENCY"
    fi
}

# Main function with error handling
main() {
    local input_file="${1:-}"

    if [[ -z "$input_file" ]]; then
        echo "Usage: $0 <input-file>" >&2
        exit "$E_NO_ARGS"
    fi

    if [[ ! -f "$input_file" ]]; then
        echo "Error: File not found: $input_file" >&2
        exit "$E_FILE_NOT_FOUND"
    fi

    if [[ ! -r "$input_file" ]]; then
        echo "Error: Cannot read file: $input_file" >&2
        exit "$E_PERMISSION"
    fi

    local output
    if ! output=$(wc -l "$input_file" 2>&1); then
        echo "Error processing file: $output" >&2
        exit 1
    fi

    echo "$output"
    exit "$E_SUCCESS"
}

# Check required tools
for tool in grep sort wc; do
    check_dependency "$tool"
done

main "$@"
public class CustomExceptions {

    static class DomainException extends Exception {
        public DomainException(String message, Throwable cause) {
            super(message, cause);
        }
    }

    static class ValidationException extends DomainException {
        public ValidationException(String message) {
            super(message, null);
        }
    }

    static class NotFoundException extends DomainException {
        public NotFoundException(String id) {
            super("Resource not found: " + id, null);
        }
    }

    static void validateAge(int age) throws ValidationException {
        if (age < 0 || age > 150) {
            throw new ValidationException("Invalid age: " + age);
        }
    }

    static String findUser(String id) throws NotFoundException {
        if (!"admin".equals(id)) {
            throw new NotFoundException(id);
        }
        return "Administrator";
    }

    public static void main(String[] args) {
        try {
            validateAge(200);
            findUser("guest");
        } catch (ValidationException | NotFoundException e) {
            System.err.println("Error: " + e.getMessage());
        }
    }
}