Setting a maximum execution time for a method/thread

前端 未结 2 1406
一整个雨季
一整个雨季 2020-12-09 11:07

I have a method, which writes to the database. The requirement is to make sure that this method does not execute after a certain time elapses. If it returns before that, the

相关标签:
2条回答
  • 2020-12-09 11:54

    You can do this by sending your job to an executor:

     public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(4);
    
        Future<?> future = executor.submit(new Runnable() {
            @Override
            public void run() {
                writeToDb();            //        <-- your job
            }
        });
    
        executor.shutdown();            //        <-- reject all further submissions
    
        try {
            future.get(8, TimeUnit.SECONDS);  //     <-- wait 8 seconds to finish
        } catch (InterruptedException e) {    //     <-- possible error cases
            System.out.println("job was interrupted");
        } catch (ExecutionException e) {
            System.out.println("caught exception: " + e.getCause());
        } catch (TimeoutException e) {
            future.cancel(true);              //     <-- interrupt the job
            System.out.println("timeout");
        }
    
        // wait all unfinished tasks for 2 sec
        if(!executor.awaitTermination(2, TimeUnit.SECONDS)){
            // force them to quit by interrupting
            executor.shutdownNow();
        }
    }
    
    0 讨论(0)
  • 2020-12-09 12:06

    There is also an AspectJ solution for that with jcabi-aspects library:

    @Timeable(limit = 5, unit = TimeUnit.SECONDS)
    public String writeToDb() {
      // writeToDb
    }
    

    There is an article explaining it further: Limit Java Method Execution Time

    0 讨论(0)
提交回复
热议问题