users@glassfish.java.net

Re: Container injected _at_Resource fields should be declared "volatile"?

From: <glassfish_at_javadesktop.org>
Date: Fri, 16 Nov 2007 11:00:57 PST

> > Most injectable resources are actually immutable
> such
> > as javax.sql.DataSource, or javax.jms.Destination,
> > etc. So they should already be thread safe.
>
> Ummm. Isn't javax.sql.DataSource a Java *interface*?
> Are you
> saying that "instances" of its implementation class
> guaranteed
> to be immutable? Where is it specified?
>

It's an interesting topic. Let me clarify myself. My above comment was not about java interface. I meant most injected resources of these types are immutable. These objects, if standalone, are mutable. But typically in appserver environment they are managed solely by appserver. Attempt by application code to modify these resource will just be ignored. At least that is how glassfish treats DataSource and jms resources. It's not specified anywhere but I would think this is commonly expected.

> It is correct that if an interface does not have a
> mutator, you are fine with
> its state, but that's not true with any interface.
> Thus, I guess my question
> is with any injectable resource.
>
> > In EJB (bean class or interceptors), component
> > instances are not shared between threads. Web
> > components may be shared by multiple threads
>
> Aren't web components always shared by multiple
> threads?
>


Not always. In the old SingleThreadModel, instances are pooled and one instance only services one request at a time. Though deprecated, it may still be used.


> > and so
> > more care is needed with field/setter injections
> for
> > non-thread-safe resources. But I doubt if using
> > volatile would solve it. Just my 2 cents.
>
> I think I was more interested in the injection
> process itself.
> Is it guaranteed to be thread-safe or should making a
> field volatile help?

The injection process happens before a component is put into service. Only the container can access it so there is no race condition.

My understanding is, volatile is used mainly as way for inter-thread communication for shared variables. For example, a boolean flag that can be read/written by multiple threads. Injected resources are generally not suitable for this use case, and I don't think applications should actively manipulate any injected resources. Hence no need to use volatile for injected resources.

Quite to the contrary, applications need to isolate such injected non-thread-safe resources from being accessed by other threads. For example, @PersistenceContext in a servlet class, such EntityManager is best declared as a local variable.

Of course, in EJB, apps should not attempt to manage threads directly with synchronized or volatile.

Just my 2 cents.
-cheng
[Message sent by forum member 'cf126330' (cf126330)]

http://forums.java.net/jive/thread.jspa?messageID=245851