【发布时间】:2010-12-07 20:08:13
【问题描述】:
假设我们正在开发实现简单 CRUD 操作以使用 DB 的类。此类还维护缓存以提高性能。
public class FooTableGateway {
Map<Integer, Foo> id2foo = new HashMap<Integer, Foo> ();
public void getFoo (int id) {
if (id2foo.containsKey (id) {
return id2foo.get (id);
}
String query = "select ...";
Connection cn = null;
Statement st = null;
ResultSet rs = null;
try {
cn = DBUtils.getConnection ();
st = cn.createStatement ();
rs = st.executeQuery (query);
if (!rs.next ()) {
return null;
}
Foo foo = new Foo (rs.getString (1)...);
id2foo.put (id, foo);
return foo;
} catch (SQLException e) {
..
} finally {
..
}
}
public boolean addFoo (Foo foo) {
if (id2foo.values ().contains (foo) {
return false;
}
String query = "insert into ...";
Connection cn = null;
Statement st = null;
ResultSet rs = null;
try {
cn = DBUtils.getConnection ();
st = cn.createStatement ();
int num = st.executeUpdate (query.toString (),
Statement.RETURN_GENERATED_KEYS);
rs = st.getGeneratedKeys ();
rs.next ();
foo.setId (rs.getInt (1);
id2foo.put (foo.getId (), foo);
return true;
} catch (SQLException e) {
..
return false;
} finally {
..
}
}
public void updateFoo (Foo foo) {
//something similar
..
}
public boolean deleteFoo (int id) {
//something similar
..
}
}
问题是:代码的哪一部分应该同步? (当然,我们正在开发网络应用程序)。
如果我将所有调用同步到缓存集合,那么我什至不确定使用缓存是否会提高性能。
【问题讨论】:
标签: java performance caching synchronization data-access-layer