In this video, learn about a data race between two concurrent threads incrementing a shared counter variable with an example Java program. Discover that the data race is inconsistent and may not always occur, which can make it difficult to identify and debug.
- [Instructor] To demonstrate a data race in Java, … I've created this simple program … that uses two threads … to concurrently increment a shared counter variable. … The Shopper class on line five extends Thread … and will be used to represent one of two shoppers. … Olivia or me. … The static class variable on line seven … is a counter for the amount of garlic we should buy … and it gets initialized to zero. … Within the thread's run method on line nine, … I simply use a for loop … to increment that garlicCount variable … ten times. … Down in the program's main method … on lines 17 through 22, … I create two shopper threads … called barron and olivia; … start them both … and then used the join method … to wait until they're both done. … Finally, I print out the value … of the garlicCount class variable on line 23, … indicating how much garlic we should buy. … When I run this program, … it tells me that we should buy 20 garlic. … And that makes sense. … I have two threads here … that are each adding 10 garlic to the counter. …
- Parallel vs. sequential computing
- Shared vs. distributed memory
- Execution scheduling
- Thread lifecycle
- Mutual exclusion
- Synchronized methods
- Checking for liveness
Skill Level Advanced
Java Essential Training: Objects and APIswith David Gassner2h 46m Intermediate
Java Essential Training: Syntax and Structurewith David Gassner3h 9m Intermediate
1. Parallel Computing Hardware
2. Threads and Processes
3. Mutual Exclusion
- Mark as unwatched
- Mark all as unwatched
Are you sure you want to mark all the videos in this course as unwatched?
This will not affect your course history, your reports, or your certificates of completion for this course.Cancel
Take notes with your new membership!
Type in the entry box, then click Enter to save your note.
1:30Press on any video thumbnail to jump immediately to the timecode shown.
Notes are saved with you account but can also be exported as plain text, MS Word, PDF, Google Doc, or Evernote.