Is this code thread safe ?
create runnable and invoke a method by reflection :
public class A {
public static void someMethod (List<VO> voList){
int endIndex=0;
for (int firstIndex = 0; firstIndex < voList.size(); ) {
endIndex = Math.min(firstIndex + threadSize, voList.size());
Runner runner = null;
try {
runner = new Runner(voList.subList(firstIndex, endIndex),
B.class.getMethod("createSomeString", D.class));
} catch (NoSuchMethodException ex) {
log.warn(ex.getMessage());
}
//start a thread
runner.start();
}
}
private static class Runner extends Thread {
private Method method;
private List<C> list;
public Runner(Method method,List<C> clist) {
this.method = method;
this.list=clist;
}
}
public void run() {
for (C vo: list) {
String xml = (String) method.invoke(null,vo);
}
}
}
I want to call a static method by reflection ,is this code block thread safe ?
public class B {
public static String createSomeString(D a) throws Exception {
return a.name;
}
}
and D.class is Plain old java object class like this :
public class D implements Serializable{
private String name;
}
If you're using static variables inside the method, or anything else that needs to be thread safe, the synchronized
keyword is one option.
public class B {
public synchronized String createSomeString(A a) throws Exception {
return a.name;
}
}
Another option would be to use a queue with a pool size of one. Google has a good example project available for this available at: Running Code on a Thread Pool Thread
If it's a.name
that may be accessed by multiple threads then you'll want to synchronize that instead.
public class B {
public static String createSomeString(A a) throws Exception {
String strName = "";
synchronize (a.name) {
strName = new String(a.name);
}
return strName;
}
}
You only doing read operation in your static method, so it's thread safe no matter how much concurrent your program is. if both read and write involved, then you have to synchronize your static method or code block.
Use volatile. Please click here to know about http://javarevisited.blogspot.in/2011/06/volatile-keyword-java-example-tutorial.html
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.