Question

I pasted my code below. In our application they set the transaction in thread local.
Actually my doubt is why do we need this?
What could happen if we didn't set the tranaction in threadlocal?

public void beginTransaction() {

    final String METHOD_NAME = "beginTransaction";
    log.entering(CLASS_NAME, METHOD_NAME);

    PcUtilLogging.logTransactionLifecycle("Begin Transaction",
            this.persistenceConfigurationKey);

    // Initialize.
    final PcRequestContext context = PcRequestContext.getInstance();
    final PersistenceManager pm =
            context.getPersistenceManager(this.persistenceConfigurationKey);

    try {
        // Begin a new transaction.
        final Transaction transaction = pm.newTransaction();

        // Set the Transaction in ThreadLocal.
        context.setTransaction(this.persistenceConfigurationKey,
                transaction);

    } catch (final Exception e) {

        // Throw.
        throw new PcTransactionException(
                new ApplicationExceptionAttributes.Builder(CLASS_NAME, METHOD_NAME).build(),
                "Error encountered while attempting to begin a ["
                        + this.getPersistenceConfigurationKey()
                        + "] transaction.", e);
    }

    log.exiting(CLASS_NAME, METHOD_NAME);
    return;
}
Was it helpful?

Solution

The problem is that one wants to access the transaction from different parts of your application (different DAOs for example), so it's usually done in this way to avoid having to pass the transaction object around the application (and leaking persistence logic into your app).

Also, transactions are usually related to the thread that takes a request (or jms message), so a ThreadLocal is a convenient place to put it. Most frameworks do this (Spring as an example).

If you don't set the transaction on a thread local two things can happen

  • Each DB access needs to use a different transaction.
  • All the transactions are mixed up, as a commit on one request, affects the changes on a different thread.

Do you see any better way of doing this Adala?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top