最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Java編寫超時(shí)工具類實(shí)例講解

 更新時(shí)間:2021年02月28日 14:57:13   作者:小妮淺淺  
在本篇內(nèi)容里小編給大家分享的是一篇關(guān)于Java編寫超時(shí)工具類實(shí)例講解內(nèi)容,有興趣的朋友們可以學(xué)習(xí)參考下。

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

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í)處理更方便,而不用到處寫代碼。

2、實(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í)的測試方法
  */
 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í)測試=============", 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)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論

阿合奇县| 柯坪县| 高邑县| 会泽县| SHOW| 溧阳市| 河源市| 通渭县| 中宁县| 凤庆县| 盖州市| 石家庄市| 武宁县| 淅川县| 凤阳县| 饶阳县| 高阳县| 舟曲县| 封开县| 庆元县| 青河县| 增城市| 淮北市| 河东区| 鹤庆县| 贵定县| 罗田县| 正镶白旗| 手游| 镇坪县| 花莲县| 醴陵市| 高清| 龙岩市| 丽江市| 永济市| 锦屏县| 阳江市| 元江| 汶上县| 凌云县|