计算catch块中发生的异常数 [英] Counting the number of exceptions happening in catch block
问题描述
我试图在 ConcurrentHashMap
中收集所有发生的异常计数和异常名称,以便使我知道该异常发生了多少次.
I am trying to collect all the counts of exception happening and the name of exception in a ConcurrentHashMap
so that I should be aware of how many times this exception has occurred.
所以在我的catch块中,我有一个映射,该映射将继续添加异常的名称,并且总计数出现.
So in my catch block I have map that will keep on adding the name of exception and there total count occurrence.
下面是我的代码,出于测试目的,我已对其进行了修改,每次都始终抛出SQL异常
,以便我可以看到异常计数是否正确.
Below is my code which I have modified to always throw SQL Exception
everytime for the testing purpose so that I can see the count of exception is accurate or not.
某些情况下-
1)如果我将线程数选择为 10
,将任务数选择为 50
,则在该图中,我可以看到该特定String <的500个异常
1) If I am choosing number of threads as 10
and number of tasks as 50
, then in that map, I can see 500 exception for that particular String
2)但是,如果我将线程数选择为 40
,将任务数选择为 500
,那么我看不到 20000
异常那个地图,它显示在 19000
附近.
2)But If I am choosing number of threads as 40
and number of tasks as 500
then I am not seeing 20000
exceptions in that map, it shows around 19000
.
我的问题是为什么?我在这里做什么错了?
My question is why? What wrong I am doing here?
class Task implements Runnable {
public static final AtomicInteger counter_exception = new AtomicInteger(0);
public static ConcurrentHashMap<String, Integer> exceptionMap = new ConcurrentHashMap<String, Integer>();
@Override
public void run() {
try {
//Making a db connection and then executing the SQL-
} catch (SQLException e) {
exceptionMap.put(e.getCause().toString(), counter_exception.incrementAndGet());
} catch (Exception e) {
}
}
}
已更新:
如果我有类似的东西,我将得到40个线程和4000个任务的 Null Pointer Exception
.为什么?
If I have something like this- I am getting Null Pointer Exception
for 40 threads and 4000 taks. Why?
catch (SQLException e) {
synchronized(this) {
exceptionMap.put(e.getCause().toString(), counter_exception.incrementAndGet());
}
}
推荐答案
也许正在发生这样的事情:
Maybe something like this is happening:
任务1-500:捕获异常,准备调用 exceptionMap.put
,从 counter_exception.incrementAndGet()
中获取一个传递给所述方法的数字
Task 1-500: Catch exceptions, prepare to call exceptionMap.put
, get a number from counter_exception.incrementAndGet()
that is passed to said method
任务500:计划从原子整数计数器中获取数字500,因此其 exceptionMap.put
首先运行
Task 500: Has number 500 from the atomic integer counter, is scheduled so its exceptionMap.put
runs first
任务1:已安排原子整数计数器的编号为1,因此其 exceptionMap.put
最后运行
Task 1: Has number 1 from the atomic integer counter, is scheduled so its exceptionMap.put
runs last
现在,即使计数器为500,并且我们有500个异常,该异常消息也会与1关联,因为该消息是最近执行的.
Now even though the counter is 500 and we had 500 exceptions, the exception message gets associated with 1 because that was executed the most recently.
这篇关于计算catch块中发生的异常数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!