Java編寫超時(shí)工具類實(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類可以滿足這一需求。Future類中重要的方法有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ù)式接口編寫一個(gè)工具類,可以讓超時(shí)處理更方便,而不用到處寫代碼。
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)工具類
/** * 校驗(yàn)對(duì)象中的屬性。如果屬性為null,拋異常。如果屬性為字符串(空串或空格),拋異常。 * @author mex * @date 2019年4月18日 * @param e 對(duì)象 * @param fieldNames 屬性名稱數(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編寫超時(shí)工具類實(shí)例講解的文章就介紹到這了,更多相關(guān)Java編寫超時(shí)工具類內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. idea重置默認(rèn)配置的方法步驟2. IntelliJ IDEA安裝插件的方法步驟3. IntelliJ IDEA設(shè)置自動(dòng)提示功能快捷鍵的方法4. Docker 部署 Prometheus的安裝詳細(xì)教程5. idea導(dǎo)入maven項(xiàng)目的方法6. 通過(guò)Django Admin+HttpRunner1.5.6實(shí)現(xiàn)簡(jiǎn)易接口測(cè)試平臺(tái)7. idea打開(kāi)多個(gè)窗口的操作方法8. IntelliJ IDEA設(shè)置背景圖片的方法步驟9. IntelliJ IDEA調(diào)整字體大小的方法10. idea設(shè)置代碼格式化的方法步驟

網(wǎng)公網(wǎng)安備