!457 HashMap应指定初始长度,增加CompletableFuture相关封装

Merge pull request !457 from 阿超/v5-dev
This commit is contained in:
Looly
2021-11-10 14:49:50 +00:00
committed by Gitee
4 changed files with 92 additions and 4 deletions

View File

@@ -179,7 +179,7 @@ public class CollStreamUtil {
Set<K> key = new HashSet<>();
key.addAll(map1.keySet());
key.addAll(map2.keySet());
Map<K, V> map = new HashMap<>();
Map<K, V> map = MapUtil.newHashMap(key.size());
for (K t : key) {
X x = map1.get(t);
Y y = map2.get(t);

View File

@@ -0,0 +1,53 @@
package cn.hutool.core.thread;
import cn.hutool.core.exceptions.ExceptionUtil;
import java.lang.reflect.UndeclaredThrowableException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
/**
* CompletableFuture工具类叫CompletableFutureUtil太长
*
* @author <achao1441470436@gmail.com>
* @since 2021/11/10 0010 20:55
*/
public class SyncUtil {
private SyncUtil() {
/* Do not new me! */
}
/**
* 等待所有任务执行完毕,包裹了异常
*
* @param tasks 并行任务
* @throws UndeclaredThrowableException 未受检异常
*/
public static void wait(CompletableFuture<?>... tasks) {
try {
CompletableFuture.allOf(tasks).get();
} catch (InterruptedException | ExecutionException e) {
ExceptionUtil.wrapAndThrow(e);
}
}
/**
* 获取异步任务结果,包裹了异常
*
* @param task 异步任务
* @param <T> 任务返回值类型
* @return 任务返回值
* @throws RuntimeException 未受检异常
*/
public static <T> T get(CompletableFuture<T> task) {
RuntimeException exception;
try {
return task.get();
} catch (InterruptedException | ExecutionException e) {
exception = ExceptionUtil.wrapRuntime(e);
}
throw exception;
}
}

View File

@@ -1362,10 +1362,9 @@ public class NumberUtil {
throw new UtilException("Size is larger than range between begin and end!");
}
Random ran = new Random();
Set<Integer> set = new HashSet<>();
Set<Integer> set = new HashSet<>(Math.max((int) (size / .75f) + 1, 16));
while (set.size() < size) {
set.add(begin + ran.nextInt(end - begin));
set.add(begin + RandomUtil.randomInt(end - begin));
}
return set.toArray(new Integer[size]);

View File

@@ -0,0 +1,36 @@
package cn.hutool.core.thread;
import cn.hutool.core.lang.Assert;
import org.junit.Test;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
/**
* CompletableFuture工具类测试
*
* @author <achao1441470436@gmail.com>
* @since 2021/11/10 0010 21:15
*/
public class SyncUtilTest {
@Test
public void waitAndGetTest() {
CompletableFuture<String> hutool = CompletableFuture.supplyAsync(() -> {
ThreadUtil.sleep(3, TimeUnit.SECONDS);
return "hutool";
});
CompletableFuture<String> sweater = CompletableFuture.supplyAsync(() -> {
ThreadUtil.sleep(4, TimeUnit.SECONDS);
return "卫衣";
});
CompletableFuture<String> warm = CompletableFuture.supplyAsync(() -> {
ThreadUtil.sleep(5, TimeUnit.SECONDS);
return "真暖和";
});
// 等待完成
SyncUtil.wait(hutool, sweater, warm);
// 获取结果
Assert.isTrue("hutool卫衣真暖和".equals(SyncUtil.get(hutool) + SyncUtil.get(sweater) + SyncUtil.get(warm)));
}
}