How do Hooks in Webflux / Spring Reactor work (using switchIfEmpty as an example)? - spring

If I use switchIfEmpty for a Mono for example, I have a hard time locating where the actual comparison (if the Mono is in fact empty) is happening. The first thing my IDE jumps to, is the snippet below.
public final Mono<T> switchIfEmpty(Mono<? extends T> alternate) {
return onAssembly(new MonoSwitchIfEmpty(this, alternate));
}
However, onAssembly only calls a static method / value in the Hooks abstract class. That hook "onEachOperatorHook" does seem to use an Functional Interface, but I can't seem to find where this is placed / coded.
The comments also mention pointcuts, but I also don't find any hints into any #Aspect annotated classes, so I assume it's implemented with the Hooks only.
Can anyone point me in the right direction, where the Hooks actually take the information from (supposedly a Lambda) for comparing the two Monos in case of switchIfEmpty?
Many thanks.

The logic is taking place inside SwitchIfEmptySubscriber<T>:
static final class SwitchIfEmptySubscriber<T> extends Operators.MultiSubscriptionSubscriber<T, T> {
final Publisher<? extends T> other;
boolean once;
SwitchIfEmptySubscriber(CoreSubscriber<? super T> actual, Publisher<? extends T> other) {
super(actual);
this.other = other;
}
public void onNext(T t) {
if (!this.once) {
this.once = true;
}
this.actual.onNext(t);
}
public void onComplete() {
if (!this.once) {
this.once = true;
this.other.subscribe(this);
} else {
this.actual.onComplete();
}
}
public Object scanUnsafe(Scannable.Attr key) {
return key == Attr.RUN_STYLE ? RunStyle.SYNC : super.scanUnsafe(key);
}
}
In case of an empty Mono:
onComplete() is triggered
this.once is false since onNext() has not been executed
this.other publisher (the alternative Mono given in switchIfEmpty) gets subscribed

Related

static vs default method - Functional interfaces

I am creating functional interfaces and want to reuse default methods with anonymous implementation.
public class JavaInterfaceTest {
public static void main(String[] args) {
FunctionalIntf fi = () -> {
System.out.println("In ananymus impl, trying to call default method");
// doInternal()
return "Hello";
};
fi.doFunction(); // How this line valid ?
fi.doInternal();
FunctionalIntf.doSomething();
}
}
#FunctionalInterface
interface FunctionalIntf {
String doFunction();
default void doInternal(){
System.out.println("In doInternal");
}
static void doSomething(){
System.out.println("In doSomething");
}
}
How fi.doFunction(); is valid, if I go thru anonymous implementation.
How can I re-sue default method or static method if I want from implementation?
3. Is returning something valid/best practice in my case as I can not handle the returned value.
When you are creating the anonymous class, you actually provide an implementation for your abstract method doFunction() from FunctionalIntf interface. So when you are using this line of code:
fi.doFunction();
It means that you are calling doFunction() method from the anonymous class. This is another example on how functional interfaces work:
Runnable r = new Runnable() {
#Override
public void run() {
System.out.println("I'm Runnable!");
}
};
r.run();
In this case we override run() method from Runnable interface, which is also a functional interface.
You cannot provide another implementation for the static method because you cannot override a static method. Static methods are not inherited in Java at all. You can instead provide another implementation for the default method by overriding as mentioned in my above example.
Regarding the returned value, you need to define your method to return the exact value you need. There is no best practice in that.
When you implement a functional interface, you have 2 options:
Use lambdas, as you have
Use inner classes.
If you use lambdas, like you have, you have the default implementation of the static/default methods along with the implementation of the abstract method.
If you use an inner class, the normal rules of overriding applies.

Cache not refreshing when being called from a asynchrounous function in Spring

