shutdown ehcache CahceManager in stateless bean - ehcache

I would like to use ehcache in stateless EJB. As I know if I get a singleton instance of CacheManager then I have to shutdown this instance when I don't need it. However it causes a big overhead for me as a lot of time is needed to create the CacheManager instance if I shutdown it at each call.
Or shouldn't I bother to shutdown the CacheManager in EJB? Won't it cause any issue?
Thanks!

Per EhCache documentation (http://ehcache.org/documentation/operations/shutdown) it's a good practice (and in some case required practice) to shutdown EhCache properly.
Either way, Should be easy to implement: I think you should register a shutdown hook for your EJB (check post EJB application shutdown hook) and in that hook, simply call the CacheManager.shutdown() method.
Hope that helps.

Related

Running Hazelcast put() and replace() calls in the calling thread

Is it possible to force Hazelcast to run put(), replace(), and delete() methods on the TransactionalMap on the calling thread? I want the XA transaction to carry over from writing to Hazelcast to writing to the database in the MapStore, but Hazelcast is queueing the changes to be run on other threads, so they aren't in the same transaction context.
I've got it set up as a write-through persistence, but I see that it's queueing the TxnSetOperation and running them on a separate thread.
This is in a Spring Boot application using the Hazelcast autoconfiguration with a JPA / Hibernate store backing to PostgreSQL.
MapStore operations don't run in the same transactional context. If you want transactional persistent updates with Hazelcast, you need to use XA transactions and not enable MapStore. Then you can set the persistent store as a different XA resource in your context. You can have a check the related section in Hazelcast's reference manual: http://docs.hazelcast.org/docs/latest/manual/html-single/index.html#providing-xa-transactions
Alsparlan's answer is partially correct, but there's no way to enlist a resource in a MapStore with the same transactional context as your actions against the Hazelcast TransactionalMap. The link he provided does NOT talk about this (unfortunately), but the Javadoc for TransactionalMap does:
When using MapStore, the call to any MapStore method is outside the transactional boundary. If you need to have an XATransaction spanning Hazelcast operations and one more other XAResources (such as a database), you should not use MapStore. Instead, enlist both resources in a transaction
I've removed my MapStore usage and wired my Spring Boot repositories directly into my services so I can make my changes to Hazelcast and my datasource in the same service methods inside the same transaction. Along with this solution to declaratively enlisting the Hazelcast XAResource this is working for me now.

Initializing tables on spring boot startup

I have a spring boot application, in which I need to initialize the tables based on some configuration. I am using managed transactions using #Transactional. My problem is that I do not know when app is ready to make DB transactions.
I created a bean which reads the configuration and updates the tables, but it gets an exception at that point:
Could not obtain transaction-synchronized Session for current thread
I have tried that if I wait sprintboot to start and make the same transactions through HTTP requests, then there is no problem. So it seems to be a timing problem. I have also tried moving the code to #PostConstruct of bean but it does not fix the issue.
How can I know that app is ready for DB transactions? Any help will be much appreciated.
You can listen on some events Spring is publishing.
See here
You properbly need to listen on this even: ContextRefreshedEvent
The simplest and cleanest way of performing the initialization should be by making your bean implement ApplicationListener for ContextRefreshedEvent and then handling the initialization in the onApplicationEvent method. This way, your initialization will run when Spring's whole application context is initialized

Why DefaultMessageListenerContainer should not use CachingConnectionFactory?

I was reading spring documentation on DefaultMessageListenerContainer
It says "Note: Don't use Spring's CachingConnectionFactory in combination with dynamic scaling. Ideally, don't use it with a message listener container at all, since it is generally preferable to let the listener container itself handle appropriate caching within its lifecycle. Also, stopping and restarting a listener container will only work with an independent, locally cached Connection - not with an externally cached one."
Could anybody explain why?
You really don't need to cache sessions for listener containers because the sessions are long lived; caching is very beneficial for frequent short use, such as with the JmsTemplate.
The problem is really when cacheConsumers = true (the default). When using dynamic scaling and a listener is stopped, the session is returned to the cache but the broker doesn't know that nobody will actually consume from that session, so you are stuck with messages sitting in the cache that won't be read until that session happens to be reused when the volume increases.
Note: if you wish a JmsTemplate running on the container thread to participate in a container transaction, you should use a CachingConnectionFactory so the producers can be cached, but you should disable caching consumers in the factory if you have variable concurrency.

how can we use addShutdownHook in project?

i saw some code use ShutdownHook like this
Runtime.getRuntime().addShutdownHook(new Thread(){
ConfigurableApplicationContext.stop();
//close spring context;
threadpool.shutdownnow();
//close theadpool
});
is there anything useful to do like this?
i thought
when jvm exit ,maybe thread will be shutdown immediately
and spring context will close tooï¼›
what shall we do next when we need to call System.exit() ?
It really depends on your application and the lifecycle of your objects and those threads you appear to have outside of your context. If you are running the spring container inside a standalone java process, then trapping the shutdown hook like this is one way to do that. Another way is to have it listen on a tcp port and send a command to begin the shutdown process. If you are running in a web container like tomcat, then you should follow the standards on normal webapp shutdown, which Spring supports with Context Listeners.
I would also consider redesigning your app so that the threads are all managed with a bean that lives inside your spring container. For instance using a bean that is configured with directives (attributes) for start/stop methods and then that bean would use an Executor for thread pooling. This way, your shutdown is ONLY shutting down the Spring container, and Spring provides very good support for orderly shutdown of beans. One of those beans is your object holding the threads within the Executor. Its a much cleaner way than trying to integrate Spring beans with external threads.
Hope this helps.

When multiple access Spring Singleton instance at same time

If you define your service in singleton scope in your spring config, what would happen if more than one user try to access it (ie as dependency injected into your controller) at the same time? Should it cause any conflict? Or the IoC container will hold the later call until the first one finish? If so it should slow down the performance in large applications, which sounds not right to me. Could any one give me a correct answer?
BTW, as I can remember, if it is not a singleton one, IoC container will pool few instances based on the number of requests. Could some one confirm it?
what would happen if more than one user try to access it (ie as dependency injected into your controller) at the same time?
A singleton bean can be accessed many times concurrently. That's why it always has to be thread-safe
Should it cause any conflict?
Only if you fail to make it thread-safe
Or the IoC container will hold the later call until the first one finish?
No, that would be awful
BTW, as I can remember, if it is not a singleton one, IoC container will pool few instances based on the number of requests. Could some one confirm it?
Spring has the following scopes (see Bean Scopes reference):
singleton (only one instance is managed per application)
prototype (a new instance for every injection)
session (one instance per HTTP session, only in Spring MVC)
request (one instance per HTTP request, only in Spring MVC)
global session (one instance per global HTTP session, only in portlet-based Spring MVC)
Also:
As of Spring 3.0, a thread scope is available, but is not registered by default. For more information, see the documentation for SimpleThreadScope.
What you describe is an Object Pool. In Spring that would be implemented as a Prototype-scoped FactoryBean. And internally it would use a library like Apache Commons / Pool.
Singletons are just that - singletons. One instance is managed by the Spring context, and all requests go through that one instance concurrently. It's up to you to make that thread-safe.
If your bean isn't thread-safe, then consider using non-singleton-scoped beans. Spring lets you use request, session and prototype scopes.

Resources