Should I bind JDBC connection to servlet thread? - servlets

I'm using jndi to access to dbcp datasource.
In scope of one servlet request each time call static_dataSource.getConnection() returns new connection.
In hibernate there is a function getCurrentSession(). As far as I understand this function return connection that binded to current thread. Should I bind my jdbc connection to thread also?
My goal is call complex business logic in scope of one transaction that contains many DAO calls, per one http request. Like in Spring I can annotate whole service class with #Transactional.

I'd recommend that you not bind a JDBC connection to a thread. Use a connection pool and hang onto the connection for the shortest time possible: acquire from pool, perform operation, close the connection, return to pool.
Your persistence code ought to be completely separate from the web tier. You should be able to test and use it independent of the web tier. Anything that you do to tie the two together will diminish the effectiveness of the persistence tier.

Related

Instantiating multiple instance of Microsoft.Azure.ServiceBus.QueueClient in .NET Core

I'm looking for the best practices for creating multiple Microsoft.Azure.ServiceBus.QueueClient instances in .Net Core using Dependency Injection. Should instances be singleton, for example? I couldn't find any official guidance on this.
Currently I am resolving one instance as a singleton, but a new requirement has necessitated that I instantiate multiple QueueClient instances for different queues using the same connection string.
The concern is connection pooling and lifetime, and how this is/should be managed. I've found mentions of MessagingFactory in .NET Framework, but not much info about the equivalent (if any) in .NET Core.
.NET Framework version of the client was using MessagingFactoring as a mechanism for connection pooling. Each client created using the same factory would re-use the same connection object.
With .NET Standard client this is no longer the case. You get to choose wherever you want to pool the connection or not. If you construct all of your queue clients using a connection string, you will create new connections each time. It's both costly and requires resources. If you construct your queue clients using the same ServiceBusConnection object, then you'll re-use the same connection and will not pay the cost of re-establishing a connection each time.
Note that whenever you reuse the object, you need to verify that the underlying connection is still opened. If it's not, you will need to create a new one by specifying the connection string or instantiating a new connection object using the connection string you have.

Does method jdbcSession() in AppServiceHub create a fresh session each time it is called?

Our code uses a custom CordaService that maintains state in a database table. To query/update the table, the service uses a JDBC Connection object obtained by calling AppServiceHub.jdbcSession().
It is not clear from the documentation if this call creates a fresh (not-in-use) JDBC Connection object or if it returns the same Connection to all callers. Since our Corda service exposes methods to flows that execute concurrently, this matters.
The documentation
states that the method
Exposes a JDBC connection (session) object using the currently configured database.
and that the method
Returns a new Connection
The second statement suggests that we should get a fresh Connection on each call, but in reality concurrent calls appear to return the same Connection object.
Can someone clarify what the intended and actual behaviors for this method are?
The second statement is incorrect. The jdbcSession method does not always return a fresh connection object. See https://github.com/corda/corda/issues/4498 (now fixed).
Instead:
The node creates a pool of connections at start-up
If one of these connections breaks, the node adds a new one to the pool
When a flow starts/is restored from a checkpoint, the node gives the flow a connection from this pool
It is possible, but not guaranteed, that by chance a flow will be handed the same connection across multiple suspend/restores
When a flow suspends/ends, the node returns the flow's connection to the pool

Does #Asynchronous in EJB 3.1 closes/releses the connection when the Async method is completed

In the EJB 3.1, we have annotated a method with #Asynchronous and using Future.get to fetch the results.
Question is when we do future.get(), does the database connections from the connection pool and resources are released which was being used in that async method?
Database connections are closed according to your configured connection pooling policy of the used application server.
When talking about session beans and container managed transactions, the connection is returned at the end to the transaction scope of the called business method.
Since session beans with #Asynchronous annotations do not support transaction propagation (e.g. see EJB 3.2 spec 4.5.3), a new transaction is created with every call to a business method if the method is configured with REQUIRED or REQUIRES_NEW. Thus, this transaction scope ends with the called business method returning.
There is a chance they are :) Otherwise using #Asynchronous would quickly lead to application crash due to lack of resources...
Anyway as resources are stored using Thread Local storage in Java-ee and as #Asynchronous defer the execution to a dedicated thread, the resources used there (including JCA Connection - and so database one) are also dedicated to the #Asynchronous method execution (not inherited from the caller thread).

