我如何计算线程抛出的异常数?

时间:2015-08-05 11:38:57

标签: 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列表放在一边。但那又怎么样?

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:0)

除了user158037的想法,您可以实现自己的 ThreadPoolExecutor 子类,并使用afterExecute method覆盖。比使用该类而不是 Executors.newFixedThreadPool 。您可以在集中的位置访问Throwables,并且可以对它们进行计数,而无需将Callables更改为Futures。

相关问题