Book Image

Programming Kotlin

Book Image

Programming Kotlin

Overview of this book

Quickly learn the fundamentals of the Kotlin language and see it in action on the web. Easy to follow and covering the full set of programming features, this book will get you fluent in Kotlin for Android.
Table of Contents (20 chapters)
Programming Kotlin
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Customer Feedback
Preface

Race conditions


A race condition is another type of concurrency bug that occurs when two or more threads access shared data and try to change it at the same time. This means a situation where the output of a piece of logic requires that interleaved code is run in a particular order -- an order that cannot be guaranteed.

A classic example is of a bank account, where one thread is crediting the account and another is debiting the account. An account operation requires us to retrieve the value, update it, and set it back, which means the ordering of these instructions can interleave with each other.

For example, assume an account starts with $100. Then, we want to credit $50 and debit $100. One possible ordering of the instructions can be something like this:

<credit thread>

<account balance>

<debit thread>

start value = 100

get current balance = 100

get current balance = 100

set new balance = 100 + 50

Updated = 150

set new balance = 100 - 100

Updated...