RxJava2 idiom for combining two Maybes - java

Given two Maybe values, how can I combine them into a single Maybe that will either:
call onSuccess() whenever either of the source Maybes calls onSuccess
call onComplete() whenever both of the source Maybes call onComplete()?
(Cf. Option.orElse() in Scala or Vavr.)
E.g., assuming the existence of a combine() method that does what I want:
combine(Maybe.just(a), Maybe.empty()) ≍ Maybe.just(a)
combine(Maybe.empty(), Maybe.just(b)) ≍ Maybe.just(b)
combine(Maybe.empty(), Maybe.empty()) ≍ Maybe.empty()
combine(Maybe.never(), /*anything*/ ) ≍ /*the thing*/
combine(/*anything*/, Maybe.never()) ≍ /*the thing*/
At first I thought amb() & family were what I was looking for, but that completes as soon as either source Maybe completes, meaning if the first Maybe completes without a value, you never get the value from the second Maybe.
Right now I'm using
Maybe.mergeArray(m1, m2).firstElement()
which seems to do what I want, but I’m not certain it’s correct and I’m not certain it’s the cleanest way to do it. (For instance, if there’s some delay, will it call onSuccess() immediately when one or the other source does, or will it wait for both onComplete()s?)
Is this correct? Is there a more idiomatic approach?
ETA: I'm happy taking the first value; I don't need to wait for both to complete:
combine(Maybe.just(a), Maybe.just(b)) ≍ Maybe.just(/* a or b, don't care */)
(I can imagine situations in which I might prefer one or the other and want to indicate that by order of the arguments, but in that situation I suspect sequential would be better than parallel.)

There's a slightly different approach which might be a little nearer to your definition. This would be using Observable.switchMapMaybe():
Maps the upstream items into MaybeSources and switches (subscribes) to the newer ones while disposing the older ones (and ignoring their signals) and emits the latest success value of the current one if available while failing immediately if this Observable or any of the active inner MaybeSources fail.
Observable.just(m1, m2).switchMapMaybe(m -> m).firstElement()
But the approach using Maybe.mergeArray(m1, m2).firstElement() should be sufficient as well. The firstElement() operator emits the first element emitted by the mergeArray() flowable. This one is unordered and thus there's no information about the completion of any of the maybes.

Related

How to timeout current running API call without using any extra threads?

I have been looking for answer to this from one week, couldn't find anything relatable. Finally decided to post here.
I have use-case, where I need to give custom timeouts to different API calls. This use-case sounds very common. right ? well, I want to achieve this without using any extra threads. I am looking for system-clock described as given below.
So basically, I want to write one method ( calling it, EnforceTimeout() ), This method takes callable ( API call converted into callable format, which returns response, or exception ), and timeout in Miliseconds.
public static Object EnforceTimeout(Callable callable, Long TimeoutInMS) throws exceptions {
// Do Some Steps on current thread, but not create new thread/thread-pool
// 1. Start the clock
// 2. Make API call
// 3. Clock runs in background which takes care of the timeout, and if API call exceeds the time-limit then automatically enforce the exception.
}
Now, Some of you might have doubt, how can we keep track of elapsed time, without creating new thread. So here, let me describe a strategy like an Event-loop( in JavaScript ). We can define a system-clock. This clock should be able to look after 10 to 100 such callable's timeouts. It can check on such callable on priority queue (whichever callable has closest ending time), whether we have crossed the time limit.
Your next argument would be, one such system-clock instance would be inefficient to manage large number of callables. In that case, We need system-clock-manager, which will manage, how many such a clocks we will need, it should be able to handle the scaling of such system clock instances.
Please, let me know, if anything as such possible in java. If my question/idea is duplicate, pls guide me to the discussion, where I can find more information about the same. Thank you very much.

Java parallelization using lambda functions

