java - 如何统计线程抛出异常的数量?

标签 java multithreading exception

我有这个代码:

@Test
public void setUserNamePropertyFromMultiThreadsUpdatesCorrectly() throws Exception {
    boolean oldVal = UsersConfig.s.NO_DB_MODE;
        final List<String> lastName = new ArrayList<String>();
        UsersConfig.s.NO_DB_MODE = true;

        String user1 = testUtils.generateUserName();
        final Long createdId = testUtils.createUserWithProperties(ImmutableMap.of("username", user1, "A", "A1",
                "isStaff", "true"));

        List<Callable<Void>> callables = new ArrayList<Callable<Void>>();
        for (int i = 0; i < 20; i++) {
            callables.add(new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    String user2 = testUtils.generateUserName();
                    boolean isSuccess = usersServerAccess.setProperties(createdId,
                            ImmutableMap.of("isStaff", "dont_know", "username", user2),
                            1, "test set", someTimeOut);
                    assertTrue(isSuccess);

                    synchronized (lastName) {
                        lastName.add(user2);
                    }
                    return null;
                }
            });

        ExecutorService executorService = Executors.newFixedThreadPool(10);
        try {
            executorService.invokeAll(callables);
            executorService.shutdown();
            executorService.awaitTermination(1, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }

        User returnedUser = usersServerAccess.getUser(createdId, "get test", someTimeOut);
        assertThat(returnedUser.getProperty("username"), equalTo(lastName.get(0)));
        assertThat(returnedUser.getProperty("A"), equalTo("A1"));
        assertThat(returnedUser.getProperty("isStaff"), equalTo("dont_know"));
}

我想断言没有线程抛出异常。

我该怎么做?

我可以把 future 列表放在一边。但然后呢?

最佳答案

当您在 Future 上执行 get() 时,您可能会得到 ExecutionException,然后只需使用 getCause() 即可返回实际的异常。

关于java - 如何统计线程抛出异常的数量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31831459/

相关文章:

java - 新的java.io.IOException : Call requires API level 9

java - Struts 1.2.9 重新加载application.properties

java - 如何加载和使用经过 Mallet 训练的 CRF?

c++ - 何时为指向动态创建内存的静态指针创建内存?

Python线程传递参数

c - 向设备发送数据时 UNIX read()/write() 的原子性

java - 不使用反射访问类的字段?

java - 如何在列中仅设置一个可能的值

Python:作业中的异常

python - 为什么我的 Flask 错误处理程序没有被调用?