I am calling a function which has CacheEvict annotation on it. This is being called from a function that is itself executed asynchronously.
It seems that the cache is not being evicted after the function has been executed.
Here is sample code
#Async("executor1")
public void function1()
{
// do something
anotherFunction("name", 123, 12);
// do something more
}
#CacheEvict(cacheNames = {"cache1", "cache2", "cache3"}, key = "#testId")
public List<Integer> anotherFunction(String name, int testId, int packageId)
{
// some code here
}
What I want is that entries corresponding to testId should be cleared from all the caches.
However, in another call, I can see old entries of cache1. function1 is being called from the controller. Both these functions are present inside the service. Now, Is this configuration correct? If yes, What may be the possible reasons that cache is not being cleared?
Any help appreciated. Thanks in advance.
I think your problem is that Spring proxies are not reentrant. To implement Async and CacheEvict, Spring creates a proxy. So, in your example, the call stack will be:
A -> B$$proxy.function1() -> B.function1() -> B.anotherFunction()
B$$proxy contains the logic for async and eviction. Which won't apply when calling directly anotherFunction. In fact, even if you remove the #Async, it will still don't work.
A trick you can use is to inject the proxied bean into the class. To delegate to the proxy of the class instead this.
public class MyClass {
private MyClass meWithAProxy;
#Autowired
ApplicationContext applicationContext;
#PostConstruct
public void init() {
meWithAProxy = applicationContext.getBean(MyClass.class);
}
#Async("executor1")
public void function1() {
meWithAProxy.anotherFunction("name", 123, 12);
}
#CacheEvict(cacheNames = "cache1", key = "#testId")
public List<Integer> anotherFunction(String name, int testId, int packageId) {
return Collections.emptyList();
}
}
It works. But there's a catch. If you now call anotherFunction directly, it won't work. I consider this to be a Spring bug and will file it as is.

Spring Cache Abstraction: How to Deal With java.util.Optional<T>

We have a lot of code in our code base that's similar to the following interface:
public interface SomethingService {
#Cacheable(value = "singleSomething")
Optional<Something> fetchSingle(int somethingId);
// more methods...
}
This works fine as long we're only using local caches. But as soon as we're using a distributed cache like Hazelcast, things start to break because java.util.Optional<T> is not serializable and thus cannot be cached.
With what I've come up so far to solve this problem:
Removing java.util.Optional<T> from the method definitions and instead checking for the trusty null.
Unwrapping java.util.Optional<T> before caching the actual value.
I want to avoid (1) because it would involve a lot of refactoring. And I have no idea how to accomplish (2) without implementing my own org.springframework.cache.Cache.
What other options do I have? I would prefer a generic (Spring) solution that would work with most distributed caches (Hazelcast, Infinispan, ...) but I would accept a Hazelcast-only option too.
A potential solution would be to register a serializer for the Optional type. Hazelcast has a flexibile serialization API and you can register a serializer for any type.
For more information see the following example:
https://github.com/hazelcast/hazelcast-code-samples/tree/master/serialization/stream-serializer
So something like this:
public class OptionalSerializer implements StreamSerializer<Optional> {
#Override
public void write(ObjectDataOutput out, Optional object) throws IOException {
if(object.isPresent()){
out.writeObject(object.get());
}else{
out.writeObject(null);
}
}
#Override
public Optional read(ObjectDataInput in) throws IOException {
Object result = in.readObject();
return result == null?Optional.empty():Optional.of(result);
}
#Override
public int getTypeId() {
return 0;//todo:
}
#Override
public void destroy() {
}
}
However the solution isn't perfect because this Optional thing will be part of the actual storage. So internally the Optional wrapper is also stored and this can lead to problems with e.g. queries.

Visual Studio code generated when choosing to explicitly implement interface

