Merging two Mono and getting a Flux. Then extracting a Mono from that Flux - mono

I have two Mono<T> that i have got from two different sources let us say KAFKA.
My intention is to merge both these Mono into a Flux<T>. 1
Then use public final Mono<T> reduce(BiFunction<T,T,T> aggregator) method in Flux to create a final Mono out of it (as the response time of above two Mono may vary). 2
approach:
There are many methods such as contact, zip, zipWith to use on Flux. How do i arrive at a correct method to use (Two Mono to Flux conversion i.e, 1).
And is this REDUCE approach really correct or is there anything else could be done to improvise it (2) ? Thanks.

If you really want to use a Flux to do this, then you'd likely want to use merge(), similar to:
Flux.merge(mono1(), mono2()).reduce((obj1, obj2) -> foo(obj1, obj2));
...where foo() fulfils the functionality of the reduce method in the question, combining both objects emitted into a single value. You wouldn't want to use concat() unless you want to subscribe to each Mono one at a time, waiting for each to complete, rather than all together - and the Flux.zipXXX series of operators would be used for zipping separate fluxes together, so you wouldn't want that.
However, I don't think you quite have the correct approach here for two values - if you want to put two Mono publishers into a Flux and then immediately reduce them back to a Mono, then it doesn't make much sense to use a Flux at all, since you have to wait for both the publishers to complete before emitting anything, and then you're just emitting a single value.
Instead, I'd recommend using this variant of Mono.zip(), which allows you to do everything you need in one go, something like:
Mono.zip(mono1(), mono2(), (obj1, obj2) -> foo(obj1, obj2));

Related

Synchronized collection that blocks on every method

I have a collection that is commonly used between different threads. In one thread I need to add items, remove items, retrieve items and iterate over the list of items. What I am looking for is a collection that blocks access to any of its read/write/remove methods whenever any of these methods are already being called. So if one thread retrieves an item, another thread has to wait until the reading has completed before it can remove an item from the collection.
Kotlin doesn't appear to provide this. However, I could create a wrapper class that provides the synchronization I'm looking for. Java does appear to offer the synchronizedList class but from what I read, this is really for blocking calls on a single method, meaning that no two threads can remove an item at the same time but one can remove while the other reads an item (which is what I am trying to avoid).
Are there any other solutions?
A wrapper such as the one returned by synchronizedList
synchronizes calls to every method, using the wrapper itself as the lock. So one thread would be blocked from calling get(), say, while another thread is currently calling put(). (This is what the question seems to ask for.)
However, as the docs to that method point out, this does nothing to protect sequences of calls, such as you might use when iterating through a collection. If another thread changes the collection in between your calls to next(), then anything could happen. (This is what I think the question is really about!)
To handle that safely, your options include:
Manual synchronization. Surround each sequence of calls to the collection in a synchronized block that synchronises on the collection, e.g.:
val list = Collections.synchronizedList(mutableListOf<String>())
// …
synchronized (list) {
for (i in list) {
// …
}
}
This is straightforward, and relatively easy to do if the collection is under your control. But if you miss any sequences, then you could get unexpected behaviour. Also, you'll need to keep your sequences short, to avoid holding the lock for an extended time and affecting performance.
Use a concurrent collection implementation which provides primitives letting you do all the processing you need in a single call, avoiding iteration and other sequences.
For maps, Java provides very good support with its ConcurrentMap interface, and high-performance implementations such as ConcurrentHashMap. These have methods allowing you to iterate, update single or multiple mappings, search, reduce, and many other whole-map operations in a single call, avoiding any concurrency problems.
For sets (as per this question) you can use a ConcurrentSkipListSet, or you can create one from a ConcurrentHashMap with newKeySet().
For lists (as per this question), there are fewer options. (I think concurrent lists are much less commonly needed.) If you don't need random access, ConcurrentLinkedQueue may suffice. Or if modification is much less common than iteration, CopyOnWriteArrayList could work.
There are many other concurrent classes in the java.util.concurrent package, so it's well worth looking through to see if any of those is a better match for your particular case.
If you have specialised requirements, you could write your own collection implementation which supports them. Obviously this is more work, and only worthwhile if none of the above approaches does what you want.
In general, I think it's well worth stepping back and seeing whether iteration is really needed. Historically, in imperative languages all the way from FORTRAN through BASIC and C up to Java, the for loop has traditionally been the tool of choice (sometimes the only structure) for operating on collections of data — and for those of us who grew up on those languages, it's what we reach for instinctively. But the functional programming paradigm provides alternative tools, and so in languages like Kotlin which provide some of them, it's good to stop and ask ourselves “What am I ultimately trying to achieve here?” (Often what we want is actually to update all entries, or map to a new structure, or search for an element, or find the maximum — all of which have better approaches in Kotlin than low-level iteration.)
After all, if you can tell the compiler what you want to do, instead of how to do it, then your program is likely to be shorter and easier to read and maintain, freeing you to think about more important things!