Can two parallel WCF requests get handled by the same thread when ConcurrencyMode = Multiple

I have a WCF service with ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple). I want to use ThreadStatic variable to srore data.
I start worrying about is it possible two parallel requests for the same or different operationContracts get handled by the same thread serverside, because if this happens my ThreadStatic variable will get overriden.(I.e. something like the thread changing between HttpHandlers and HttpModules in ASP.NET)
I made a spike service with the same ServiceBehaviour and maxConcurrentCalls="2". After that a wcf client called the service with 50 parallel requests and my worry did not occur. However this is not a 100% proof.
Thank in advance!
Irrespective of the ConcurrencyMode, a ThreadStatic value will persist when your request terminates and the thread is returned to the thread pool. The same thread can be reused for a subsequent request, which will therefore be able to see your ThreadStatic value.
Obviously this won't be true for two concurrent requests, because by definition they will be executed on different threads.
From comments:
Also by definition MSDN says: 'The service instance is multi-threaded. No synchronization guarantees are made. Because other threads can change your service object at any time, you must handle synchronization and state consistency at all times.' So it is not so obvious:)
This means that a single instance of your service class can be accessed concurrently by multiple requests. So you would need to handle synchronization for any accesses to instance members of the service class.
However ThreadStatic members are by definition only used by one thread (and hence one request) at a time, so don't need synchronization.
The direct answer to your question is Joe's answer.
However you mention in the comments you are using an ambient design pattern. That pattern is already implemented in WCF as the OperationContext and is specifically designed to be extensible. I highly recommend using OperationContext over any custom thread storage.
See Where to store data for current WCF call? Is ThreadStatic safe?
I wanted to add to Joe's answer here because I would recommend that you use some sort of correlation for your requests if you're needing to store state. The threading model will become very convoluted and unreliable in production.
Further, now imagine you have two IIS servers hosting this service and a hardware or software load balancer forward facing so that you can consume it. To ensure that the correct state is gathered you'll need correlation because you never know which server the service will be started on. In the post below I mocked up a simplified version of how that might work. One thing to keep in mind is that the SessionState would need to be kept in a shared location to all instances of the service, an AppFabric Cache server for example.
Global Variable between two WCF Methods

Communication between EJB3 Instances (Java EE inter-bean communication) possible?

I'm designing a part of a Java EE 6 application, consisting of EJB3 beans. Part of the requirements are multiple parallel (say a few hundred) long running (over days) database hunts. Individual hunts have different search parameters (start time, end time, query filter). Parameters may get changed over time.
Currently I'm thinking of the following:
SearchController (Stateless Session Bean) formulates a set of search parameters, sends it off to a SearchListener via JMS
SearchListener (Message Driven Bean) receives search parameters, instantiates a SearchWorker with the parameters
SearchWorker (SLSB) hunts repeatedly through the database; when it finds something, the result is sent off via JMS, and the search continues; when the given 'end-time' has reached, it ends
What I'm wondering now:
Is there a problem, with EJB3 instances running for days? (Other than that I need to be able to deal with container restarts...)
How do I know how many and which EJB instances of SearchWorker are currently running?
Is it possible to communicate with them individually (similar to sending a System V signal to a unix process), e.g. to send new parameters, to end an instance, etc..
If you're holding a huge ResultSet open for an extended period of time, you're likely to encounter either transaction timeouts or database locking issues.
There is no builtin mechanism for determining which bean instances are running in a method, so you would need to add your own mechanism. Your product might have some kind of performance monitoring that lets you know how many of each type of bean is currently running a method.
As for cross-thread communication, you would need to implement your own synchronization and periodically check in the bean method. You'll be outside the scope of standard EJB since each parallel call to a business method will allocate a new SLSB from the pool.

Resources