Results 1 to 2 of 2

Thread: AbstractRoutingDataSource and Potential Thread safety issue

  1. #1
    Join Date
    Dec 2009
    Posts
    2

    Default AbstractRoutingDataSource and Potential Thread safety issue

    Since the EntityManagerFactory is shared across EntityManagers, if you are calling setDataSource() on the EMF, then you could have a potential threading issue. The scenario below explains it.

    Thread 1 --> Begin transaction 1

    Thread 2 --> Begin transaction 2

    Thread 1 --> emf.setDataSource(Client1)

    Thread 2 --> emf.setDataSource(Client2)

    Thread 2 --> em2.persist(entity2)

    Thread 2 --> Commit transaction 2

    Thread 1 --> em1.persist(entity1) // Remember, the last set datasource was client 2 datasource set on EMF by thread 2.

    Thread 1 --> Commit transaction 1 // Will this not try to save the data through datasource of client 2.

    Be sure entity1 is persisted to Client1 (and not Client2) datasource !!

    Is the above understanding clear and sane? Do we not see a potential issue as I anticipate.

    Any help will be appreciated.

  2. #2
    Join Date
    Jan 2005
    Location
    Bucharest, Romania
    Posts
    5,403

    Default

    The general rule is that FactoryBeans (and the other stateful classes in the framework) are setup once during initialization and then untouched. Just like the JdbcTemplate for example, this guarantees thread-safety without creating all sorts of defensive barriers to prevent the user from making 'mistakes'.
    As you've described yourself, changing a shared state between multiple threads will cause problem. Spring doesn't prevent you from doing that since the assumption is that you know what you are doing.
    Note that there are valid cases for doing what you've done though these are rare (for example working transparently across multiple JPA providers).
    Costin Leau
    SpringSource - http://www.SpringSource.com- Spring Training, Consulting, and Support - "From the Source"
    http://twitter.com/costinl
    Please use [ c o d e ] [ / c o d e ] tags

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •