java 方法要求固定时间返回值
有的java方法太复杂,耗时偶尔很长,怎么解决?限制时间,超时就不要了。
文/程忠 浏览次数:0次 2022-01-13 17:32:46
package net.highersoft.service; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TestTime { private static Logger log=LoggerFactory.getLogger(TestTime.class); public static void main(String[] args) { testMethod(); } public static void testMethod() { CompletableFuture<Object> future = CompletableFuture.supplyAsync(() -> { try { int randTime=(int)(Math.random()*5000); System.out.println("sleep:"+randTime); Thread.sleep(randTime); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException("Interrupted", e); } return "abc"; }); try { Object rst=future.get(2000, TimeUnit.MILLISECONDS); System.out.println("return:"+rst); } catch (TimeoutException e) { // Operation timed out. Cancel it and log. future.cancel(true); log.error("Timed out", e); } catch (InterruptedException e) { // Current thread interrupted while waiting. Cancel operation and log. future.cancel(true); log.error("Interrupted", e); // Reassert interrupt flag, since exception is not propagated. Thread.currentThread().interrupt(); } catch (ExecutionException e) { log.error("Operation failed", e.getCause()); // No need to cancel in this case, since the operation has completed. } } }
相关阅读
评论:
↓ 广告开始-头部带绿为生活 ↓
↑ 广告结束-尾部支持多点击 ↑