I have an array of some objects with the method process() that I want to run parallelized. And I wanted to try lambdas to achieve the parallelization. So I tried this:
Arrays.asList(myArrayOfItems).forEach(item->{
System.out.println("processing " + item.getId());
item.process();
});
Each process() call takes about 2 seconds. And I have noticed that there is still no speedup with the "parallelization" approach. It seems that everything is still running serialized. The ids are printed in series (ordered) and between every print there is a pause of 2 seconds.
Probably I have misunderstood something. What is needed to execute this in parallel using lambdas (hopefully in a very condensed way)?
Lambdas itself aren't executing anything in parallel. Streams are capable of doing this though.
Take a look at the method Collection#parallelStream (documentation):
Arrays.asList(myArrayOfItems).parallelStream().forEach(...);
However, note that there is no guarantee or control when it will actually go parallel. From its documentation:
Returns a possibly parallel Stream with this collection as its source. It is allowable for this method to return a sequential stream.
The reason is simple. You really need a lot of elements in your collection (like millions) for parallelization to actually pay off (or doing other heavy things). The overhead introduced with parallelization is huge. Because of that, the method might choose to use sequential stream instead, if it thinks that it will be faster.
Before you think about using parallelism, you should actually setup some benchmarks to test if it improves anything. There are many examples where people did just blindly use it without noticing that they actually decreased the perfomance. Also see Should I always use a parallel stream when possible?.
You can check if a Stream is parallel by using Stream#isParallel (documentation).
If you use Stream#parallel (documentation) directly on a stream, you get a parallel version.
Method Collection.forEach() is just iteration through all the elements. It is called internal iteration as it leaves up to the collection how it will iterate, but it is still an iteration on all the elements.
If you want parallel processing, you have to:
Get a parallel stream from the collection.
Specify the operation(s) which will be done on the stream.
Do something with the result if you need to.
You may read first part of my explanation here: https://stackoverflow.com/a/22942829/2886891
To create a parallel stream, invoke the operation .parallelStream on a Collection
See https://docs.oracle.com/javase/tutorial/collections/streams/parallelism.html
Arrays.asList(myArrayOfItems).parallelStream().forEach(item->{
System.out.println("processing " + item.getId());
item.process();
});

Multithreaded Observer in Java - preserve proper order

I am implementing something that I would call "Observable Set". It is just a normal set, but it can have some observers that are notified about adding new elements.
What is important for me, is that elements may be added from many threads at time, and also there are many observing threads. I hold Observers in CopyOnWriteArrayList (it is thread-safe). The key point is to inform observers about adding elements in way, that informing order for each of observers is the same as order of adding elements.
What is best approach?
The most naive one is to put adding and informing in "synchronized" block. But i believe it can be slow etc.
Second I've tried was to just add element to set, and add it to "informing queue". With each addition of element it was checked whether informing is turned on. If not, it was started until the queue was empty. It was working quite OK but i was afraid that it wasn't nice approach.
The last that I've implemented, i would call as "informing threads". With adding observers, each observer has it's own "informing thread" created. That thread runs in background and checks if it's at end of global "informing queue". If it isn't it informs specific thread about new elements. However I've problems with synchronization, and while(true) loop. I don't know how to set condition to end thread. The next problem I noticed when writing it, is that every new thread will be informed from beginning... It's not good.
I hope I have described everything quite well. If not, please let me know, i will try to fix it.
What is best way to accomplish this task?
Thanks!
Your second solution could be improved to use a BlockingQueue: with it you don't need to check whether "informing is turned on", you just call take(), and it will wait for something to appear in the queue.
You could also look into the RxJava project. It is somewhat complex, but it has lots of features you might need.
It extends the observer pattern to support sequences of data/events and adds operators that allow you to compose sequences together declaratively while abstracting away concerns about things like low-level threading, synchronization, thread-safety and concurrent data structures.

Why addListener() typically returns void?

