V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
hello2060
V2EX  ›  Java

Spring TaskExecutor 问题

  •  
  •   hello2060 · 2021-05-20 08:58:55 +08:00 · 942 次点击
    这是一个创建于 1043 天前的主题,其中的信息可能已经有所发展或是发生改变。

    我的 service 想要开启一个线程做计算,

    所以我用了

    Class MyService() {
        SimpleAsyncTaskExecutor theExecutor = new SimpleAsyncTaskExecutor();
        theExecutor.setConcurrencyLimit(1);
    
        Runnable indexAll = () -> {
            // do job
        }
        public void doJob() {
            theExecutor.execute(indexAll);
        }
    }
    
    

    但这样的设置是,比如我调用 service.doJob() 10 次,他最终会执行 10 次,一个一个来。我的要求是一旦已经有 job 在执行了,这时候调用 service.doJob() 不会放到队列里去,也就是直接忽略。

    请问有这样的设置吗?或者 Spring 有提供任何相关的工具?

    谢谢

    hello2060
        1
    hello2060  
    OP
       2021-05-20 09:34:29 +08:00
    看来有个 bounded thread pool 可以设置超过指定数量以后丢弃,我来试试看
    oaix
        2
    oaix  
       2021-05-20 09:34:44 +08:00
    new ThreadPoolExecutor(
    1, // core
    1, // max
    0, // alive
    TimeUnit.SECONDS,
    new SynchronousQueue<>(),
    new RejectedExecutionHandler() {
    @Override
    public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
    // ignore
    }
    }
    );
    reeco
        3
    reeco  
       2021-05-20 10:05:51 +08:00 via iPhone
    加个锁不就好了吗
    ailaoli
        4
    ailaoli  
       2021-05-20 10:13:22 +08:00
    CountDownLatch ?
    hello2060
        5
    hello2060  
    OP
       2021-05-20 10:30:57 +08:00
    @oaix 这个可以的,

    .execute() 如果已经有 job 在运行会抛出 RejectedExecutionException, 完美。谢啦
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2435 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 16:04 · PVG 00:04 · LAX 09:04 · JFK 12:04
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.