超时引发的牛角尖二(hystrix中的超时)

至今我都清楚记得自己负责的系统请求云上关联系统时所报的异常信息。为了解决这个异常,我坚持让这个关联系统的负责人查看,并且毫不顾忌他的嘲讽和鄙视,甚至无视他烦躁的情绪。不过我还是高估了自己的脸皮,最终在其恶狠狠地抛下“你自己的问题为啥不自己看!”这句话后悻悻离开。当时,这个“超时”问题就铭刻在了我的脑海里。

回到座位,我就狠地翻起了代码,最终发现我们系统调用他们系统地请求会被包装到HystrixCommand子类对象中,然后通过调用该对象上地execute()方法来完成。但是我依旧没有弄明白超时是怎么实现的。直到今天,我才有了一个大概的思路。为了将自己的思路描述出来,先让我们看一些工作中经常用到的工具类吧。

1. CountDownLatch

首先要介绍的就是CountDownLatch。它是java并发包(java.util.concurrent)中提供的一个同步工具类,其允许一个或多个线程等待其他线程完成一组操作后再执行。它再多线程编程中主要用于实现线程间的协调和同步。接下来让我们看一下其源码:

public class CountDownLatch {
    /**
     * Synchronization control For CountDownLatch.
     * Uses AQS state to represent count.
     */
    private static final class Sync extends AbstractQueuedSynchronizer {
        private static final long serialVersionUID = 4982264981922014374L;

        Sync(int count) {
            setState(count);
        }

        int getCount() {
            return getState();
        }

        protected int tryAcquireShared(int acquires) {
            return (getState() == 0) ? 1 : -1;
        }

        protected boolean tryReleaseShared(int releases) {
            // Decrement count; signal when transition to zero
            for (;;) {
                int c = getState();
                if (c == 0)
                    return false;
                int nextc = c - 1;
                if (compareAndSetState(c, nextc))
                    return nextc == 0;
            }
        }
    }

    private final Sync sync;

    /**
     * Constructs a {@code CountDownLatch} initialized with the given count.
     *
     * @param count the number of times {@link #countDown} must be invoked
     *        before threads can pass through {@link #await}
     * @throws IllegalArgumentException if {@code count} is negative
     */
    public CountDownLatch(int count) {
        if (count < 0) throw new IllegalArgumentException("count < 0");
        this.sync = new Sync(count);
    }

    /**
     * Causes the current thread to wait until the latch has counted down to
     * zero, unless the thread is {@linkplain Thread#interrupt interrupted}.
     *
     * <p>If the current count is zero then this method returns immediately.
     *
     * <p>If the current count is greater than zero then the current
     * thread becomes disabled for thread scheduling purposes and lies
     * dormant until one of two things happen:
     * <ul>
     * <li>The count reaches zero due to invocations of the
     * {@link #countDown} method; or
     * <li>Some other thread {@linkplain Thread#interrupt interrupts}
     * the current thread.
     * </ul>
     *
     * <p>If the current thread:
     * <ul>
     * <li>has its interrupted status set on entry to this method; or
     * <li>is {@linkplain Thread#interrupt interrupted} while waiting,
     * </ul>
     * then {@link InterruptedException} is thrown and the current thread's
     * interrupted status is cleared.
     *
     * @throws InterruptedException if the current thread is interrupted
     *         while waiting
     */
    public void await() throws InterruptedException {
        sync.acquireSharedInterruptibly(1);
    }