Sorry for the vague title, but I'm not sure what this is called.
Say I add IDisposable to my class, Visual Studio can create the method stub for me. But it creates the stub like:
void IDisposable.Dispose()
I don't follow what this syntax is doing. Why do it like this instead of public void Dispose()?
And with the first syntax, I couldn't work out how to call Dispose() from within my class (in my destructor).
When you implement an interface member explicitly, which is what the generated code is doing, you can't access the member through the class instance. Instead you have to call it through an instance of the interface. For example:
class MyClass : IDisposable
{
void IDisposable.Dispose()
{
// Do Stuff
}
~MyClass()
{
IDisposable me = (IDisposable)this;
me.Dispose();
}
}
This enables you to implement two interfaces with a member of the same name and explicitly call either member independently.
interface IExplict1
{
string InterfaceName();
}
interface IExplict2
{
string InterfaceName();
}
class MyClass : IExplict1, IExplict2
{
string IExplict1.InterfaceName()
{
return "IExplicit1";
}
string IExplict2.InterfaceName()
{
return "IExplicit2";
}
}
public static void Main()
{
MyClass myInstance = new MyClass();
Console.WriteLine( ((IExplcit1)myInstance).InstanceName() ); // outputs "IExplicit1"
IExplicit2 myExplicit2Instance = (IExplicit2)myInstance;
Console.WriteLine( myExplicit2Instance.InstanceName() ); // outputs "IExplicit2"
}
Visual studio gives you two options:
Implement
Implement explicit
You normally choose the first one (non-explicit): which gives you the behaviour you want.
The "explicit" option is useful if you inherit the same method from two different interfaces, i.e multiple inheritance (which isn't usually).
Members of an interface type are always public. Which requires their method implementation to be public as well. This doesn't compile for example:
interface IFoo { void Bar(); }
class Baz : IFoo {
private void Bar() { } // CS0737
}
Explicit interface implementation provides a syntax that allows the method to be private:
class Baz : IFoo {
void IFoo.Bar() { } // No error
}
A classic use for this is to hide the implementation of a base interface type. IEnumerable<> would be a very good example:
class Baz : IEnumerable<Foo> {
public IEnumerator<Foo> GetEnumerator() {}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { }
}
Note how the generic version is accessible, the non-generic version is hidden. That both discourages its use and avoids a compile error because of a duplicate method.
In your case, implementing Dispose() explicitly is wrong. You wrote Dispose() to allow the client code to call it, forcing it to cast to IDisposable to make the call doesn't make sense.
Also, calling Dispose() from a finalizer is a code smell. The standard pattern is to add a protected Dispose(bool disposing) method to your class.

Best way to notify observers in MVC?

Say you have 5 or 6 variables in the model which a certain View is interested in, do you write different functions for each, such as
int a;
int b;
int c;
void setA( newA ) {
a = newA;
notifyAObservers();
}
void setB( newB ) {
b = newB;
notifyBObservers();
}
void setC( newC ) {
b = newC;
notifyCObservers();
}
Or do you just have one notify method and waste a little bit of CPU time
i.e. instead of notifyAObservers and notifyBObservers, you just have notifyObservers
I believe the traditional approach is to notify all observers, and let them handle it. This is because you don't know which observers are observing which variable(s) - you just know that they want to be notified when something changes. However, if you do know what observers are observing which variables, and performance is critical, then you might be able to do something like what you have.
In the traditional Observer pattern, the Observers implement an update() method that is called by the controller when a change happens. The Observables (the data model) would have a notifyObservers() method that iterates over the Observers and calls their update() method. Then, the Observers get whatever they need and the view updates.
Any time I have implemented the Observer pattern, however, I simply keep a list of observers and notify them all. That way, I only have one list of observers and the rest of the class as well as the different observers can all change without me making any changes to the observable class notification.
EDIT: I wrote my answer a few years ago. After reading it just now, I felt I needed to update it.
I believe the best approach is to notify all observers and let the views decide if they need to update themselves..
Each view will be able to verify the state of the model and act accordingly.
Additionally, the "args" could be used as a flag to indicate what has changed (the view may not wish to update itself for every little change).
That way, the model REALLY does not know how and what the view is displaying, they are decoupled.
A first implementation would look like this:
public class MyModelV1 extends Observable {
private int value;
public void setValue(int value) {
this.value = value;
setChanged();
notifyObservers();
}
public int getValue() {
return value;
}
}
public class MyViewV1 implements Observer {
public void update(Observable o, Object arg) {
if (o instanceof MyModelV1) {
System.out.println(((MyModelV1) o).getValue());
}
}
}
The view simply checks the type of the observable received.
However, if the model has many attributes and triggers the view for many different scenarios, this simple check may refresh the view too often.
Another approach would be the following:
public class MyModelV2 extends Observable {
private int value;
public void setValue(int value) {
this.value = value;
setChanged();
notifyObservers("value");
}
public int getValue() {
return value;
}
}
public class MyViewV2 implements Observer {
public void update(Observable o, Object arg) {
if (o instanceof MyModelV2 && "value".equals(arg)) {
System.out.println(((MyModelV2) o).getValue());
}
}
}
Here, the notification passes a qualifier, which lets the view decide more precisely when to refresh itself.
The view still needs to check and cast the Model, because there is no garantee that the arg "value" isn't notified by another model (and the cast would fail at runtime).
My personal favorite is something along those lines:
public class MyModelV3 extends Observable {
private int value;
public void setValue(int value) {
this.value = value;
setChanged();
Notification.MY_MODEL_VALUE_UPDATED.notifyObserver(this);
}
public int getValue() {
return value;
}
}
public class MyViewV3 implements Observer {
public void update(Observable o, Object arg) {
if (Notification.MY_MODEL_VALUE_UPDATED.equals(arg)) {
MyModelV3 model = Notification.MY_MODEL_VALUE_UPDATED.getModel(o);
System.out.println(model.getValue());
}
}
}
public class Notification<T extends Observable> {
public static final Notification<MyModelV3> MY_MODEL_VALUE_UPDATED = new Notification<MyModelV3>();
private Notification() {
}
public T getModel(Observable o) {
return (T) o;
}
public void notifyObserver(T observable){
observable.notifyObservers(this);
}
}
Here, the notification sends a strongly typed qualifier, which is bound to the Model.
The view is able to use the notification to retrieve a strongly typed model (instead of casting).
This is somewhere between an observer and an event bus..

Resources