Do we need to lock the immutable list in kotlin?

var list = listOf("one", "two", "three")
fun One() {
list.forEach { result ->
/// Does something here
}
}
fun Two() {
list = listOf("four", "five", "six")
}
Can function One() and Two() run simultaneously? Do they need to be protected by locks?
No, you dont need to lock the variable. Even if the function One() still runs while you change the variable, the forEach function is running for the first list. What could happen is that the assignment in Two() happens before the forEach function is called, but the forEach would either loop over one or the other list and not switch due to the assignment
if you had a println(result) in your forEach, your program would output either
one
two
three
or
four
five
six
dependent on if the assignment happens first or the forEach method is started.
what will NOT happen is something like
one
two
five
six
Can function One() and Two() run simultaneously?
There are two ways that that could happen:
One of those functions could call the other.  This could happen directly (where the code represented by // Does something here in One()⁽¹⁾ explicitly calls Two()), or indirectly (it could call something else which ends up calling Two() — or maybe the list property has a custom setter which does something that calls One()).
One thread could be running One() while a different thread is running Two().  This could happen if your program launches a new thread directly, or a library or framework could do so.  For example, GUI frameworks tend to have one thread for dispatching events, and others for doing work that could take time; and web server frameworks tend to use different threads for servicing different requests.
If neither of those could apply, then there would be no opportunity for the functions to run simultaneously.
Do they need to be protected by locks?
If there's any possibility of them being run on multiple threads, then yes, they need to be protected somehow.
99.999% of the time, the code would do exactly what you'd expect; you'd either see the old list or the new one.  However, there's a tiny but non-zero chance that it would behave strangely — anything from giving slightly wrong results to crashing.  (The risk depends on things like the OS, CPU/cache topology, and how heavily loaded the system is.)
Explaining exactly why is hard, though, because at a low level the Java Virtual Machine⁽²⁾ does an awful lot of stuff that you don't see.  In particular, to improve performance it can re-order operations within certain limits, as long as the end result is the same — as seen from that thread.  Things may look very different from other threads — which can make it really hard to reason about multi-threaded code!
Let me try to describe one possible scenario…
Suppose Thread A is running One() on one CPU core, and Thread B is running Two() on another core, and that each core has its own cache memory.⁽³⁾
Thread B will create a List instance (holding references to strings from the constant pool), and assign it to the list property; both the object and the property are likely to be written to its cache first.  Those cache lines will then get flushed back to main memory — but there's no guarantee about when, nor about the order in which that happens.  Suppose the list reference gets flushed first; at that point, main memory will have the new list reference pointing to a fresh area of memory where the new object will go — but since the new object itself hasn't been flushed yet, who knows what's there now?
So if Thread A starts running One() at that precise moment, it will get the new list reference⁽⁴⁾, but when it tries to iterate through the list, it won't see the new strings.  It might see the initial (empty) state of the list object before it was constructed, or part-way through construction⁽⁵⁾.  (I don't know whether it's possible for it to see any of the values that were in those memory locations before the list was created; if so, those might represent an entirely different type of object, or even not a valid object at all, which would be likely to cause an exception or error of some kind.)
In any case, if multiple threads are involved, it's possible for one to see list holding neither the original list nor the new one.
So, if you want your code to be robust and not fail occasionally⁽⁶⁾, then you have to protect against such concurrency issues.
Using #Synchronized and #Volatile is traditional, as is using explicit locks.  (In this particular case, I think that making list volatile would fix the problem.)
But those low-level constructs are fiddly and hard to use well; luckily, in many situations there are better options.  The example in this question has been simplified too much to judge what might work well (that's the down-side of minimal examples!), but work queues, actors, executors, latches, semaphores, and of course Kotlin's coroutines are all useful abstractions for handling concurrency more safely.
Ultimately, concurrency is a hard topic, with a lot of gotchas and things that don't behave as you'd expect.
There are many source of further information, such as:
These other questions cover some of the issues.
Chapter 17: Threads And Locks from the Java Language Specification is the ultimate reference on how the JVM behaves.  In particular, it describes what's needed to ensure a happens-before relationship that will ensure full visibility.
Oracle has a tutorial on concurrency in Java; much of this applies to Kotlin too.
The java.util.concurrent package has many useful classes, and its summary discusses some of these issues.
Concurrent Programming In Java: Design Principles And Patterns by Doug Lea was at one time the best guide to handling concurrency, and these excerpts discuss the Java memory model.
Wikipedia also covers the Java memory model
(1) According to Kotlin coding conventions, function names should start with a lower-case letter; that makes them easier to distinguish from class/object names.
(2) In this answer I'm assuming Kotlin/JVM.  Similar risks are likely apply to other platforms too, though the details differ.
(3) This is of course a simplification; there may be multiple levels of caching, some of which may be shared between cores/processors; and some systems have hardware which tries to ensure that the caches are consistent…
(4) References themselves are atomic, so a thread will either see the old reference or the new one — it can't see a bit-pattern comprising parts of the old and new ones, pointing somewhere completely random.  So that's one problem we don't have!
(5) Although the reference is immutable, the object gets mutated during construction, so it might be in an inconsistent state.
(6) And the more heavily loaded your system is, the more likely it is for concurrency issues to occur, which means that things will probably fail at the worst possible time!

What are the drawbacks of encapsulating arguments for different cases in one object?

I'll give you an example about path finding. When you wnat to find a path, you can pick a final destination, a initial position and find the fastest way between the two, or you can just define the first position, and let the algorithm show every path you can finish, or you may want to mock this for a test and just say the final destination and assume you "teleport" to there, and so on. It's clear that the function is the same: finding a path. But the arguments may vary between implementations. I've searched a lot and found a lot of solutions: getting rid of the interface, putting all the arguments as fields in the implementation, using the visitor pattern...
But I'd like to know from you guys what is the drawback of putting every possible argument (not state) in one object (let's call it MovePreferences) and letting every implementation take what it needs. Sure, may you need another implementation that takes as argument that you didn't expect, you will need to change the MovePreferences, but it don't sound too bad, since you will only add methods to it, not refactor any existing method. Even though this MovePreferences is not an object of my domain, I'm still tempted to do it. What do you think?
(If you have a better solution to this problem, feel free to add it to your answer.)
The question you are asking is really why have interfaces at all, no, why have any concept of context short of 'whatever I need?' I think the answers to that are pretty straightforward: programming with shared global state is easy for you, the programmer, and quickly turns into a vortex for everyone else once they have to coalesce different features, for different customers, render enhancements, etc.
Now the far other end of the spectrum is the DbC argument: every single interface must be a highly constrained contract that not only keeps the knowledge exchanged to an absolute minimum, but makes the possibility of mayhem minimal.
Frankly, this is one of the reasons why dependency injection can quickly turn into a mess: as soon as design issues like this come up, people just start injecting more 'objects,' often to get access to just one property, whose scope might not be the same as the scope of the present operation. [Different kind of nightmare.]
Unfortunately, there's almost no information in your question. Do I think it would be possible to correctly model the notion of a Route? Sure. That doesn't sound very challenging. Here are a few ideas:
Make a class called Route that has starting and ending points. Then a collection of Traversals. The idea here would be that a Route could completely ignore the notion of how someone got from point a to point b, where traversal could contain information about roads, traffic, closures, whatever. Then your mocked case could just have no Traversals inside.
Another option would be to make Route a Composite so that each trip is then seen as the stringing together of various segments. That's the way routes are usually presented: go 2 miles on 2 South, exit, go 3 miles east on Santa Monica Boulevard, etc. In this scenario, you could just have Routes that have no children.
Finally, you will probably need a creational pattern. Perhaps a Builder. That simplifies mocking things too because you can just make a mock builder and have it construct Routes that consist of whatever you need.
The other advantage of combining the Composite and Builder is that you could make a builder that can build a new Route from an existing one by trying to improve only the troubling subsegments, e.g. it got traffic information that the 2S was slow, it could just replace that one segment and present its new route.
Consider an example,
Say if 5 arguments are encapsulated in an object and passed on to 3 methods.
If the object undergoes change in structure, then we need to run test cases for all the 3 methods. Instead if the method accepts only the arguments they need, they need not be tested.
Only problem I see out of this is Increase in Testing Efforts
Secondly you will naturally violate Single Responsibility Principle(SRP) if you pass more arguments than what the method actually needs.

Comparing ASTNodes in Eclipse

I'm writing a plugin for Eclipse that periodically walks the Abstract Syntax Tree provided by Eclipse JDT and places IMarkers on certain nodes - for example, a printStackTrace() is highlighted for removal (Youtube Demo). For each subsequent walk I want to avoid placing a 2nd (or 3rd or 4th or...) marker.
The position of these nodes can change (if the document is edited between walks) but the IMarkers do not (IMarker positions do not update until the document has been saved), so I can't use char_start and char_end comparisons on these objects.
I also can't use the .equals method of ASTNode, as a stored copy of an ASTNode won't update these charstart and charend positions. I've also tried comparing getParent() nodes but this has its own issues (ie two printStackTraces, in separate catch blocks, will have a common TryStatement parent)
Right now I'm looking at extending ASTMatcher and overriding the various matches() methods, but to call each matches() I'll need to cast one of the nodes from ASTNode to the appropriate subclass.
Before trying to write that up with a massive switch statement and a lot of casting, is there a more elegant solution for checking if two ASTNodes are the same without relying on .equals()?
Generally validators and builders will remove all of the markers on a file before going back and adding their own for that particular validation or build. I suspect they did it that way instead of taking your approach because it was easier that way. I'd take that approach unless there is a serious performance reason not to.
If you do need to do a comparison between old and new, you'll need to write a switch statement and do a lot of casting, although you can at least make it look elegant with a factory pattern of some sort.

How to fill Gtk::TreeModelColumn with a large dataset without locking up the application

I need to fill in a large (maybe not so much - several thousands of entries) dataset to a Gtk::TreeModelColumn. How do I do that without locking up the application. Is it safe to put the processing into separate thread? What parts of the application do I have to protect with a lock then? Is it only the Gtk::TreemodelColumn class, or Gtk::TreeView widget it is placed in, or maybe even surrounding frame or window?
There are two general approaches you could take. (Disclaimer: I've tried to provide example code, but I rarely use gtkmm - I'm much more familiar with GTK in C. The principles remain the same, however.)
One is to use an idle function - that runs whenever nothing's happening in your GUI. For best results, do a small amount of calculation in the idle function, like adding one item to your treeview. If you return true from the idle function, then it is called again whenever there is more processing time available. If you return false, then it is not called again. The good part about idle functions is that you don't have to lock anything. So you can define your idle function like this:
bool fill_column(Gtk::TreeModelColumn* column)
{
// add an item to column
return !column_is_full();
}
Then start the process like this:
Glib::signal_idle().connect(sigc::bind(&fill_column, column));
The other approach is to use threads. In the C API, this would involve gdk_threads_enter() and friends, but I gather that the proper way to do that in gtkmm, is to use Glib::Dispatcher. I haven't used it before, but here is an example of it. However, you can also still use the C API with gtkmm, as pointed out here.