JBoss 6: timer starts when application is not fully deployed - dependency-injection

I have a problem at deploy time in JBoss 6.
My application contains a Stateless EJB with one method marked with the #Schedule(hour="1") annotation. Such a method uses another Stateless EJB injected by #EJB annotation.
#Stateless
public class AuditRecordCleanerBean implements AuditRecordCleanerLocal
{
#EJB
private RecordManager recordManager;
#Schedule(hour="1")
public void moveRecordsToHistoricTable()
{
recordManager.moveRecords();
...
}
}
Because the timer is persistent in JBoss, when I reboot the application server it can sometimes happen that the timer triggers when the EJB RecordManager is not yet deployed causing a NameNotFoundException.
In server.log I found the following warning:
WARN [org.jboss.ejb3.TimerServiceContainer] (Thread-2) EJBTHREE-2193: using deprecated TimerServiceFactory for restoring timers
Could be this the problem?
How can I delay the first timer execution after the complete deploy of the application?
Best regards,
Fabio

Related

Stress Testing - EntityFramework issue - DBContext Creation

I am doing stress testing for web api (webapi2) with 20 users on boarding in 0 seconds. I am getting the following errors.
System.Data.Entity.Core.EntityCommandExecutionException: An error occurred while executing the command definition. See the inner exception for details. ---> System.InvalidOperationException: Invalid operation. The connection is closed.
Another error
System.Data.Entity.Core.EntityException: The underlying provider failed on Open. ---> System.InvalidOperationException: The connection was not closed. The connection's current state is connecting.
My code to get the DBContext, each time a new DBContext is getting created:
public static ForcesChecker_Context GetDataContext()
{
return new ForcesChecker_Context();
}
For one web api request this code is getting executed multiple times and multiple instances of this object is getting created. When I call 20 users at a time, it generates 20* ~10 = ~200 objects are created.
My connection string:
Min Pool Size=1;Max Pool Size=200;
It seems there is a race condition.
What settings would help to allow more users to access my system concurrently?
I fixed it. The reason was, Connection Leak. There are other places in the application wherein the DBContext object wasn't disposed properly. Particularly in UnitOfWork class, DBContext object is used, but not disposed inside the Dispose() method. That led to the connection leak. Subsequently, that led to the race condition when new threads (http requests) try to use a connection from the connection pool. Here is the solution code.
public class UnitOfWork: IDisposable, IUnitOfWork
{
ForcesChecker_Context forcesContext; //EntityFramework DBContext
...
public void Dispose()
{
forcesContext.Dispose(); //Leak prevented by this new line.
}
...
}
Thumb rule is, always remember to use Transient Life Time for the DBContext. That is a new instance every time, and dispose them immediately after use.

How to keep .NET Core console app alive in Docker container

I am testing a .NET Core 2.0 app which uses the Service Bus SDK to retrieve messages from an Event Hub. I setup a console app to do that, and intend to run the app as a Docker container.
This method creates the Event Host Processor which will read the messages:
private static async Task MainAsync(string[] args)
{
Console.WriteLine("Registering EventProcessor...");
var eventProcessorHost = new EventProcessorHost(
EhEntityPath,
PartitionReceiver.DefaultConsumerGroupName,
EhConnectionString,
StorageConnectionString,
StorageContainerName);
// Registers the Event Processor Host and starts receiving messages
Console.WriteLine("Retrieving messages");
await eventProcessorHost.RegisterEventProcessorAsync<EventProcessor>();
Console.WriteLine("Sleeping");
Thread.Sleep(Timeout.Infinite);
}
As the event processor implemented in class EventProcessor will be the one handling the events, I am trying to prevent the console app to exit when the registration of the Processor is finished.
However, I can't find a reliable way to keep the app alive. If I run this container as-is, all I see in the output window is:
Registering EventProcessor...
Retrieving messages
Sleeping
and no messages are ever received.
Thanks all for the suggestions.
I followed those articles but eventually ended up with this, which applies specifically to .NET Core apps:
https://github.com/aspnet/Hosting/issues/870
I've tested it and the app can shutdown gracefully when it receives a termination signal from the Docker runtime.
UPDATE: this is the relevant sample from the GH issue link above:
public class Program
{
public static void Main(string[] args)
{
var ended = new ManualResetEventSlim();
var starting = new ManualResetEventSlim();
AssemblyLoadContext.Default.Unloading += ctx =>
{
System.Console.WriteLine("Unloding fired");
starting.Set();
System.Console.WriteLine("Waiting for completion");
ended.Wait();
};
System.Console.WriteLine("Waiting for signals");
starting.Wait();
System.Console.WriteLine("Received signal gracefully shutting down");
Thread.Sleep(5000);
ended.Set();
}
}

