Autowiring Spring Services on Construction of Object - multithreading

Is there a way I can have Spring inject dependencies on construction of an object at runtime, rather than when parsing the Spring XML files or on package-scan?
I've got some objects that extend Thread and do file transfers. It be nice to have the services these Thread sublasses depend on autowired, so I don't have to pass them all in the constructor.
BONUS QUESTION!
Is there anything I need to do with these Thread subclasses once they've done their run() implementation has finished? Do they need 'killing' somehow?

I'd use the Spring injection facilities as is. You can inject a ThreadPoolTaskExecutor and let your objects use that. No Threads will be killed or harmed by your application: Spring will manage them all.

Related

does a reader for spring batch have to be an injected bean?

The transaction model in Spring batch is not so easy to understand, therefore I wonder where spring batch really needs to have proxies to fulfill all its work.
So does Spring need to create proxies around Readers, Writers, Processors and Steps and therefore I have to inject them as beans? or is it OK to no use injection for them?
Spring only uses proxies within batch when you're using step scope. Otherwise, the beans are created and injected. With regards to not using injection for them, you can take that approach but there is a lot going on under the covers that you'd need to handle yourself so it's not recommended.

Spring Hibernate SessionFactory.getCurrentSession in multithreaded environment

I have written a batch application which spawns multiple threads to read assigned files and save records to database. The architecture uses Spring context and Hibernate.
Transaction is managed by Spring and I am using SessionFactory.getCurrentSession to get a session to perform a save operation for each thread.
Consider that I have a generic DAO that handles get, save, update operations and a facade to hide Hibernate implementation, how can I be assured that two threads when invoking SessionFactory.getCurrentSession() are getting their dedicated Session object to perform DB operations.
I found a post in StackOverflow where someone recommended not to use current_session_context_class=thread when using spring managed transaction. what is the default implementation used by Spring for current_session_context_class property?
Thanks in Advance!
As of Spring 2.0 Spring integrates with hibernate throuhg its own implementation(s) of the CurrentSessionContext interface provided by hibernate.
By default spring sets this to the SpringSessionContext to integrate properly. In general you don't want or need to mess with the current_session_context_class unless you are using JTA (although when using Hibernate 4 with a recent Spring version it should also just work).

EJB 3.1 Singleton + JPA + JSF design advice needed

