Project Reactor Schedulers on field level or chain level - spring-webflux

I saw that when schedulers are extracted to field or bean in Spring then Intellij suggest that is a blocking call in non-blocking scope. I know that but when I put Scheduler like below then Intellij treats this situation ok.
return Mono.fromCallable(() -> /** BLOCKING CALL **/)
.subscribeOn(Schedulers.boundedElastic());
Which version is better? Bean, field or chain level.. ?
Is Scheduler always singleton with the same name? If not then the scheduler at the chain level is a bad idea from an allocation perspective.

Built-in schedulers like boundedElastic are fine to be referenced as part of the chain, as they are singleton. Only if you use one of the methods with new... prefix like newBoundedElastic or the ones that start with from... like fromExecutor, then you should create them at fields level as they create new resources.

Related

How can I use DI in Quartz JobListener?

I need to update some fields in the database each time a job starts and ends, keeping this apart from the jobs inner work.
The thing is I have no way to access my db context inside the listener, as the Scheduler.ListenerManager.AddJobListener method only receives an instance of the listener. How can I apply dependency injection to the listener in this situation?
You should use the built-in support for dependency injection. Because listeners are basically singletons I think you need to inject a service provider to the listener and then manually create a scope for resolving for the db context usage.

Access Service Provider Context in HystrixCommand's RunFallbackAsync

