Thursday, July 11, 2013

Concurrency Pattern: Object Update (part 1)

Today we're going to talk about a Concurrent Pattern for modifying an object, that can be used when there is a single Writer thread and multiple Reader threads (Single-Write-Multiple-Readers). This is a series post where we will describe other more complex patterns which have seen and used in our code.
 
Suppose you have a class that has several member fields and you wish to modify all the fields in one shot (a single transaction) and that we define two simple operations, a Write operation (incrementMembers()) and a Read operation (sumMembers()):


class MyClass {
    int a;
    int b;
    int c;

    // This is a Write operation
    void incrementMembers() {
        a++;
        b++;
        c++;
    }

    // This is a Read operation
    int sumMembers() {
        return (a+b+c);
    }
}

Making each of the members be an atomic variable is not enough because, a Reader thread could jump in the middle of a Write operation and see an "inconsistent" state of the MyClass instance. For example, let's say that the only valid states are {a=1;b=1;c=1}, {a=2;b=2;c=2}, {a=3;b=3;c=3}... etc, and for example, the following state would be invalid {a=1;b=2;c=2}:


class MyClass {
    volatile int a;
    volatile int b;
    volatile int c;

    void incrementMembers() {
        a++;
        b++;
        c++;
    }

    int sumMembers() {
        return (a+b+c);
    }
}

The code above is "wrong" because making the members of MyClass atomic (or volatile in Java) would not suffice since a Reader thread could end up seeing an invalid state like {a=1;b=2;c=2} if there is an ongoing call of incrementMembers(), and return a value of 5 from sumMembers() which should not be possible.

The simplest solution to this problem is to wrap the access to each instance with a mutual exclusion lock, or better yet, with a Reader-Writer Lock so that multiple Readers may enter at the same time. The new code would look like this:


class MyClass {
    int a;
    int b;
    int c;
    ReentrantReadWriteLock rwlock;

    void incrementMembers() {
        rwlock.writeLock().lock();
        a++;
        b++;
        c++;
        rwlock.writeLock().unlock();
    }

    int sumMembers() {
        int sum = 0;
        rwlock.readLock().lock();
        sum = a+b+c;
        rwlock.readLock().unlock();
        return (sum);
    }
}

The problem with the RWLock approach is that it is Blocking.
So, how do we do it in a way that is non-blocking?

One way that is very fashionable amongst functional programmers is to make the contents of the class immutable, and whenever we need to change one (or several) of the members, we just make a copy of the entire instance:


class MyClass {
    final int a;
    final int b;
    final int c;

   MyClass(int a, int b, int c) {
       this.a = a;
       this.b = b;
       this.c = c;
    }

    MyClass incrementMembers() {
        return new MyClass(a+1, b+1, c+1);
    }

    int sumMembers() {
        return (a+b+c);
    }
}

Notice that incrementMembers() now returns a new instance of MyClass where all the members have been incremented by one.

This immutability technique has been used in many situations, but particularly in the context of Immutable data structures or sometimes also called Persistent data structures. See for example Scala's ImmutableTreeSet or Function Java's TreeMap:
http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.TreeSet
http://functionaljava.googlecode.com/svn/artifacts/3.0/javadoc/fj/data/TreeMap.html

Advantages:
- Non-Blocking (Wait-Free) operations (assuming a single Writer).
- Simple to implement

Disadvantages:
- Allows only a single Writer
- Needs a language with a Garbage Collector
- Slow for large objects
- Lots of churn on the GC
- Even with a single Writer thread it is not really Wait-Free for incrementMembers() because it does memory allocation. Will be realistically Lock-Free at best.


On the next post we will see a variation of this pattern that allows for multiple Writers.

Monday, July 1, 2013

Relaxed Atomics in Java

As surprising as you may find it, Java also supports relaxed atomics... kind of.
If you don't know what relaxed atomics are, then you can first watch this presentation from Herb Sutter "Atomic Weapons".

In case you don't want to watch the video, the summary of it is that Relaxed Atomics are a new feature in C11 and C++11 that comes as part of the new SC-DRF (Sequentially-Consistent for Data-Race-Free programs) Memory Model. They are useful to improve the performance on some concurrent algorithms and data-structures, particularly on non-x86 architectures.

Recently, memory barriers have been introduced in Java. To use them we need Unsafe which is not a very nice way to develop code (because the API can change at any time in the future), but ohhh well.

An interesting guarantee given by the JVM is that references and native types are always atomic, with the exception of long and double, for which no such guarantee is given. http://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html#jls-17.7
This may seem like a trivial matter, but it means that an int variable in Java will never have an intermediate state. To understand how important that is, just try to write a concurrent data structure.... or watch the video mentioned before.

Relaxed atomic operations can be done in Java by using a "regular variable" (except for long or double), and then using loadFence() or storeFence() when barriers are actually needed. The disadvantage of this approach is that it doesn't allow for CAS operations for longs.

Here is a comparison table that shows how different atomic operations can be done on Java and C11, including relaxed loads and stores:


Notice that we can't disable the barriers on volatile variables.
As you can see from the table above, the trick to get relaxed atomics in Java is to use sun.misc.Unsafe, namely:
Unsafe.fullFence()
Unsafe.loadFence()
Unsafe.storeFence()
Unsafe.compareAndSwapInt()
Unsafe.compareAndSwapObject()
Unsafe.compareAndSwapLong()
Unsafe.getAndAddInt()

More info on fences can be found here