Given: simple JSF webapp (no Seam), having JSF beans calling few EJB's which in turn load and persist JPA entities. What I want to is to use #Singleton annotation for ejb's and inject EntityManager instead of EntityManagerFactory:
#Singleton
public class MyEJB {
#PersistenceContext(unitName = PERSISTENCE_UNIT_NAME)
protected EntityManager em; // not EntityManagerFactory
}
Spec says that #Singleton is thread-safe, supports concurrency and transaction attributes which (from my pov) makes it safe for calling from JSF beans. I expect also performance benefits because of EntityManager not being recreated for each call and it's internal caching abilities.
My main concern here is create/update operations on JPA entities in the situation when I have several singletons and, as a result, the same count of long-living EntityManagers.
What happens if one singleton updates an JPA instance and how these
changes are populated to other singletons?
As I'm not able to close entity manager, do I need to flush it upon
each entity update?
Would it be better if these few singletons will share the same entity
manager?
I saw only few examples of such design. Why? Are there any serious
drawbacks?
Many thanks in advance!
I expect also performance benefits because of EntityManager not being recreated for each call and it's internal caching abilities.
You might save some memory using singletons, but using it everywhere in your app could make it actually slower, because as there's only one EJB to serve all the concurrent requests by various users of your app, the container locks access to the EJB and when it's busy serving a request it cannot be serving another request. However this can be alleviated to some degree using lock types (i.e. #Lock(WRITE) and #Lock(READ)).
Singletons are useful for times when you want to execute a piece of code periodically using EJB timers, or to update a cache periodically, etc.
What happens if one singleton updates an JPA instance and how these changes are populated to other singletons?
Shouldn't be any different to the way non-singleton EJBs behave.
As I'm not able to close entity manager, do I need to flush it upon each entity update?
If you use CMT, no. At the end of each transaction everything will be flushed automatically.
Would it be better if these few singletons will share the same entity manager?
Looks like premature optimization to me. Just let the container inject the EM for you.
I saw only few examples of such design. Why? Are there any serious drawbacks?
Already explained.
There is one thing I want to mention regarding changing LockType of Singleton EJBs. While in general it sounds like a good idea, you should remember that resources such as EntityManger are NOT thread-safe, so appropriate concurrent access control should be provided. You can annotate methods that access non-thread-safe resources with #Lock(WRITE), but if almost all interface methods of your Singleton EJB access such resources, you will have almost the same situation as with fully write locked one. Alternative is to use Bean Concurrency Management with manual fine-grained synchronization, but it's also questionable decision.
Because of this in general I prefer Stateless EJBs over Singleton and use latter in specific cases.

Are Message-Driven Beans (MDB) bound to the same restrictions as other EJB beans?

In a Message-Driven Bean am I restricted to the same rules of Session Beans (EJB3 or EJB3.1), i.e:
use the java.lang.reflect Java Reflection API to access information unavailable by way of the security rules of the Java runtime environment
read or write nonfinal static fields
use this to refer to the instance in a method parameter or result
access packages (and classes) that are otherwise made unavailable by the rules of Java programming language
define a class in a package
use the java.awt package to create a user interface
create or modify class loaders and security managers
redirect input, output, and error streams
obtain security policy information for a code source
access or modify the security configuration objects
create or manage threads
use thread synchronization primitives to synchronize access with other enterprise bean instances
stop the Java virtual machine
load a native library
listen on, accept connections on, or multicast from a network socket
change socket factories in java.net.Socket or java.net.ServerSocket, or change the stream handler factory of java.net.URL.
directly read or write a file descriptor
create, modify, or delete files in the filesystem
use the subclass and object substitution features of the Java serialization protocol
It is always a good idea not to create threads manually (ExecutorService seems fine in some cases though).
Actually MDBs are very often used to address this limitation: instead of creating a separate thread, send some task object (put something like MyJob extends Serializable in ObjectMessage) into the queue and let it be executed in MDB thread pool. This approach is much more heavyweight but scales very well and you don't have to manage any threads manually. In this scenario JMS is just a fancy way of running jobs asynchronously.
These EJB restrictions are typically not hard restrictions. In fact, they're not caveats on making your EJBs work properly, they're more like advisories on how to make your EJBs portable across EJB containers.
From time to time, some very fussy EJB container providers (cough.... WebSphere... cough) will actually enforce these restrictions through java security policies, but I would say about half of those restrictions are routinely ignored ( I mean just using log4j in your MDB potentially violates about 30% of them).
Violating the the other 70% probably indicates some architectural or design problem.
So, can you call System.exit() in an MDB ? The answer is yes, but only once... :)
It sounds like, in your case, you need some of these restrictions to reign in potentially misbehaving plugins. I don't know if MDBs are going to get you out of that problem. I suppose it depends on how much you trust the third party developers, but rather than use the invocation based models in EJB, I would install the components as JMX ModelMBeans. You can use the java security model to limit what they can do, but I suppose that would defeat the purpose.
Perhaps using some run (or load) time AOP byte code engineering, you could rewrite all requests for threads to be redirected to a per component thread factory that you allocate and limits the threads that can be created. Because you don't want to stop them from doing whatever it is that they do, you just don't want them to take down the whole server when they crash/stall/misbehave.
Interesting problem.

Are multiple DAOs with jdbctemplate constructor injection a multi-threading risk?

I've got a large multi-threaded webapp in which I am passing in jdbcTemplates into DAO classes via constructor injection. Is this a multi-threading risk? Should I be passing in just the datasource instead?
Spring IOC runs in only 1 thread on start up so threading issues are not an issue there. Spring will not publish the DAO as a bean (to be retrieved from elsewhere) until it is completely constructed.
There is no risk of multithreading, you can safely pass jdbcTemplate into DAO classes.
In every query execution method, it essentially talks to the injected datasource and does not use any state which could lead to any side effect.

Resources