2 ms·
I think that it is universal advice for libraries: do not do multithreading inside, let the client code do it and/or pass necessary constructs. Simple example
by galkk 7y ago
I think that it is universal advice for libraries: do not do multithreading inside, let the client code do it and/or pass necessary constructs.
Simple example for Java: do not create executorservice instances inside of a library, but allow client code to pass them.
Ayende wrote much better than me long time ago
https://ayende.com/blog/159201/multi-threaded-design-guidelines-for-libraries-part-i https://ayende.com/blog/159201/multi-threaded-design-guideli...
- jillesvangurp 7y agoI think what Kotlin is doing with co-routines improves a bit on this. The approach there is to make asynchronous code look (almost) like normal code. The only difference is that 1) you are dealing with functions that are marked as suspend and 2) you can only call these from a co-routine scope. The last bit is the crucial thing. The co-routine scope is how you structure concurrency and is something I have not really seen in other approaches. In a mobile application you have the main thread, IO threads, and maybe some CPU threads. When calling something that is asynchronous, you have to assign it a scope. When that scope ends (because of a timeout, error, etc.) there's a cleanup step that cancels all the dangling tasks. The nice thing about this is that you get clean separation of how to structure your concurrency and the logic. They also made it very easy to integrate with existing asynchronous code (there are a lot of frameworks for this in Java).
- hn_mattfreeman 7y agoKotlin's approach is extremely nice, not perfect but nice, for example most of Kotlins collection operations are inline so functions like mapIndexed etc.. you can call a suspend function even though mapIndexed is agnostic (by nature of just a ~template) as long as your in a co-routine scope of course, I don't often call suspending operations in collection operations but the inline fun approach well in other areas (your own code). Other languages don't have this - Javascript for example map/filter/reduce won't await if you return a Promise. C# would need specialized Task aware version of the Linq stuff (they probably already exist). The scope tree thing is really nice too once you get your head around it, much nicer than in c# with carrying cancellationtokens around and creating your own cancellationsource when you need something like a supervisor scope.