Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iBatis SqlMapClient and thread safety

Tags:

java

ibatis

I know the API state "A thread safe client for working with your SQL Maps", but I want to understand how it works a little better and was wondering if anyone was running this ina multi-threaded environment with transactions. For instance using:

void doSomeSql() throws SQLException{
  sqlMapper.startTransaction();
  sqlMapper.startBatch();
  final Map paramMap = new HashMap();
  paramMap.put("data", "data"); 
  Integer num = (Integer) sqlMapper.queryForObject("getRowCount", paramMap);//get row count
  sqlMapper.insert("insertData", paramMap); //insert row
  num = (Integer) sqlMapper.queryForObject("getRowCount", paramMap);//get row count again
  sqlMapper.executeBatch();
  sqlMapper.commitTransaction();
}

If this was used on where multiple threads can call this and there is only one shared sqlMapper object would there be some threads that are executing the batch because another thread called executeBatch()? This becomes more of an issue if I have lots of other methods doing delete's updates etc using the same sqlMapper in other threads.

I dont want start a transaction in one thread, and have another thread commit before the previous thread was done.

I understand I can synchronize on all this, but would rather not have to.

like image 772
Nick Avatar asked Jul 23 '10 14:07

Nick


2 Answers

Internally, org.ibatis.sqlmap.engine.impl.SqlMapClientImpl uses a ThreadLocal to store it's internal sessions, so even if many threads share the same SqlMapClient reference, the class uses a different internal object for each thread.

like image 60
matt b Avatar answered Sep 25 '22 19:09

matt b


Each thread will get its own DB connection, and transactions work the way you want: they're per DB connection too.

like image 41
Brian Avatar answered Sep 25 '22 19:09

Brian