I am working to add the Hystrix CircuitBreaker pattern to an existing ASP.NET Core microservice, using Steeltoe CircuitBreaker, while maintaining the existing logging functionality with minimal refactoring (or as little as I can hope for).
Currently, an incoming HTTP request goes through the following layers:
Controller -> Service -> DerivedProvider -> AbstractProvider (and out to downstream service)
with Hystrix, I would like it to be:
Controller -> Service -> HystrixCommand<> -> DerviedProvider (via HystrixCommand's ExecuteAsync) -> AbstractProvider
Lots of context is stored in the providers, which is passed down through the layers via constructors, and logging is then happening in the AbstractProvider using that context, regardless of the outgoing call's result. The AbstractProvider also supports a fair amount of custom logic, such as optional pre and post execution callbacks. The post callback is invoked when a non-success response message is returned. Needless to say, changing the layers drastically doesn't appear easy to me, with my current understanding.
After reviewing the Hystrix documentation and Steeltoe CircuitBreaker documentation I am unclear if I can maintain, and access, the provider and its context within the HystrixCommand<>.RunFallbackAsync().
Perhaps the answer might relate to the lifecycle hooks you can override? Like onFallbackStart(HystrixInvokable commandInstance?
Ultimately, the goal is simply to make sure that any existing callback/logging functionality is not lost by wrapping these existing providers in a HystrixCommand. I am failing to understand how the HystrixCommand manages the providers and its context, and when/where you do or do not have access to them. Any suggestions or direction you can offer would be very much appreciated! Cheers!
Hystrix commands can be added to the service container or can be "new'd" (i.e. new MyHystrixCommand(...) whichever makes the most sense for you situation.
Remember that Hystrix commands can not be reused .. i.e. once you create and execute the command you must not try and reuse it.
Clearly if you are new'ng the HystrixCommand then you can define whatever arguments you want in the constructor and supply it with the right arguments (i.e. state) it needs to execute.
If you are injecting it into a controller or another service.. then before you use it... you can initialize it with whatever state you want using properties and then execute it.

Facade in Object Oriented Programming

In OOP, should a Facade be an object or just a class? Which is better?
Most of the examples in Wikipedia creates Facade as an object which should be instantiated before use.
CarFacade cf = new CarFacade();
cf.start();
Can it be designed to be like this instead?
CarFacade.start();
UPDATE
Can a Facade facilitate a singleton?
A facade
represents a high level API for a complex subsystem (module).
reduces client code dependencies.
This means that your client code only uses the facade and does
not have a lot of dependencies to classes behind that facade.
It is better to use an instance of an interface, because
you can replace it for tests. E.g. mock the subsystem the facade represents.
you can replace it at runtime.
When you use a static methods, your client code is bound to that method implementations at compile-time. This is usually the opposite of the open/close principle.
I said "usually the opposite", because there are examples when static methods are used, but the system is still open for extension. E.g.
ServiceLoader
The static load methods only scan the classpath and lookup service implementations. Thus adding classes and META-INF/services descriptions to the classpath will add other available services without changing the ServiceLoader's code.
Spring's AuthenticationFacade for example uses a ThreadLocal internally. This makes it possible to replace the behavior of the AuthenticationFacade. Thus it is open for extension too.
Finally I think it is better to use an instance and interface like I would use for most of the other classes.
It's two fold. You can use it as a static method. Say for instance in spring security I use AuthenticationFacade to access currently logged in user Principal details like so. AuthenticationFacade.getName()
There are other instances, in which mostly people create an instance of Facade and use it. In my opinion neither approach is superior over the other. Rather it depends on your context.
Finally Facade can use Singleton pattern to make sure that it creates only one instance and provides a global point of access to it.
This question is highly subjective. The only reason I am responding is because I reviewed some of my own code and found where I had written a Façade in one application as a singleton and written almost the same Façade in a different application requiring an instance. I'm going to discuss why I chose each of those routes in their respective applications so that I can evaluate if I made the correct choice.
A façade vs the open/close principle is already explained by #Rene Link. In my personal experience, you have to think of it this way: Does the object hold the state of itself?
Let's say I have a façade that wraps the Azure Storage API for .NET (https://learn.microsoft.com/en-us/azure/storage/common/storage-samples-dotnet)
This facade holds information about how to authenticate against the storage API so that it the client can do something like this:
Azure.Authenticate(username, password);
Azure.CreateFile("My New Text File", "\\FILELOCATION");
As you can see in this example, I have not created an instance and i'm using static methods, therefore following the singleton pattern. While this makes for code that is more concise, I now have an issue if I need to authenticate to a given path with a different credential than the one already provided, I would have to do something like this:
Azure.Authenticate(username, password)
Azure.CreateFile("My New Text File", "\\FILELOCATION");
Azure.Authenticate(username2, password2);
Azure.CreateFile("My Restrictied Text File", "\\RESTRTICTEDFILELOCATION");
While this would work, it can be hard to determine why authentication failed when I call Azure.ReadFile, as I have no idea what username and password may have been passed into the singleton from thread4 on form2 (which is no where to found) This is a prime example of where you should be using an instance. It would make much more since to do something like this:
Using (AzureFacade myAzure = Azure.Authenticate(username, password))
{
Azure.CreateFile("My New Text File", "\\FILELOCATION"); // I will always know the username and password.
}
With that said, what happens if the developer needs to create a file in Azure in a method that has no idea what the username and password to Azure may be. A good example of this would be an application that periodically connects to Azure and performs some multi-threaded tasks. In said application, the user setups a connection string to azure and all mulit-threaded tasks are performed using that connection string. Therefore, there is no need to create an instance for each thread (as the state of the object will always be the same) However, in order to maintain thread safety, you don't want to share the same instance across all the threads. This is where a singleton, thread-safe pattern may come into play. (Spring's AuthenticationFacade according to #Rene Link) So that I could do something like this (psudocode)
Thread[] allTask = // Create 5 threads
Azure.Authenticate(username, password) // Authenticate for all 5 threads.
allTask.start(myfunction)
void myFunction()
{
Azure.CreateFile("x");
}
Therefore, the choice between an instance of a façade v. a singleton façade is completely dependent on the intended application of the facade, however both can definitely exist.

#RepositoryEventHandler only invoked via HTTP - why?

when I use a #RepositoryEventHandler then its methods are only invoked when the call into the repository comes in via HTTP.
Any reason why? OK, it is called Spring Data REST, but wouldn't it be VERY useful to invoke the handler too, when I call my Repo directly, not via HTTP?
Any way to invoke the handler when called directly (some magic AOP-stuff)?
Thank you
The reason for that is that the different persistence mechanisms covered by the different Spring Data modules already ship with event mechanisms. Depending on the one you use you now get a different mechanism to use.
Unfortunately this can't be unified as e.g. with JPA not all persistence operations need to go through the repository in the first place, as JPA automatically flushes all changes that were made to an attached instance on EntityManager flush. In this case even AOP on the repository instance doesn't help.
So you're basically left with two choices:
The events exposed by Spring Data REST for all repositories (as we basically don't make use of the automatic change tracking in JPA).
The store specific event mechanisms that will make sure that the persistence mechanism exposes events as documented.
I don't know if the solution I put below from other stackoverflow questions would seen as acceptable by #Olivier-drotbohm, but from:
SpringDataRest #RepositoryEventHandler not running when Controller is added
and
#RepositoryEventHandler events stop with #RepositoryRestController
you could inject/autowire the "ApplicationEventPublisher" and fire the BeforeCreateEvent/AfterCreateEvent manually to trigger the RepositoryEventHandler.
This is not a perfect solution, but I hope it is good enough for you (and we tested it: it works).

EJB3 Singleton Session Bean and ConcurrentHashMap

If using a EJB3 Singleton Session Bean, there is no point to having ConcurrentHashMap state variable - correct? I can just use a regular HashMap that will be managed by the Container Concurrency Manager ?
That is correct. If nothing else is specified, by default singleton session bean uses container managed concurrency. Further, if not specified, every business and timeout method have by default LockType.WRITE. Result is that there is not multiple threads concurrently executing methods in singleton and as consequence using regular java.util.HashMap is perfectly fine.
The default is #ConcurrencyManagement(CONTAINER) with #Lock(WRITE) for all methods, which won't scale as nicely as a ConcurrentHashMap since all method calls will block waiting for the write lock. You could use #Lock(READ) and ConcurrentHashMap to allow multiple threads, but at that point, you might as well use #ConcurrencyManagement(BEAN) to get rid of the container-managed concurrency altogether.