开发者

IS ResultSet thread safe

Is ResultSet Thread safe?

My question arises because in my program i have used different statement for each query i have declared a ResultSet as an local variable but it gives me a error of Operation not allowed after ResultSet is closed. But my statements are working as i'm using the statements in insert and delete query.I have co开发者_运维百科mmented the ResultSet part and have not got the error !!


The real problem is that you are sharing Statement objects between multiple threads. Each time you "execute" a Statement, the previously returned ResultSet is automatically closed. In this case, the ResultSet objects "belong" to a different thread which may not yet have finished using it. Hence the exception ...

You should not share Connection, Statement / PreparedStatement or ResultSet objects between multiple threads. Each thread should acquire and release its own resources.


No, ResultSet should not be exposed to more than one thread.

A ResultSet should never have a scope larger than a single method: execute the query, map the ResultSet into an object or collection, and close the ResultSet in the same scope in which it was created.

The correct way to close a ResultSet is in a finally block in its own try/catch.

Looked at the code in your other question. It needs a serious, complete refactoring. It's not surprising that you're having problems with it. Here are a few suggestions:

  1. Follow the Sun Java coding conventions. It might seem trivial, but anything that makes your code harder to read is a bad idea. Your "doComms" and "savetodatabase" classes break the "class names start with a capital letter" convention.
  2. Naming matters. "doComms" is not my idea of a good abstraction.
  3. Magic numbers/constants are everywhere. They'll make your code harder to change later.
  4. Java's an object-oriented language; you're writing in another style altogether. When I see "insert studentinfo", it makes me wonder where the Student class is.
  5. Your JDBC code doesn't handle resources properly at all.

Just curious - are you trying to learn how to write a server? Is there a reason why you wouldn't use a servlet engine as the basis for this app? Sockets are a very low level place to start to solve a problem like this.


The few times I've written hand-coded JDBC, it's been both ugly and error prone. Of course, that could just be me, but you may have much better results with using the Spring JDBC data access classes. You don't have to use the whole spring container, just a DataSource and a spring's JdbcTemplate class.

It enforces a usage pattern to JDBC that is both thread-safe and resource-safe.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