Do I really need to dispose IUnityContainer on shutdown of application

I'm maintaining code for a web application built using Asp.NET MVC. An MVC dependency resolver has been implemented using Unity container. Here's the cleanup code that's called on application shutdown.
public static void Shutdown()
{
IUnityContainer container = UnityConfig.GetConfiguredContainer();
container.Dispose(); //currently when called causes stack overflow
}
The issue we're having is that during a shutdown the call to dispose (above) causes a stack overflow exception and then the process crashes because of it. This also occurs during development when debugging the app and making changes to web.config (since changes to web.config seems to restart the application) which also stops the debugging session which normally shouldn't end. No stack overflow seems to occur if I remove the call to dispose, and the application then exits or restarts normally without the process crashing during debugging sessions.
I'm thinking of simply permanently removing the call to Dispose but I'm uncertain of the consequences, wouldn't an application shut down inevitably lead to the disposing of the container anyway?
If removing the call to dispose is not recommended then the only option would be to find the real cause which I believe lie in a circular dependency within the container itself, but I can't find it, how should I debug this issue ?
The cause of the stackoverflow is infinite recursive call to Dispose of UnityContainer, which I think is (weirdly) caused by the automatically registered IUnityContainer which is not managed by our code and should be handled in unity library. I was able to stop the infinite recursion simply by swapping out the usage of the UnityContainer class with a derived class that override Dispose and returns on a recursive call:
public class CustomUnityContainer : UnityContainer
{
private bool inDispose = false;
protected override void Dispose(bool disposing)
{
if (inDispose) //prevents recursive calls into Dispose
return;
inDispose = true;
base.Dispose(disposing);
inDispose = false;
}
}

How do I fix a Thread Leak in a JSF application?

I have an ApplicationScoped bean that fires up a separate Thread to do some background work. The Thread has a method for cleanly terminating it called terminate(). If not terminated via that method it runs in an infinite loop, and sleeps for a while if it finds it has nothing to do.
The thing is I am in development mode (Netbeans -> Maven) and each time I recompile the application, the Maven plug-in un-deploys and redeploys the application (most conveniently I must say) but the background Thread from the last deployment hangs around. It eventually terminates with an Exception because it wakes up from its sleep and tries to access a JPA EntityManager that isn't there anymore.
I would prefer to automatically call the terminate() method when the application is stopped. Is there some way to implement a listener that will do that at the JSF 2.0 specification level? If not, how about at the Servlet level?
This is using GlassFish 3.1.1.
Add a #PreDestroy method to you bean which will run when your application is undeployed or stopped and it can stop the background thread, like this:
import javax.annotation.PreDestroy;
import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;
#ApplicationScoped
#ManagedBean
public class AppBean {
public AppBean() {
System.out.println("new AppBean()");
}
#PreDestroy
public void preDestory() {
// call thread.terminate() here
System.out.println("preDestory");
}
}

Unity not resolving registered dependency.. even though it really is registered

This is driving me nuts...
Two assemblies/projects in play:
An Infrastructure project, which has an interface in it:
IDtoMapping<in TDto, out TDomain>
And an app project, referencing Infx, with an implementation:
PatientMapping : IPatientMapping
...and a marker interface, just to be clear:
public interface IPatientMapping : IDtoMapping<PatientDTO, Patient> {}
When the app boots, this gets run:
_container.RegisterType<IPatientMapping, PatientMapping> ( new ContainerControlledLifetimeManager () );
This happens in the app project, through a system-wide bootstrapping process.
(Immediately after this line runs, (through a watch), I can successfully resolve it.)
Finally, we try to resolve it (in a WCF service, in the app projec)
public PatientService (
IPatientRepository patientRepository,
ISessionSource session,
IPatientMapping patientDtoToDomainMapper )
{
.. and it fails. With the ResolutionFailedException "Cannot instantiate an interface, etc.." I've put break points at the .Resolve call, the registration, etc.. everything is getting hit as expected. But when the app tries to Resolve/BuildUp the WCF Service, Unity can't resolve the IPatientMapping parameter... it's like it forgot.
I'm at a loss.. I upgraded to Unity 2.0, added that intermediate marker interface, removed the generic interface and just used the vanilla one.. all to no avail.
Other dependencies in the system resolve just fine, including the other parameters on that same WCF constructor.
The only thing my gut is telling me is could it have something to do with the assemblies? That the .Resolve call is happening in the Infx project, but the implementation actually lives in the app-project? At runtime, all assemblies are loaded, so it shouldn't really matter, right?
Thanks for any ideas!

Resources