transactions icon indicating copy to clipboard operation
transactions copied to clipboard

shortcut for new InitialContext() blah blah blah

Open gavinking opened this issue 8 months ago • 9 comments

According to the specification, this is still—after 25 years of us knowing better—the usual way to obtain the current UserTransaction:

try {
    var userTransaction = 
            (UserTransaction) 
                    new InitialContext()
                            .lookup("java:comp/UserTransaction")
}
catch (NamingException ne) {
    throw new RuntimeException(ne);
}

This code is absurdly verbose, lacks type-safety, and throws checked exceptions I have no idea what to do with. If I were to set about to deliberately design an API that's as hostile as possible to users, I would be hard-put to come up with something worse.

Now, fortunately, if the programmer is lucky enough to have CDI, they can inject the UserTransaction or use:

CDI.current().select(UserTransaction.class).get()

Which is much more sensible.

But this is also all quite silly. The UserTransaction object is bound to the current thread, and there's never more than one of it. We really don't need all the fancy CDI machinery for such a task.

I propose adding the following static method or something like it to UserTransaction (or to TransactionController, see #228):

    /**
     * Obtain an instance representing the active transaction associated
     * with the current thread.
     * 
     * @throws IllegalStateException if there is no instance available
     */
    static TransactionController get() {
        try {
            return (UserTransaction)
                    new InitialContext()
                            .lookup("java:comp/UserTransaction");
        }
        catch (NamingException e) {
            throw new IllegalStateException(e);
        }
    }

So that the programmer can write:

var userTransaction = UserTransaction.get();

[In light of issue #209 I would add similar get() methods to Transaction and to TransactionSynchronizationRegistry.]

gavinking avatar May 04 '25 16:05 gavinking