Java編寫(xiě)超時(shí)工具類(lèi)實(shí)例講解
我們?cè)陂_(kāi)發(fā)過(guò)程中,在進(jìn)行時(shí)間操作時(shí),如果在規(guī)定的時(shí)間內(nèi)完成處理的話,有可能會(huì)回到正確的結(jié)果。否則,就會(huì)被視為超時(shí)任務(wù)。此時(shí),我們不再等待(不再執(zhí)行)的時(shí)間操作,直接向調(diào)用者傳達(dá)這個(gè)任務(wù)需要時(shí)間,被取消了。
1、說(shuō)明java已經(jīng)為我們提供了解決辦法。jdk1.5帶來(lái)的并發(fā)庫(kù)Future類(lèi)可以滿(mǎn)足這一需求。Future類(lèi)中重要的方法有g(shù)et()和cancel()。get()獲取數(shù)據(jù)對(duì)象,如果數(shù)據(jù)沒(méi)有加載,則在獲取數(shù)據(jù)之前堵塞,cancel()取消數(shù)據(jù)加載。另一個(gè)get(timeout)操作表明,如果timeout時(shí)間內(nèi)沒(méi)有得到,就會(huì)失敗回來(lái),不會(huì)堵塞。
利用泛型和函數(shù)式接口編寫(xiě)一個(gè)工具類(lèi),可以讓超時(shí)處理更方便,而不用到處寫(xiě)代碼。
2、實(shí)例/** * TimeoutUtil <br> * * @author lys * @date 2021/2/25 */@Slf4j@Component@NoArgsConstructorpublic class TimeoutUtil { private ExecutorService executorService; public TimeoutUtil(ExecutorService executorService) { this.executorService = executorService; } /** * 有超時(shí)限制的方法 * * @param bizSupplier 業(yè)務(wù)函數(shù) * @param timeout 超時(shí)時(shí)間,ms * @return 返回值 */ public <R> Result<R> doWithTimeLimit(Supplier<R> bizSupplier, int timeout) { return doWithTimeLimit(bizSupplier, null, timeout); } /** * 有超時(shí)限制的方法 * * @param bizSupplier 業(yè)務(wù)函數(shù) * @param defaultResult 默認(rèn)值 * @param timeout 超時(shí)時(shí)間,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í)行超過(guò)%d毫秒,強(qiáng)制結(jié)束', timeout); log.error(errMsg, e); futureTask.cancel(true); result = defaultResult; } return of(result, errMsg); } /** * 隨機(jī)耗時(shí)的測(cè)試方法 */ private String randomSpentTime() { Random random = new Random(); int time = (random.nextInt(10) + 1) * 1000; log.info('預(yù)計(jì)randomSpentTime方法執(zhí)行將耗時(shí): ' + 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); // 以守護(hù)線程方式啟動(dòng) thread.setDaemon(true); return thread; }); TimeoutUtil timeoutUtil = new TimeoutUtil(executorService); for (int i = 1; i <= 10; i++) { log.info('n=============第{}次超時(shí)測(cè)試=============', i); Thread.sleep(6000); long start = System.currentTimeMillis(); String result = timeoutUtil.doWithTimeLimit(() -> timeoutUtil.randomSpentTime(), 5000).getOrElse('默認(rèn)'); log.info('doWithTimeLimit方法實(shí)際耗時(shí){}毫秒,結(jié)果:{}', System.currentTimeMillis() - start, result); } }}
實(shí)例知識(shí)點(diǎn)擴(kuò)展:
屬性校驗(yàn)工具類(lèi)
/** * 校驗(yàn)對(duì)象中的屬性。如果屬性為null,拋異常。如果屬性為字符串(空串或空格),拋異常。 * @author mex * @date 2019年4月18日 * @param e 對(duì)象 * @param fieldNames 屬性名稱(chēng)數(shù)組 * @return void * @throws Exception */ public static <E> void validateAttr(E e, String[] fieldNames) throws Exception { if (null == e) { throw new Exception('請(qǐng)求對(duì)象為空'); } 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('請(qǐng)求字段:' + fieldName + '不能為空'); } // 如果該屬性為字符串,判斷其為空或空格的情況 if ('java.lang.String'.equals(typeName)) {if (StringUtils.isBlank((String)fieldValue)) { throw new Exception('請(qǐng)求字段:' + fieldName + '不能為空');} } } }
到此這篇關(guān)于Java編寫(xiě)超時(shí)工具類(lèi)實(shí)例講解的文章就介紹到這了,更多相關(guān)Java編寫(xiě)超時(shí)工具類(lèi)內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. Struts2獲取參數(shù)的三種方法總結(jié)2. JSP中Servlet的Request與Response的用法與區(qū)別3. IntelliJ IDEA刪除類(lèi)的方法步驟4. js select支持手動(dòng)輸入功能實(shí)現(xiàn)代碼5. Android 實(shí)現(xiàn)徹底退出自己APP 并殺掉所有相關(guān)的進(jìn)程6. vue cli4下環(huán)境變量和模式示例詳解7. vue使用moment如何將時(shí)間戳轉(zhuǎn)為標(biāo)準(zhǔn)日期時(shí)間格式8. Django視圖類(lèi)型總結(jié)9. IntelliJ IDEA導(dǎo)入jar包的方法10. Xml簡(jiǎn)介_(kāi)動(dòng)力節(jié)點(diǎn)Java學(xué)院整理
