Announcement Announcement Module
Collapse
No announcement yet.
Sample code is multi-thread safe? Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Sample code is multi-thread safe?

    Hi,

    Taking a look to the sample code of section 10.2.5 of the reference documentation (Data Access using JDBC) I am left wondering whether it is multi-thread safe, since several methods share the same JdbcTemplate member variable.

    Regards,
    F.

  • #2
    A JdbcTemplate is threadsafe.

    Comment


    • #3
      Sample code is multi-thread safe?

      Rod,

      Yes I know you mention JdbcTemplate is thread-safe in both documentation and your books (at least the first one, I recently bought the second one but still waiting for delivery, so don't know for sure).

      I've read the source code of JdbcTemplate and now I think I understand why the sample code is thread safe. However I still feel like the sample code is a little bit misguiding for beginners. For instance, consider how such a programmer could "extend" the code:

      Code:
      public int getCount() {
          jt = new JdbcTemplate(dataSource);
          jt.setFetchSize(1);
          int count = jt.queryForInt("select count(*) from mytable");
          return count;
      }
      
      public List getList() {
          jt = new JdbcTemplate(dataSource);
          jt.setFetchSize(1000);
          List rows = jt.queryForList("select * from mytable");
          return rows;
      }
      Now the above code may still function but there would be no guarantees as to what fetch size will be used in queryForInt() and queryForList() in a multi-threaded scenario.

      Since changing the above code to use:
      Code:
          JdbcTemplate jt = new JdbcTemplate(dataSource);
          ...
      would solve the issue, my question is what does it buy to have jt as a member variable? Please forgive if I am clueless. I am just trying to understand.

      Thank you in advance,
      F.

      Comment


      • #4
        Well, the cheap answer is that the fetch size should not be set after initial construction and configuration of the jdbcTemplate, if the template is going to be shared... The fetch size would be configured a deployment setting, something set in the application context.

        At this point it is quite valid to construct a new JdbcTemplate for each use (feeding it a DataSource). It used to be that a lookup of database type and error codes would be done on each construction, a somewhat expensive process, but this information is now cached.

        So you can use either approach...

        Regards,

        Comment


        • #5
          Thanks

          Thank you very much guys, now it is clear .

          It is interesting to see how some framework usage idioms develop.

          F.

          Comment

          Working...
          X