Simple TimerCallable Support

简介: 我们知道使用Callable可以获得线程中的返回值,它在 java.util.concurrent 包中声明。此接口还包含一个单一的、无参数的cal方法,此方法与Runnable接口的run方法类似,只是它可以返回一个值,并且可以抛出一个已检查的异常。事实上Callable也是Runnable,因为这两个接口都指定了一个有可能被另一个线程执行的类,只是它不受Runnable的限制。

前言

image (1).png
我们知道使用Callable可以获得线程中的返回值,它在 java.util.concurrent 包中声明。此接口还包含一个单一的、无参数的cal方法,此方法与Runnable接口的run方法类似,只是它可以返回一个值,并且可以抛出一个已检查的异常。事实上Callable也是Runnable,因为这两个接口都指定了一个有可能被另一个线程执行的类,只是它不受Runnable的限制。

Callable

Callable的使用很简单,多数场景下,大家肯定用它来作为并行查询、计算之类的业务场景,但是如果想统计每个任务的执行耗时,进行相关的任务优化,这个时候通常都是在任务执行前后进行时间的统计计算并输出,这里提供一个简单的工具类在统一收集。

/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

/*
 * This file is available under and governed by the GNU General Public
 * License version 2 only, as published by the Free Software Foundation.
 * However, the following notice accompanied the original version of this
 * file:
 *
 * Written by Doug Lea with assistance from members of JCP JSR-166
 * Expert Group and released to the public domain, as explained at
 * http://creativecommons.org/publicdomain/zero/1.0/
 */

package java.util.concurrent;

/**
 * A task that returns a result and may throw an exception.
 * Implementors define a single method with no arguments called
 * {@code call}.
 *
 * <p>The {@code Callable} interface is similar to {@link
 * java.lang.Runnable}, in that both are designed for classes whose
 * instances are potentially executed by another thread.  A
 * {@code Runnable}, however, does not return a result and cannot
 * throw a checked exception.
 *
 * <p>The {@link Executors} class contains utility methods to
 * convert from other common forms to {@code Callable} classes.
 *
 * @see Executor
 * @since 1.5
 * @author Doug Lea
 * @param <V> the result type of method {@code call}
 */
@FunctionalInterface
public interface Callable<V> {
    /**
     * Computes a result, or throws an exception if unable to do so.
     *
     * @return computed result
     * @throws Exception if unable to compute a result
     */
    V call() throws Exception;
}

AbstractBaseCallable

import com.google.common.base.Stopwatch;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;

/**
 * AbstractBaseCallable
 *
 * @author Duansg
 * @version 1.0
 * @date 2021/11/5 下午3:24
 */
@Slf4j
public abstract class AbstractBaseCallable<T> implements Callable<T> {

    /**
     * 获取执行体
     *
     * @return
     */
    protected abstract Supplier<T> getSupplier();

    /**
     * 获取线程名称
     *
     * @return
     */
    protected abstract String getMethodName();

    @Override
    public T call() throws Exception {
        Stopwatch stopwatch = Stopwatch.createStarted();
        try {
            return getSupplier().get();
        } finally {
            log.info("methodName:{},耗时: {} ms", getMethodName(), stopwatch.elapsed(TimeUnit.MILLISECONDS));
            stopwatch.stop();
        }
    }

}

TimerCallable

import cn.gov.zcy.service.thread.base.AbstractBaseCallable;
import lombok.Getter;

import java.util.function.Supplier;

/**
 * TimerCallable
 *
 * @author Duansg
 * @version 1.0
 * @date 2021/11/5 下午3:15
 */
@Getter
public class TimerCallable<T> extends AbstractBaseCallable<T> {

    /**
     * 线程名称
     */
    public String methodName;

    /**
     * 执行函数
     */
    private Supplier<T> supplier;

    /**
     * 构造方法
     *
     * @param methodName 执行的方法名称
     * @param supplier 方法体
     */
    public TimerCallable(String methodName, Supplier<T> supplier) {
        this.methodName = methodName;
        this.supplier = supplier;
    }

}

Test Unit

import cn.gov.zcy.service.support.ExecutorsSupport;
import cn.gov.zcy.service.thread.TimerCallable;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;

/**
 * TimerCallableTest
 *
 * @author Duansg
 * @version 1.0
 * @date 2021/11/8 上午10:07
 */
@Slf4j
public class TimerCallableTest {

    private static ExecutorService executorService = ExecutorsSupport.newFixedThreadPool(5, 5, 30, new ThreadFactoryBuilder()
            .setNameFormat("TimerCallableTest-test-%d").build());


