您好,登錄后才能下訂單哦!
本文章向大家介紹利用Java怎么實(shí)現(xiàn)一個(gè)超時(shí)工具類的基本知識(shí)點(diǎn)總結(jié)和需要注意事項(xiàng),具有一定的參考價(jià)值,需要的朋友可以參考一下。
Java的特點(diǎn)有哪些 1.Java語言作為靜態(tài)面向?qū)ο缶幊陶Z言的代表,實(shí)現(xiàn)了面向?qū)ο罄碚摚试S程序員以優(yōu)雅的思維方式進(jìn)行復(fù)雜的編程。 2.Java具有簡單性、面向?qū)ο?、分布式、安全性、平臺(tái)獨(dú)立與可移植性、動(dòng)態(tài)性等特點(diǎn)。 3.使用Java可以編寫桌面應(yīng)用程序、Web應(yīng)用程序、分布式系統(tǒng)和嵌入式系統(tǒng)應(yīng)用程序等。
1、說明
java已經(jīng)為我們提供了解決辦法。jdk1.5帶來的并發(fā)庫Future類可以滿足這一需求。Future類中重要的方法有g(shù)et()和cancel()。get()獲取數(shù)據(jù)對(duì)象,如果數(shù)據(jù)沒有加載,則在獲取數(shù)據(jù)之前堵塞,cancel()取消數(shù)據(jù)加載。另一個(gè)get(timeout)操作表明,如果timeout時(shí)間內(nèi)沒有得到,就會(huì)失敗回來,不會(huì)堵塞。
利用泛型和函數(shù)式接口編寫一個(gè)工具類,可以讓超時(shí)處理更方便,而不用到處寫代碼。
/** * TimeoutUtil <br> * * @author lys * @date 2021/2/25 */ @Slf4j @Component @NoArgsConstructor public 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í)行超過%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)工具類
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ī)淼睦肑ava怎么實(shí)現(xiàn)一個(gè)超時(shí)工具類的全部內(nèi)容了,希望大家多多支持億速云!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。