国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術(shù)文章
文章詳情頁

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

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

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

1、說明

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

利用泛型和函數(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è)務(wù)函數(shù) * @param timeout 超時時間,ms * @return 返回值 */ public <R> Result<R> doWithTimeLimit(Supplier<R> bizSupplier, int timeout) { return doWithTimeLimit(bizSupplier, null, timeout); } /** * 有超時限制的方法 * * @param bizSupplier 業(yè)務(wù)函數(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毫秒,強制結(jié)束', 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('預(yù)計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方法實際耗時{}毫秒,結(jié)果:{}', 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 + '不能為空');} } } }

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

標簽: Java
相關(guān)文章:
主站蜘蛛池模板: 抚顺市| 湖北省| 汾西县| 永福县| 龙州县| 谢通门县| 浪卡子县| 兴海县| 洛宁县| 樟树市| 浦江县| 原平市| 托克逊县| 河池市| 手游| 喀喇| 宜黄县| 西林县| 子洲县| 中阳县| 容城县| 辽阳县| 来安县| 保康县| 乐安县| 克山县| 灌南县| 应用必备| 昭平县| 广宗县| 永登县| 南京市| 五原县| 靖安县| 东乡族自治县| 临颍县| 德昌县| 周宁县| 当雄县| 林周县| 新昌县|