I'm looking for a naming convention for thread safe functions, meaning functions that can be called safely from multiple threads. But suppose I use :
void FooThreadSafe();
In your mind, do you think that :
This function will use locking mechanism and is safe to call concurrently ?
Or
This function can be called ONLY in a thread safe context ?
To me it's the first option, but many people think it's the second option. So I'm looking for a way to make it clear that you don't have to lock to call the function. Any idea ?
Thanks,
Noisetier
Java uses Atomic or Concurrent as prefix.
For example AtomicReference<>, ConcurrentHashMap<>.
Related
I'd read a lot of the many adventages of using coroutines, but I find nothing about why you shouldn't or couldn't use them.
Why not use all methods as suspend methods, by the way?
I'm having some trouble to understand some concepts here, so with my question I pretend to make the opposite case (why not use it), so I can understand better by contrast.
The main reason not to have all functions suspendable is the overhead they introduce, at least on the JVM. Every suspendable function compiles into a Java method that receives another parameter, the continuation object, and its body compiles into pretty complex state machine code that, among other things, always instantiates another continuation object and daisy-chains it to the one received as the parameter.
So, whenever you have nothing to gain from coroutines, you shouldn't use them as the default way to do things.
Please see my answers inline to your questions:
but I find nothing about why you shouldn't or couldn't use them.
Answer:
a. You should not use them for any foreground task.
b. You should not use them for any simple/real quick operations.
c. You should not use them for any kind of initialization.
Why not use all methods as suspend methods, by the way?
Answer:
a) This will be treated as code smell. Bad practice to do so.
b) If you mark all functions as suspend, then whenever you want to call a suspend function you will have to create a Coroutine Scope to run it.
c) Testing of suspend function is difficult. It needs some additional setup of RunBlockingTest from AndroidX.
The title states my question.
What is exactly the reason why CoroutineScope.launch and Coroutine.async are just extension functions of CoroutineScope instead oa a member function?
What benefits does it provide?
I am asking because maybe the reason behind this design could be helpful in designing things in the future too.
Thank in advance.
Mostly because with extension functions it is easier to structure your code in multiple modules even if it is represented as one class.
CoroutineScope is actually a really good example of this design pattern. Take a look at CoroutineScope.kt where the interface is declared. There is only basic functionality there (plus operator and cancel())
The two functions you mentioned are defined in Builders.common.kt. If You take a look at the contents of this file, you can see that there are multiple classes which are private, this means they can only be used in this file. This tells you right away that you don't need this these classes for the basic functionality which is designed in CoroutineScope.kt, they are only there for launch {...} and async {...}
So if you have a large class with multiple functionality, it makes sense to break it up in multiple files (=modules).
launch and async are coroutine builders, but they aren't the only ones: look in integration modules for future (and another future), publish, the RxJava 2 builders etc. Obviously those can't be members of CoroutineScope, so why should launch and async be?
In addition, by being extension functions you know they don't rely on any CoroutineScope privates (well, they could rely on internals since they are in the same module).
The kotlinx.coroutines uses structural concurrency approach to make sure all errors are propagated to a parent coroutine. Similarly, a parent coroutine will by default wait for all it's child coroutines to complete.
There is a Job object associated with every coroutine when you do launch or async. It is just easier to use extension functions for that design to make it work implicitly, without a code-writer explicit attention
You may have a look at the more detailed explanation :
https://kotlinlang.org/docs/reference/coroutines/basics.html#structured-concurrency
https://medium.com/#elizarov/structured-concurrency-722d765aa952
In objective-c when you are implementing a method that is going to perform a repetitive operations, for example, you need to choice in between the several options that the language brings you:
#interface FancyMutableCollection : NSObject { }
-(void)sortUsingSelector:(SEL)comparator;
// or ...
-(void)sortUsingComparator:(NSComparator)cmptr;
#end
I was wondering which one is better?
Objective-c provides many options: selectors, blocks, pointers to functions, instances of a class that conforms a protocol, etc.
Some times the choice is clear, because only one method suits your needs, but what about the rest? I don't expect this to be just a matter of fashion.
Are there any rules to know when to use selectors and when to use blocks?
The main difference I can think of is that with blocks, they act like closures so they capture all of the variables in the scope around them. This is good for when you already have the variables there and don't want to create an instance variable just to hold that variable temporarily so that the action selector can access it when it is run.
With relation to collections, blocks have the added ability to be run concurrently if there are multiple cores in the system. Currently in the iPhone there isn't, but the iPad 2 does have it and it is probable that future iPhone models will have multiple cores. Using blocks, in this case, would allow your app to scale automatically in the future.
In some cases, blocks are just easier to read as well because the callback code is right next to the code that's calling it back. This is not always the case of course, but when sometimes it does simply make the code easier to read.
Sorry to refer you to the documentation, but for a more comprehensive overview of the pros/cons of blocks, take a look at this page.
As Apple puts it:
Blocks represent typically small, self-contained pieces of code. As such, they’re particularly useful as a means of encapsulating units of work that may be executed concurrently, or over items in a collection, or as a callback when another operation has finished.
Blocks are a useful alternative to traditional callback functions for two main reasons:
They allow you to write code at the point of invocation that is executed later in the context of the method implementation.
Blocks are thus often parameters of framework methods.
They allow access to local variables.
Rather than using callbacks requiring a data structure that embodies all the contextual information you need to perform an operation, you simply access local variables directly.
On this page
The one that's better is whichever one works better in the situation at hand. If your objects all implement a comparison selector that supports the ordering you want, use that. If not, a block will probably be easier.
I'm wondering whether prepared statements in Android (instances of SQLiteStatement) are thread-safe. In particular I'm asking with regard to the following scenario:
In a ContentProvider you create a pre-compiled insert statement during onCreate. Then, in the overriden insert method you make use of this statement by binding a set of parameters to it and calling executeInsert on it.
We know that a ContentProvider has to be written in a thread-safe manner. If SQLiteStatement does not bind parameters per thread, a concurrent call to the provider's insert method would alter the statement's bindings and result in unpredictable behavior.
Android's own Contacts provider uses prepared statements in this way (http://bit.ly/bDuKAT), so I tend to believe that they are in fact thread-safe. Looking at the source code of SQLiteStatement I don't see how though (http://bit.ly/9M1Swv).
So, is SQLiteStatement (or SQLiteProgram that is) thread-safe with respect to parameter binding or not?
It is explicitly stated in the SQLiteStatement documentation that
SQLiteStatement is not internally synchronized
Thus, the class is not thread-safe and cannot be used by multiple threads concurrently without unexpected results.
If it's two separate methods, then it can't possibly be thread-safe:
mStatusUpdateDelete.bindLong(1, dataId);
mStatusUpdateDelete.execute();
The first thread could call bindLong with 1, then the second thread with 2, and then both threads could call execute. So even if bindLong and execute internally are thread safe, it wouldn't help.
Not during instantiation, but once instantiation of singleton object is done, what will happen if two or more threads are trying to access the same singleton object? Especially in the case where the singleton object takes lot of time to process the request (say 1 min)... In this case, if for ex., 5 threads try to access the same singleton object, what will the result be?
Additional question: normally when should we go for the singleton pattern and when should we avoid it?
Unless synchronization (locking) is being performed within the Singleton, the answer is this: it's a free-for-all.
Though the Singleton ensures that only one instance of an object is used when requested, the pattern itself doesn't inherently provide any form of thread safety. This is left up to the implementer.
In the specific case you cited (with a long running method), it would be critical to synchronize access to any method that uses class or object-level variables. Failure to do so would, in all likelihood, lead to race conditions.
Good luck!
The general rule of thumb i use for Singletons is that it should not affect the running code, and have no side-effects. Essentially for me, in my projects this translates into some kind of logging functionality, or static value lookup (ie. loading some common data from a database once and storing it for reference so it doesn't have to be read in everytime its needed).
A singleton is no different than any other object other than there is only one instance. What happens when you try to access it will largely depend on what the accessing threads are attempting (ie read vs write) and what kind of data your singleton is holding.
The answer to your question as it is, is "it really depends". What kind of singleton? i.e. what does it do, and how does it do it? And in what language?
The reality is that the singleton patter)n only dictates and enforces that you can only have one instance of a certain object. In of itself it does not say anything about multiple threads accessing that object.
So, if coded right (with thread synchronization implemented correctly) there is no reason why it shouldn't behave correctly - even if the requests to the object take a really long time to process!
Then you need thread safe implementation of singleton pattern.
Find this article useful for the same which describes most of the multi-threading scenario of singleton pattern.
HTH!