RSS feed [root] /concurrency /java /weblog




login:

password:

title search:




 


Tue Feb 15 17:16:05 GMT 2011

AnonymousInnerClass



Here is an tricky concurrency concern in Java when using Anonymous Inner Class with ExecutorService, if you use collection from outside class, that collection actually a global variable in the Inner Class, and need to take care the issues happened in concurrency access.

For this class:

public static void main(String[] args) throws InterruptedException {
ExecutorService es = Executors.newFixedThreadPool(80);
final List list = new ArrayList();
for (int i = 0; i < 100000; i++)
es.execute(new Runnable() {
@Override
public void run() {
list.add(new String());
}
});
es.shutdown();
while (true) {
boolean terminated = es.awaitTermination(5, TimeUnit.SECONDS);
if (terminated) {
break;
}
}
for (String string : list) {
if (string == null)
System.out.println("Have null");
}
}

actually same as

private static final class RunnableImpl implements Runnable {
private final List mList;
private RunnableImpl(List list) {
mList = list;
}

@Override
public void run() {
mList.add(new String());
}
}
public static void main(String[] args) throws InterruptedException {
ExecutorService es = Executors.newFixedThreadPool(80);
final List list = new ArrayList();
for (int i = 0; i < 100000; i++)
es.execute(new RunnableImpl(list));
/** @formatter:on */
es.shutdown();
while (true) {
boolean terminated = es.awaitTermination(5, TimeUnit.SECONDS);
if (terminated) {
break;
}
}
for (String string : list) {
if (string == null)
System.out.println("Have null");
}
}



(google search) (amazon search)
second
download zip of files only