Are volatile variable ‘reads’ as fast as normal reads?

You should really check out this article: http://brooker.co.za/blog/2012/09/10/volatile.html. The blog article argues volatile reads can be a lot slower (also for x86) than non-volatile reads on x86. Test 1 is a parallel read and write to a non-volatile variable. There is no visibility mechanism and the results of the reads are potentially stale. Test 2 … Read more

Throttling CPU/Memory usage of a Thread in Java?

If I understand your problem, one way would be to adaptively sleep the threads, similarly as video playback is done in Java. If you know you want 50% core utilization, the your algorithm should sleep approximately 0.5 seconds – potentially distributed within a second (e.g. 0.25 sec computation, 0.25 sec sleep, e.t.c.). Here is an … Read more

Does posting Runnable to an UI thread guarantee that layout is finished when it is run?

I like the question too. It forced me to dig into Android source code once again. I believe this works because post() gets called after setContentView(). Method setContentView() ends up in calling ViewGroup.addView() of the top view, and addView() call always triggers requestLayout(). In turn, requestLayout() posts a task to the main thread to be … Read more

Read Locks and Write Locks

In database management theory, locking is used to implement isolation among multiple database users txn. This is the “I” in the acronym ACID (Atomicity, Consistency, Isolation, Durability). Locks are applied by a TX (transaction) to data, which may block other TXs from accessing the same data during the TX’s life. Simple Locking: Two main types … Read more

Do I need to lock or mark as volatile when accessing a simple boolean flag in C#?

Firstly, threading is tricky ;-p Yes, despite all the rumours to the contrary, it is required to either use lock or volatile (but not both) when accessing a bool from multiple threads. For simple types and access such as an exit flag (bool), then volatile is sufficient – this ensures that threads don’t cache the … Read more

std::map thread-safety

The C++11 standard guarantees that const method access to containers is safe from different threads (ie, both use const methods). In addition, [container.requirements.dataraces] states implementations are required to avoid data races when the contents of the contained object in different elements in the same sequence, excepting vector<bool> In other words, except for vector<bool> modifying distinct … Read more