To be accurate, C11 and C++11 allow for a much finer tuning of the kind of relaxed operations allowed. For example, we can have re-ordering of loads with stores, but not loads with loads, or other special cases, which in Java are not possible.
In practice, the only kind of relaxed atomics that we have felt the need for in our algorithms are the fully relaxed. For example, because we need the atomicity but we know that the barriers are not needed on a particular place in the code, because soon after there will be a release barrier or, there was an acquire-barrier just before.


One of the things that I've always admired in Java is the Memory-Model, but now with the new memory model in C11 and C++11 the developers of C/C++ have at their disposal a way of writing faster concurrent algorithms than Java developers can achieve, because of the lack of complete support for relaxed atomics.
Time will tell how important is this feature for the performance of concurrent algorithms in current and future CPU architectures, but my bet is on C11/C++11.

Anyways, when it comes to memory models, C11/C++11 has matched and went beyond Java.




Thursday, May 30, 2013

Queues just aren't scalable

Queues don't scale with the number of threads. Most of you that live in the land of multi-core programming know this already, but now it has been proven in this paper:
http://www.cs.bgu.ac.il/~hendlerd/papers/072646RRR.pdf
Notice that in the list of authors is included Nir Shavit, one of the co-authors of "The Art of Multiprocessor Programming" (so that's what he's been up to lately!).

For those of you not mathematically inclined (or don't feel like reading the 18 pages of it), here is my short interpretation of what this means:
These guys have proven that Queues have a time complexity that is at best of the order of the number of threads concurrently accessing the Queue, and if it wasn't enough, they proved it also for Stacks and a few other data-structures that have some implicit sequentiality.
What this means for us common mortals is, that even if someone discovers a fully Wait-free or Wait-Free Population-Oblivious Queue (assuming such a thing is possible), it will still have a performance that reduces proportionally to the number of threads adding/removing items in the queue, in other words, it will not be scalable.

So, Queues aren't scalable and they never will be... ever!

But don't despair, there is some hope hidden behind this. Namely, you can't have a Queue that is fully scalable, but it doesn't mean that all its operations are equally non-scalable.
Just like different methods in an algorithm may have different progress-condition guarantees, perhaps they may also have different time complexity. Assuming such a thing is possible, it could allow for the creation of a Queue that has constant time complexity for insertions, and quadratic or exponential time complexity for removals (or the other way around).

With a queue like that, you would be able to insert into the queue very quickly and have little or no impact on performance no matter how many threads would be inserting, but then doing the removal could take a substantial amount of time which would not improve with by adding more threads to do removals, and could in fact worsen.

What possible purpose could a queue like that serve? Well, in real-time systems it is usually desirable (or even needed) to handle a large number of events in a constraint amount of time, or some kind of similar bursty behavior. Imagine for example, a software process in a router that has a fixed time to read packets before more packets arrive and fill up the hardware queues, but as long as it is able to put these packets in a queue for later being processed by some other threads, it is ok.

Either someone will prove such a thing is not possible, or someone will come up with a Queue with these kind of proprieties, until then, whenever your application gives crappy scalability, just blame it on the queues   :)


Tuesday, May 21, 2013

How to micro-benchmark concurrent data structures?

One of the issues with benchmarking of concurrent algorithms is to choose the right distribution of tasks among the threads.

For many of our tests we used equal-capability threads where each thread can either be doing a Read operation or a Write operation according to some probability (like for example: 50%, 10%, or 0.1% Writes).
This is fine for testing Blocking algorithms like Locks or lock-based data structure, but for data structures with Wait-Free capabilities it just doesn't work.
The reason is that, when we use the equal-capability threads approach there is an implicit dependency between the Reads and the Writes, and eventually we can (and will) end up with all Reads finished and only threads attempting to Write are waiting, or maybe the other way around, depending on whether there is some kind of reader-preference or writer-preference. Either way, we create a "blocking" dependency between the two kinds of operations, which can bias the micro-benchmark results significantly.
Here is a schematic that shows what the issue looks like:


In this example we have threes threads each doing 50% Writes (one Read operation, followed by one Write operation, followed by another Read, and so on).
Most of the time of each thread is spent waiting for the Write to finish because this is usually slowest operation. This shows that in practice we are "blocking" the Read operations, even if they are Wait-Free because each thread will not be able to progress to the following Read until it does a Write, thus causing a blocking dependency.


The solution is to use dedicated threads: some threads are Writers, and the remaining threads are Readers.
This way there is no blocking of the tasks of reading and writing to the data structure, and as many as can be executed will be. It has the added advantage that you get to test as well the "fairness" of the data structure when concurrent Reads and Writes are done.

We are currently finishing up a paper on a concurrent pattern which we call the "Left-Right pattern", and it has the property that Writes are Blocking and Reads are Wait-Free Population-Oblivious. With this kind of guarantees, we decided to make tests where we run one or two Writer threads, and all the other threads are Readers.
The reasoning behind it is that choosing two writer threads makes sure that at any given time there is at least a Writer waiting to execute, and then adding Reader threads will show how it scales under Read operations. This is a good test of the overall "fairness" of the data structure under high-contention. A "fair" data structure should provide proportional or constant performance for each of the operations (whether they are Writes or Reads) as we scale one of the others, in the case of our "Left-Right pattern", we scale up the number of Reader threads and check how the number of Write operations changes as a function of number of Readers.



In conclusion, mixed-task threads are fine for testing Blocking data structures, but for the ones with Wait-Free proprieties, it is better to use threads with dedicated tasks, in order to avoid blocking dependencies between the tasks in the test framework itself.