Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ThreadLocal safety in Weblogic threadpool

I'm writing an app which uses MDBs, EJBs and needs ThreadLocal to pass and log a variable across multiple EJBs and Helper classes until the transaction is complete.

The flow is

Starting with MDB onMessage() -> some business delegate EJBs -> some helpers

Question:

This app runs within Weblogic and Weblogic re-uses Threads from within it's ThreadPool. So is there a possibility of data corruption across threads? Is the solution to use ThreadLocal.remove() safe enough?

Is there an alternative to ThreadLocal other than passing around the Object as a parameter to all methods?

like image 754
JoseK Avatar asked Dec 17 '22 10:12

JoseK


2 Answers

WebLogic does not reset user set ThreadLocal variables when the thread is returned back to the pool - the user is responsible for managing them. When such threads are reused, its likely they will interfere. You may run into memory leaks since the thread local reference isn't cleaned up. You can safely reset your thread locals prior to returning the thread back to the container. The ThreadLocal.remove() call should clean it up (ensure that its done in a finally block)

Note that if any async or rmi calls are involved, your thread locals will not propagate. You may want to consider the WebLogic WorkArea feature which allows context propagation across threads, clients & servers. More details can be found at http://download.oracle.com/docs/cd/E17904_01/web.1111/e13706/context.htm#i1058690

like image 178
prash Avatar answered Dec 29 '22 01:12

prash


You can't reliably use a ThreadLocal in the EJB tier. Even if your code seems to 'work' now, what happens if someone deploys one of your beans remotely? From EJB Restrictions:

Why is thread creation and management disallowed?

The EJB specification assigns to the EJB container the responsibility for managing threads. Allowing enterprise bean instances to create and manage threads would interfere with the container's ability to control its components' lifecycle. Thread management is not a business function, it is an implementation detail, and is typically complicated and platform-specific. Letting the container manage threads relieves the enterprise bean developer of dealing with threading issues. Multithreaded applications are still possible, but control of multithreading is located in the container, not in the enterprise bean.

If you need to share state, you should pass it in to the EJB method as a parameter. Is there a reason this approach won't work for you? Another option would be to temporarily dump it into a transaction enlisted database or cache.

like image 45
jonathan.cone Avatar answered Dec 29 '22 00:12

jonathan.cone