V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
hello2060
V2EX  ›  Java

Spring TaskExecutor 问题

  •  
  •   hello2060 · May 20, 2021 · 1759 views
    This topic created in 1806 days ago, the information mentioned may be changed or developed.

    我的 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
       May 20, 2021
    看来有个 bounded thread pool 可以设置超过指定数量以后丢弃,我来试试看
    oaix
        2
    oaix  
       May 20, 2021
    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  
       May 20, 2021 via iPhone
    加个锁不就好了吗
    ailaoli
        4
    ailaoli  
       May 20, 2021
    CountDownLatch ?
    hello2060
        5
    hello2060  
    OP
       May 20, 2021
    @oaix 这个可以的,

    .execute() 如果已经有 job 在运行会抛出 RejectedExecutionException, 完美。谢啦
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2630 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 39ms · UTC 15:20 · PVG 23:20 · LAX 08:20 · JFK 11:20
    ♥ Do have faith in what you're doing.