    /**
     * Causes the current thread to wait until the latch has counted down to
     * zero, unless the thread is {@linkplain Thread#interrupt interrupted},
     * or the specified waiting time elapses.
     *
     * <p>If the current count is zero then this method returns immediately
     * with the value {@code true}.
     *
     * <p>If the current count is greater than zero then the current
     * thread becomes disabled for thread scheduling purposes and lies
     * dormant until one of three things happen:
     * <ul>
     * <li>The count reaches zero due to invocations of the
     * {@link #countDown} method; or
     * <li>Some other thread {@linkplain Thread#interrupt interrupts}
     * the current thread; or
     * <li>The specified waiting time elapses.
     * </ul>
     *
     * <p>If the count reaches zero then the method returns with the
     * value {@code true}.
     *
     * <p>If the current thread:
     * <ul>
     * <li>has its interrupted status set on entry to this method; or
     * <li>is {@linkplain Thread#interrupt interrupted} while waiting,
     * </ul>
     * then {@link InterruptedException} is thrown and the current thread's
     * interrupted status is cleared.
     *
     * <p>If the specified waiting time elapses then the value {@code false}
     * is returned.  If the time is less than or equal to zero, the method
     * will not wait at all.
     *
     * @param timeout the maximum time to wait
     * @param unit the time unit of the {@code timeout} argument
     * @return {@code true} if the count reached zero and {@code false}
     *         if the waiting time elapsed before the count reached zero
     * @throws InterruptedException if the current thread is interrupted
     *         while waiting
     */
    public boolean await(long timeout, TimeUnit unit)
        throws InterruptedException {
        return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));
    }

    /**
     * Decrements the count of the latch, releasing all waiting threads if
     * the count reaches zero.
     *
     * <p>If the current count is greater than zero then it is decremented.
     * If the new count is zero then all waiting threads are re-enabled for
     * thread scheduling purposes.
     *
     * <p>If the current count equals zero then nothing happens.
     */
    public void countDown() {
        sync.releaseShared(1);
    }

    /**
     * Returns the current count.
     *
     * <p>This method is typically used for debugging and testing purposes.
     *
     * @return the current count
     */
    public long getCount() {
        return sync.getCount();
    }

    /**
     * Returns a string identifying this latch, as well as its state.
     * The state, in brackets, includes the String {@code "Count ="}
     * followed by the current count.
     *
     * @return a string identifying this latch, as well as its state
     */
    public String toString() {
        return super.toString() + "[Count = " + sync.getCount() + "]";
    }
}

从源码可以看出,CountDownLatch内部维护了一个计数器(counter),该计数器在构造时初始化为一个特定的值。其中有两个比较常用的方法:1.countDown()方法,当一个线程完成了自己的工作后调用此方法,会将计数器减1;2.await()方法,其会在主线程或者其他等待线程中调用,如果当前计数器不为0,则会阻塞等待,直到计数器递减至0为止。此外还有一个与await()方法作用类似的方法——await(long timeout, TimeUnit unit),该方法可以实现超时等待。在这个方法中,我们会传入一个等待的超时时间(timeout)和时间单位(TimeUnit)。如果在指定的时间内计数器到达0或者当前线程被中断,则该方法会返回true。如果计数器没有到达0并且等待时间超过了指定的超时时间,那么该方法将会返回false。下面让我们看一个例子:

public class SpringTransactionApplication {

