Please, look at the classes below and tell me if the code below is thread safe. The point of my question is that one class whose static
method and that method calls singleton instance's method. Also, the static
method is invoked by Runnable
instance. So I am asking you guys to see the codes - static
method and it calls singleton's method in multi thread environment - is safe?
I will really appreciate if you answer my question.
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
public class SingletonCls {
private static SingletonCls singletonInstance = null;
private SingletonCls() {
}
public static SingletonCls getIntance() {
if (SingletonCls.singletonInstance == null) {
singletonInstance = new SingletonCls();
}
return SingletonCls.singletonInstance;
}
public List<Map<String, String>> call(String id) throws Exception {
List<Map<String, String>> list = new ArrayList<Map<String, String>>();
BufferedReader br = null;
final String col = "col";
try {
br = new BufferedReader(new FileReader("test.txt"));
String lineStr = null;
while ((lineStr = br.readLine()) != null) {
StringTokenizer st = new StringTokenizer(lineStr, ",");
int colIdx = 1;
if (lineStr.startsWith(id)) {
Map<String, String> map = new HashMap<String, String>();
while (st.hasMoreTokens()) {
String value = st.nextToken();
map.put(col + (colIdx++), value);
}
list.add(map);
}
}
} finally {
if (br != null) {
br.close();
}
}
return list;
}
}
import java.io.IOException;
import java.util.List;
import java.util.Map;
public class TestSingleTonCaller {
public static List<Map<String, String>> getData(String id) throws Exception {
List<Map<String, String>> list = SingletonCls.getIntance().call(id);
return list;
}
}
import java.io.IOException;
import java.util.List;
import java.util.Map;
public class RunnableSingleTonExe implements Runnable {
private final String id;
public RunnableSingleTonExe(String inId) {
this.id = inId;
}
public void run() {
try {
List<Map<String, String>> list = TestSingleTonCaller
.getData(this.id);
System.out.println("thread id:" + this.id + " list > "
+ (list == null ? "" : list.toString()));
} catch (IOException e) {
Thread.currentThread().interrupt();
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}