我有一个看起来像这样的 HashMap -
HashMap<String, TableConnectionInfo> tableList
这意味着它的值是一个TableConnectionInfo
看起来像这样的类 -
public class TableConnectionInfo {
public String url;
public String user;
public String password;
public String driver;
public String suffix;
public String sql;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getDriver() {
return driver;
}
public void setDriver(String driver) {
this.driver = driver;
}
public String getSuffix() {
return suffix;
}
public void setSuffix(String suffix) {
this.suffix = suffix;
}
public String getSql() {
return sql;
}
public void setSql(String sql) {
this.sql = sql;
}
}
在主线程中,我通过像这样从属性文件中读取上面的地图来填充上面的地图,之后这个地图将不会被修改。
for (String arg : databaseNames) {
TableConnectionInfo ci = new TableConnectionInfo();
String url = prop.getProperty(arg + ".url");
String user = prop.getProperty(arg + ".user");
String password = prop.getProperty(arg + ".password");
String driver = prop.getProperty(arg + ".driver");
String suffix = prop.getProperty(arg + ".suffix");
String sql = prop.getProperty(arg + ".sql");
ci.setUrl(url);
ci.setDriver(driver);
ci.setPassword(password);
ci.setSql(sql);
ci.setSuffix(suffix);
ci.setUser(user);
tableList.put(arg, ci);
}
现在我将此tableList
映射传递给这样的各种线程,并且它不会被任何线程修改(通过进行集合调用)。每个线程都将使用 get 方法来获取所需的方法。
for (int i = 0; i< 1000; i++) {
service.submit(new Task(tableList));
}
下面是我的包含可运行接口的任务类
class Task implements Runnable {
private Connection[] dbConnection = null;
private CallableStatement[] callableStatement = null;
private ArrayList<Method> methods[] = null;
private final HashMap<String, TableConnectionInfo> tableLists;
public Task(HashMap<String, TableConnectionInfo> tableList) {
this.tableLists = tableList;
}
@Override
public void run() {
try {
int j = 0;
dbConnection = new Connection[tableLists.size()];
callableStatement = new CallableStatement[tableLists.size()];
methods = new ArrayList[tableLists.size()];
for (TableConnectionInfo ci : tableLists.values()) {
dbConnection[j] = getDBConnection(ci.getUrl(), ci.getUser(), ci.getPassword(), ci.getDriver());
callableStatement[j] = dbConnection[j].prepareCall(ci.getSql());
methods[j] = getRequiredMethods(ci.getSuffix());
j++;
}
}
}
}
问题:-
现在我的问题是 - 在我的运行方法中,我调用了TableConnectionInfo
类的 get 方法,所以它是否是线程安全的?由于多个线程将尝试进行 get 调用。所以我不确定我是否需要在这里做任何额外的事情?还是代码看起来不错?