Am seeing that a typical addXXXListener() returns void !
I have seen this as a practice across the board whether it is UI frameworks (like Swing) or server-side frameworks.
For ex:
Class: AsyncContext
public void addAsyncListener(AsyncListener listener);
Class: AbstractButton
public void addActionListener(ActionListener l)
And numerous other examples...
Shouldnt we be interested to know if the add listener call completed successfully ?
What if the component was in a state where the listener could not be added ?
For ex: Consider the Guava library [ListenableFuture](http://guava-libraries.googlecode.com/svn/tags/release08/javadoc/com/google/common/util/concurrent/ListenableFuture.html#addListener(java.lang.Runnable, java.util.concurrent.Executor))
It has a
void addListener(Runnable listener, Executor exec);
Its behavior is that the listener is executed when the Future's computation is complete.
They took the approach that, if the Future is already complete then the listener would be called immediately. Even if the future was completed ages back.
There is no indication to the user that they are calling addListener() unnecessarily on an already completed future !
I would think the addListener() should be capable of returning a value(boolean?) that says if the listener could be successfully added and let the caller do the handling if the listener could not be added !
I know there must be some reason why all addListeners are written this way.
I just dont know why ?
These methods generally simply add your listener to a list. The circumstances in which it would not work are generally outside your control (think out of memory error for example) and would trigger an exception anyway.
The reason why Collection#add, for example, returns a boolean is that some implementations will only add the item if some conditions are met (e.g. Sets won't add an item if it is a duplicate). Note that this is the only situation when Collection#add will return false (other reasons will trigger an exception):
If a collection refuses to add a particular element for any reason other than that it already contains the element, it must throw an exception (rather than returning false). This preserves the invariant that a collection always contains the specified element after this call returns.
This was probably deemed not very useful for addListener.
The convention is to return information to the caller if the caller can be expected to act on the information.
The ListenableFuture is a very different use case to most addXXXListener() calls. These are expected to return immediately and be 100% successful in normal operation (e.g. just adding a listener to some internal list structure) and there is no actionable information to return to the caller. (However, in non-normal operation you would probably expect it to throw an unchecked Exception).
One possible variation is to treat this as a mutator operation and extend the usual Collection pattern to return a boolean if the internal data structure has been modified by the addXXXListener() call. Although this only returns useful information if the caller is not aware whether or not it has already added itself...
In all these cases, there's no possible way the listener could fail to be added.
Even if the future was completed ages back.
So what if the future was completed ages back? If you want to add a listener to the Future, you want to do something with that result whenever it's completed, whether that was ages ago or in the future.

Name for pattern in which actions happen upon completion of a future event / Java class

I have a class currently called Promise that works as follows:
It holds a future value
It can always accept a subsequent action to take that uses the future value as the parameter
When the value is completed the function queue launches
Any functions added after the future is complete happen synchronously
So this seems to be a design pattern from functional programming that we're jamming into Java. The important thing is that we can daisy-chain on delayed events, which I understand is a feature more built into C# 3.0 language but you have to hack together with Java classes. Unfortunately, one, I don't know a better name for this than "promise" or "future," which seem misleading since the focus is more on the "DelayedCallStack" then the value at hand, and two, I don't know of any way to do this beyond writing our own fairly complicated Promise class. Ideally I'd like to lift this from the functional Java library but the concept eludes me thus far.
Note Java doesn't even give language/library support for an asynchronous callback that takes a parameter, which is one reason I'm so pessimistic about being able to find this.
So, what is this pattern, can it be done in libraries?
Take a look a ListenableFuture in Guava:
http://code.google.com/p/guava-libraries/wiki/ListenableFutureExplained
ListenableFuture allows you to add callbacks to be executed when the Future computation is completed. You can control what thread pool the callbacks get executed under, so they can be executed synchronously or asynchronously.
I can only say that we implemented pretty much exactly the same thing in Flex (ActionScript) and we also called it a Promise. In Clojure a promise is something quite a bit more lightweight: the get operation on it blocks until another thread delivers the promise. It's basically a one-element queue except that it retains its value forever, so subsequent gets always succeed.
What you have is a kind of a promise coupled with observers of its value. I'm not aware of any special term covering exactly that case.
EDIT
Now I notice that your "promise/future" might own the code that produces its future value (at least it's not entirely obvious whether it does). The ActionScript implementation I mentioned didn't do that -- it behaved like Clojure's, the value being supplied from the outside. I think this is the key distinction between a future and a promise.

Categories

Resources