    public static void main(String[] args) {

        Future<String> itemMapTask =
                executorService.submit(new TimerCallable<>("TimerCallableTest#main", () ->{
                    log.info("Dunssss");

                    return  "Duansg";
                }));
        try {
            System.out.println(itemMapTask.get());
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            executorService.shutdown();
        }
    }
}
目录
相关文章
|
10月前
|
人工智能 API 开发者
重磅官宣!阿里云百炼Coding Plan四大模型齐上线,7.9元就能用顶配
阿里云百炼Coding Plan上线Qwen3.5、GLM-5、MiniMax M2.5、Kimi K2.5四大顶尖开源模型,支持Qwen Code等工具自由切换。Lite套餐首月7.9元(1.8万次请求),Pro仅39.9元(9万次),大幅降低开发成本。
|
人工智能 JavaScript 测试技术
Qwen3-Coder入门教程|10分钟搞定安装配置
Qwen3-Coder 挑战赛简介:无论你是编程小白还是办公达人,都能通过本教程快速上手 Qwen-Code CLI,利用 AI 轻松实现代码编写、文档处理等任务。内容涵盖 API 配置、CLI 安装及多种实用案例,助你提升效率,体验智能编码的乐趣。
39989 114
|
存储 Java API
SpringBoot整合Flowable【02】- 整合初体验
本文介绍了如何基于Flowable 6.8.1版本搭建工作流项目。首先,根据JDK和Spring Boot版本选择合适的Flowable版本(7.0以下)。接着,通过创建Spring Boot项目并配置依赖,包括Flowable核心依赖、数据库连接等。然后,建立数据库并配置数据源,确保Flowable能自动生成所需的表结构。最后,启动项目测试,确认Flowable成功创建了79张表。文中还简要介绍了这些表的分类和常用表的作用,帮助初学者理解Flowable的工作原理。
4414 0
SpringBoot整合Flowable【02】- 整合初体验
|
敏捷开发 运维 测试技术
Codes 告诉你2025不可不知道的极简项目任务管理流程及实践
所谓的极简,说白了就是管理好工作事项,让人和事清晰明了,事项进度一目了然,人员的工作动态尽在掌握即可,不需要复杂的流程,事项记录清楚且方便协同就行。这种模式适合什么项目呢?适合运行期项目,运维类项目,日常维护类项目,小团队开发周期短的小项目等。非正规模式的项目管理,也就是任务即需求,也就是围绕任务展来进行项目管理,存在即合理。本篇我们就对这种任务即需求的非正规模式,来说道说道两种最常用的任务管理模式实践。
|
监控 安全 数据安全/隐私保护
Windows 账号管理与安全指南
本文详细介绍了Windows账号管理与安全防护方法,涵盖基础命令(如`net user`和`whoami`)、隐藏账户技术及安全措施。通过学习账户创建、权限管理和状态调整等操作,结合密码策略配置、弱密码防御和系统审计,帮助管理员提升系统安全性,防范潜在威胁。同时提醒注意隐藏账户可能带来的风险,建议定期检查和监控系统账户状态,确保安全可控。
1566 0
|
监控 安全 网络安全
防火墙和入侵检测系统
【8月更文挑战第16天】
1144 1
|
物联网 PyTorch 测试技术
手把手教你捏一个自己的Agent
Modelscope AgentFabric是一个基于ModelScope-Agent的交互式智能体应用,用于方便地创建针对各种现实应用量身定制智能体,目前已经在生产级别落地。
|
存储 敏捷开发 安全
阿里云云原生 DevOps-云效平台六大产品(1)
阿里云云原生 DevOps-云效平台六大产品(1)
阿里云云原生 DevOps-云效平台六大产品(1)
|
算法 数据安全/隐私保护
基于星座图整形方法的QAM调制解调系统MATLAB误码率仿真,对比16,32,64,256四种QAM调制方式
本MATLAB 2022a仿真展示了不同QAM阶数下的星座图及误码率性能,通过星座图整形技术优化了系统性能。该技术利用非均匀分布的星座点提高功率效率,并通过合理布局增强抗干扰能力。随着QAM阶数增加,数据传输速率提升,但对信道质量要求也更高。核心程序实现了从比特生成到QAM映射、功率归一化、加噪及解调的全过程,并评估了系统误码率。
1169 0
|
Python
Python解释raise关键字的作用。
Python解释raise关键字的作用。
1925 1