我正在考虑多线程代码中发生count
的次数。exceptions
因此,我所做的是,我创建了一种方法addException
,在该方法中我使用AtomicInteger
.
addException
方法接受两个参数,one is the String
和 otherboolean flag
表示我们是否要因为任何异常而终止程序。意思是,如果该标志为真,那么只要有任何异常,我都需要终止程序。
因此,如果您查看我的下面的catch
块,我有addException
用于计算异常的方法调用,并且在该方法调用下面我也在记录异常。
ExecutorService service = Executors.newFixedThreadPool(threads);
for (int i = 0; i < threads; i++) {
service.submit(new ReadTask());
}
class ReadTask implements Runnable {
public static ConcurrentHashMap<String, AtomicInteger> exceptionMap = new ConcurrentHashMap<String, AtomicInteger>();
public ReadTask() {
}
@Override
public run() {
try {
.........
} catch (ClassNotFoundException e) {
addException(e.getCause() != null ? e.getCause().toString() : e.toString(), Read.flagTerminate);
LOG.error("Threw a ClassNotFoundException in " + getClass().getSimpleName(), e);
} catch (SQLException e) {
addException(e.getCause() != null ? e.getCause().toString() : e.toString(), Read.flagTerminate);
LOG.error("Threw a SQLException while making connection to database in " + getClass().getSimpleName(), e);
}
}
/**
* A simple method that will add the count of exceptions and name of
* exception to a map
*
* @param cause
* @param flagTerminate
*/
private static void addException(String cause, boolean flagTerminate) {
AtomicInteger count = exceptionMap.get(cause);
if (count == null) {
count = new AtomicInteger();
AtomicInteger curCount = exceptionMap.putIfAbsent(cause, count);
if (curCount != null) {
count = curCount;
}
}
count.incrementAndGet();
if(flagTerminate) {
System.exit(1);
}
}
}
问题陈述:-
此代码是否可能存在任何线程争用?如果是,我怎样才能addException
以更好的方式编写方法来避免Thread Contention
?
这里有没有更有效的写法addException
?