亚洲精品久久久中文字幕-亚洲精品久久片久久-亚洲精品久久青草-亚洲精品久久婷婷爱久久婷婷-亚洲精品久久午夜香蕉

您的位置:首頁技術文章
文章詳情頁

Java編寫超時工具類實例講解

瀏覽:44日期:2022-08-16 09:03:40

我們在開發(fā)過程中,在進行時間操作時,如果在規(guī)定的時間內完成處理的話,有可能會回到正確的結果。否則,就會被視為超時任務。此時,我們不再等待(不再執(zhí)行)的時間操作,直接向調用者傳達這個任務需要時間,被取消了。

1、說明

java已經(jīng)為我們提供了解決辦法。jdk1.5帶來的并發(fā)庫Future類可以滿足這一需求。Future類中重要的方法有get()和cancel()。get()獲取數(shù)據(jù)對象,如果數(shù)據(jù)沒有加載,則在獲取數(shù)據(jù)之前堵塞,cancel()取消數(shù)據(jù)加載。另一個get(timeout)操作表明,如果timeout時間內沒有得到,就會失敗回來,不會堵塞。

利用泛型和函數(shù)式接口編寫一個工具類,可以讓超時處理更方便,而不用到處寫代碼。

2、實例

/** * TimeoutUtil <br> * * @author lys * @date 2021/2/25 */@Slf4j@Component@NoArgsConstructorpublic class TimeoutUtil { private ExecutorService executorService; public TimeoutUtil(ExecutorService executorService) { this.executorService = executorService; } /** * 有超時限制的方法 * * @param bizSupplier 業(yè)務函數(shù) * @param timeout 超時時間,ms * @return 返回值 */ public <R> Result<R> doWithTimeLimit(Supplier<R> bizSupplier, int timeout) { return doWithTimeLimit(bizSupplier, null, timeout); } /** * 有超時限制的方法 * * @param bizSupplier 業(yè)務函數(shù) * @param defaultResult 默認值 * @param timeout 超時時間,ms * @return 返回值 */ public <R> Result<R> doWithTimeLimit(Supplier<R> bizSupplier, R defaultResult, int timeout) { R result; String errMsg = 'Null value'; FutureTask<R> futureTask = new FutureTask<>(bizSupplier::get); executorService.execute(futureTask); try { result = futureTask.get(timeout, TimeUnit.MILLISECONDS); } catch (InterruptedException | ExecutionException | TimeoutException e) { errMsg = String.format('doWithTimeLimit執(zhí)行超過%d毫秒,強制結束', timeout); log.error(errMsg, e); futureTask.cancel(true); result = defaultResult; } return of(result, errMsg); } /** * 隨機耗時的測試方法 */ private String randomSpentTime() { Random random = new Random(); int time = (random.nextInt(10) + 1) * 1000; log.info('預計randomSpentTime方法執(zhí)行將耗時: ' + time + '毫秒'); try { Thread.sleep(time); } catch (Exception e) { } return 'randomSpentTime --> ' + time; } public static void main(String[] args) throws Exception { ExecutorService executorService = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), runnable -> { Thread thread = new Thread(runnable); // 以守護線程方式啟動 thread.setDaemon(true); return thread; }); TimeoutUtil timeoutUtil = new TimeoutUtil(executorService); for (int i = 1; i <= 10; i++) { log.info('n=============第{}次超時測試=============', i); Thread.sleep(6000); long start = System.currentTimeMillis(); String result = timeoutUtil.doWithTimeLimit(() -> timeoutUtil.randomSpentTime(), 5000).getOrElse('默認'); log.info('doWithTimeLimit方法實際耗時{}毫秒,結果:{}', System.currentTimeMillis() - start, result); } }}

實例知識點擴展:

屬性校驗工具類

/** * 校驗對象中的屬性。如果屬性為null,拋異常。如果屬性為字符串(空串或空格),拋異常。 * @author mex * @date 2019年4月18日 * @param e 對象 * @param fieldNames 屬性名稱數(shù)組 * @return void * @throws Exception */ public static <E> void validateAttr(E e, String[] fieldNames) throws Exception { if (null == e) { throw new Exception('請求對象為空'); } if (null == fieldNames) { return; } for (int i = 0; i < fieldNames.length; i++) { String fieldName = fieldNames[i]; Field field = e.getClass().getDeclaredField(fieldName); String typeName = field.getGenericType().getTypeName(); field.setAccessible(Boolean.TRUE); Object fieldValue = field.get(e); // 判斷該屬性為null的情況 if (null == fieldValue) {throw new Exception('請求字段:' + fieldName + '不能為空'); } // 如果該屬性為字符串,判斷其為空或空格的情況 if ('java.lang.String'.equals(typeName)) {if (StringUtils.isBlank((String)fieldValue)) { throw new Exception('請求字段:' + fieldName + '不能為空');} } } }

到此這篇關于Java編寫超時工具類實例講解的文章就介紹到這了,更多相關Java編寫超時工具類內容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持好吧啦網(wǎng)!

標簽: Java
相關文章:
主站蜘蛛池模板: 性色xxx视频 | 免费黄网址 | 国产在线精品观看 | 手机国产日韩高清免费看片 | 国产淫视| 久久久精品久久视频只有精品 | 99久免费精品视频在线观看2 | 久久精品国产99久久3d动漫 | 91原创视频在线 | 国产一区二区精品久久 | 加勒比一本一道在线 | 看黄色的视频 | 黄色一级视频免费看 | 免费a级片在线观看 | 亚洲成人一区二区 | 国产成人啪精品视频免费网 | 国产综合精品在线 | 嘿嘿嘿视频在线观看 | 黄录像欧美片在线观看 | 天天做天天爱天天影视综合 | 欧美黄色片免费 | 91精品一区二区三区在线观看 | 国产一区高清视频 | 国产免费一级高清淫日本片 | 国产免费69成人精品视频 | 日韩亚洲视频 | 欧美日韩一区二区三区毛片 | 亚洲大胆视频 | 国产成人精品三级91在线影院 | 精品成人免费播放国产片 | 永久免费的啪啪免费的网址 | 国产911情侣拍拍在线播放 | 色婷婷综合久久久久中文一区二区 | 婷婷黄色| 亚洲图片国产日韩欧美 | 久久国产视频在线观看 | 国产精品麻豆久久99 | 国产一级黄毛片 | 三级黄色毛片 | 人人综合| 中国大陆一级毛片 免费 |