    public static void main(String[] args) {
        CountDownLatch countDownLatch = new CountDownLatch(1);
        new Thread() {
            @Override
            public void run() {
                try {
                    // 当前线程等待 10 秒钟
                    if (!countDownLatch.await(3, TimeUnit.SECONDS)) {
                        System.out.println("超时");
                        return;
                    } else {
                        System.out.println("正常");
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }.start();
        // 主线程休眠 8 秒钟
        try {
            Thread.sleep(1000 * 8);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        // 主线程调用 CountDownLatch 上的 countDown() 方法
        countDownLatch.countDown();
        // 这里会有两种情况,如果主线程 - main 的等待时间超过了当前线程 - t1 的等待时间,那么当前线程 - t1 会输出“超时“
        // 如果主线程 - main 的等待时间小于当前线程 - t1 的等待时间,则当前线程 - t1 会输出“正常”

    }

}

通过执行这个例子,我们不难发现,在主线程等待8秒的时间里,没有任何线程调用CountDownLatch上的countDown()方法,所以线程t1在等待3秒后await(timeout, TimeUnit)方法直接返回了false,所以可以看到控制台输出了超时,如下图所示:

下面让我们一起梳理一下这个类的应用场景吧:

  1. 启动屏障:主线程等待多个子线程完成初始化或任务后才能继续执行。例如,在一个服务启动时,主线程需要等待所有组件和服务加载完毕。主线程创建一个CountDownLatch,并设置计数器为组件数量,每个组件加载完成后调用countDown()方法,当计数器归零时,主线程通过await()方法解除阻塞。
  2. 一次性活动:所有参与者准备好后开始执行一次性的活动,如比赛开始。想象一个学生跑步比赛的例子,所有参赛者(线程)准备就绪后,裁判(主线程)等待所有选手(通过CountDownLatch)表示准备完毕,然后鸣枪开始比赛。
  3. 批处理任务同步:在分布式系统中,可能需要等待多个独立的异步任务完成后再进行下一步操作。比如,你可能有一个工作线程池处理大量任务,主线程使用CountDownLatch来等待所有这些任务结束。
  4. 性能测试:在压力测试或性能基准测试中,可以用来确保所有并发线程都已开始执行任务后才开始测量时间,最后再等待所有线程完成以计算总耗时。
  5. 阶段控制:多阶段任务中,某个阶段需要等待前一阶段的所有工作全部完成。例如,在构建过程中,等待所有编译任务结束后再统一进行部署。
  6. 资源初始化:当某些共享资源必须在多个线程能够访问之前先完成初始化时,可以通过CountDownLatch来实现同步。

总的来看,CountDownLatch通常用于解决一个或多个线程必须等待一组其他线程完成各自的工作之后才能继续执行的问题。(仔细审视我们的超时案例,其编程模式与CountDownLatch通常要解决的问题一致)

2.Executor及其子类

Executor是java并发编程框架中的一个核心接口,位于java.util.concurrent包中。它定义了一种统一的方式来执行异步任务,即实现了Executor的对象能够接收Runnable对象作为任务,并负责安排这些任务在某一时刻执行。下面是Executor接口的源码:

public interface Executor {

    /**
     * Executes the given command at some time in the future.  The command
     * may execute in a new thread, in a pooled thread, or in the calling
     * thread, at the discretion of the {@code Executor} implementation.
     *
     * @param command the runnable task
     * @throws RejectedExecutionException if this task cannot be
     * accepted for execution
     * @throws NullPointerException if command is null
     */
    void execute(Runnable command);
}

从上述源码可以看出,execute()方法会接收一个Runnable类型的任务参数。该任务将在Executor管理的线程中异步执行。通过这个接口,我们可以将关注点从如何创建和管理线程转移到如何定义和提交执行的任务上,从而简化了多线程编程模型,提高了程序的可读性和可维护性。另外,java提供了Executors工具类,它是一个静态工厂类,提供了多种预配置的线程池实现,比如固定大小的线程池、单线程执行器、可缓存线程池等等,这些都是ExecutorService接口(该接口继承了Executor接口)的实现,进一步增强了对线程池功能的支持,包括任务调度、线程生命周期管理以及任务结果的获取等。下面让我们来研究一下java并发包提供的一个扩展自Executor 接口的重要接口——ExecutorService,它提供了更多管理和控制线程池的方法ExecutorService 提供了启动、执行和关闭线程池的能力,以及对异步任务的更丰富的控制,比如可以取消正在执行的任务,查询线程池状态,提交具有返回值的任务等。该接口中的主要方法包括:

  1. submit(Callable<T> task): 提交一个有返回值的任务,返回一个 Future 对象,通过该对象可以获取任务执行结果或者取消任务。
  2. submit(Runnable task, T result): 提交一个无返回值的任务,并提供一个结果,返回一个 Future 对象。
  3. execute(Runnable command): 执行一个 Runnable 类型的任务,与 Executor 接口中的方法一致。
  4. shutdown(): 关闭 ExecutorService,不再接收新任务,但会将已提交的任务执行完毕。
  5. shutdownNow(): 尝试停止所有正在执行的任务并返回尚未开始的任务列表。
  6. awaitTermination(long timeout, TimeUnit unit): 等待所有任务都已完成,或者超过指定时间后终止等待。
  7. invokeAll(Collection<? extends Callable<T>> tasks): 执行给定的任务集合,当所有任务完成或超时后返回包含每个任务结果的 Future 列表。
  8. invokeAny(Collection<? extends Callable<T>> tasks): 执行给定的任务集合,返回第一个成功完成的任务的结果。

通过 ExecutorService,我们可以更加方便地管理和控制并发任务,有效地利用系统资源,提高程序的性能和响应速度等。下面让我们一起来看一下这个接口的继承体系:

首先跟大家说声抱歉,今天无法完成本篇文章的主旨了,明天我会继续就文章主旨进行梳理。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/370365.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

智能决策的艺术:探索商业分析的最佳工具和方法

文章目录 一、引言二、商业分析思维概述三、数据分析在商业实践中的应用四、如何培养商业分析思维与实践能力五、结论《商业分析思维与实践&#xff1a;用数据分析解决商业问题》亮点内容简介作者简介目录获取方式 一、引言 随着大数据时代的来临&#xff0c;商业分析思维与实…

前端小案例——滚动文本区域(HTML+CSS, 附源码)

一、前言 实现功能: 这个案例实现了一个具有滚动功能的文本区域&#xff0c;用于显示长文本内容&#xff0c;并且可以通过滚动条来查看完整的文本内容。 实现逻辑&#xff1a; 内容布局&#xff1a;在<body>中&#xff0c;使用<div>容器创建了一个类名为listen_t…

vue3 之 组合式API—watch函数

watch函数 作用&#xff1a;侦听一个或者多个数据的变化&#xff0c;数据变化时执行回调函数 两个额外参数&#xff1a; 1.immediate&#xff08;立即执行&#xff09;2.deep&#xff08;深度侦听&#xff09; 场景&#xff1a;比如选择不同的内容请求后端不同数据时 如下图 …

【算法与数据结构】300、674、LeetCode最长递增子序列 最长连续递增序列

文章目录 一、300、最长递增子序列二、674、最长连续递增序列三、完整代码 所有的LeetCode题解索引&#xff0c;可以看这篇文章——【算法和数据结构】LeetCode题解。 一、300、最长递增子序列 思路分析&#xff1a; 第一步&#xff0c;动态数组的含义。 d p [ i ] dp[i] dp[i…

IDEA 配置以及一些技巧

1. IDEA设置 1.1 设置主题 1.2 设置字体和字体大小 1.3 编辑区的字体用ctrl鼠标滚轮可以控制大小 1.4 自动导包和优化多余的包 1.5 设置编码方式 1.6 配置 maven 1.7 设置方法形参参数提示 1.8 设置控制台的字体和大小 注意&#xff1a;设置控制台字体和大小后需要重启IDEA才会…

异步解耦之RabbitMQ(二)_RabbitMQ架构及交换机

异步解耦之RabbitMQ(一)-CSDN博客 RabbitMQ架构 RabbitMQ是一个基于AMQP&#xff08;Advanced Message Queuing Protocol&#xff09;协议的消息代理中间件&#xff0c;它通过交换机和队列实现消息的路由和分发。以下是RabbitMQ的架构图&#xff1a; Producer&#xff08;生产…

LabVIEW风力发电机在线监测

LabVIEW风力发电机在线监测 随着可再生能源的发展&#xff0c;风力发电成为越来越重要的能源形式。设计了一个基于控制器局域网&#xff08;CAN&#xff09;总线和LabVIEW的风力发电机在线监测系统&#xff0c;实现风力发电机的实时监控和故障诊断&#xff0c;以提高风力发电的…

ArrayList在添加元素时报错java.lang.ArrayIndexOutOfBoundException

一、添加单个元素数组越界分析 add源码如下 public boolean add(E e) {ensureCapacityInternal(size 1); // Increments modCount!!elementData[size] e;return true; } size字段的定义 The size of the ArrayList (the number of elements it contains). ArrayList的大…

【面试官问】Redis 持久化

目录 【面试官问】Redis 持久化 Redis 持久化的方式RDB(Redis DataBase)AOF(Append Only File)混合持久化:RDB + AOF 混合方式的持久化持久化最佳方式控制持久化开关主从部署使用混合持久化使用配置更高的机器参考文章所属专区

【Django】Cookie和Session的使用

Cookies和Session 1. 会话 从打开浏览器访问一个网站&#xff0c;到关闭浏览器结束此次访问&#xff0c;称之为一次会话。 HTTP协议是无状态的&#xff0c;导致会话状态难以保持。 Cookies和Session就是为了保持会话状态而诞生的两个存储技术。 2. Cookies 2.1 Cookies定…

机器学习系列——(六)数据降维

引言 在机器学习领域&#xff0c;数据降维是一种常用的技术&#xff0c;旨在减少数据集的维度&#xff0c;同时保留尽可能多的有用信息。数据降维可以帮助我们解决高维数据带来的问题&#xff0c;提高模型的效率和准确性。本文将详细介绍机器学习中的数据降维方法和技术&#…

【Linux取经路】进程控制——程序替换

文章目录 一、单进程版程序替换看现象二、程序替换的基本原理三、程序替换接口学习3.1 替换自己写的可执行程序3.2 第三个参数 envp 验证四、结语一、单进程版程序替换看现象 #include <stdio.h> #

Vue学习笔记之组件基础

1、组件的定义 一般将 Vue 组件定义在一个单独的 .vue 文件中&#xff0c;称做单文件组件&#xff1b;当然也可以将组件直接定义在js文件中&#xff0c;如下js代码&#xff0c;定义一个组件BlogPost&#xff0c;通过props定义对外暴露属性title&#xff0c;父组件传递title&am…

List的模拟实现 迭代器

———————————————————— list与vector相比&#xff0c;插入、删除等操作实现的成本非常低&#xff0c;如果在C语言阶段熟悉理解过链表&#xff0c;那么现在实现起来list就显得比较简单&#xff0c;可以说操作层面上比vector更简洁&#xff0c;因为list没有扩…

C++ 动态规划 线性DP 最长上升子序列

给定一个长度为 N 的数列&#xff0c;求数值严格单调递增的子序列的长度最长是多少。 输入格式 第一行包含整数 N 。 第二行包含 N 个整数&#xff0c;表示完整序列。 输出格式 输出一个整数&#xff0c;表示最大长度。 数据范围 1≤N≤1000 &#xff0c; −109≤数列中的数…

istio 限流

#详细参数看官网&#xff0c;我参数就不解释https://istio.io/latest/docs/reference/config/networking/destination-rule/cat << EOF > dr.yaml apiVersion: networking.istio.io/v1alpha3 kind: DestinationRule metadata:name: my-testnamespace: demon spec:hos…

瑞_23种设计模式_抽象工厂模式

文章目录 1 抽象工厂模式&#xff08;Abstract Factory Pattern&#xff09;1.1 概念1.2 介绍1.3 小结1.4 结构 2 案例一2.1 需求2.2 代码实现 3 案例二3.1 需求3.2 代码实现 4 总结4.1 抽象工厂模式优缺点4.2 抽象工厂模式使用场景4.3 抽象工厂模式 VS 工厂方法模式4.4 抽象工…

记一次生产系统每隔10小时(36000000毫秒)固定进行一次Full GC排查思路

一、 背景描述 某个应用在生产环境通过系统监控发现&#xff0c;应用每隔10小时就会触发一次Full GC&#xff0c;该系统当时承接的业务量并不大&#xff0c;而且固定10小时就会进行Full GC&#xff0c;通过监控时间轴发现Full GC频率很规律&#xff0c;直觉告诉我这不是JVM自身…

回归预测 | Matlab实现RIME-CNN-LSTM-Attention霜冰优化卷积长短期记忆网络注意力多变量回归预测(SE注意力机制)

回归预测 | Matlab实现RIME-CNN-LSTM-Attention霜冰优化卷积长短期记忆网络注意力多变量回归预测&#xff08;SE注意力机制&#xff09; 目录 回归预测 | Matlab实现RIME-CNN-LSTM-Attention霜冰优化卷积长短期记忆网络注意力多变量回归预测&#xff08;SE注意力机制&#xff0…

计算机网络-差错控制(奇偶校验码 CRC循环冗余码)

文章目录 差错从何而来从传感器层面提高信道比来减少线路本身的随机噪声的一个例子热噪声和冲击噪声 数据链路层的差错控制检错编码-奇偶校验码检错编码-CRC循环冗余码例子注意 差错从何而来 噪声通常指的是任何未预期的、随机的信号干扰&#xff0c;这些干扰可能源自多种物理…
最新文章