In this video, learn how to prevent a data race by adding a lock to the previous example Java program. Discover that by enforcing mutual exclusion in the critical section the program produces a deterministic result.
- [Instructor] To demonstrate how to manually enforce … mutual exclusion with locks in Java, … I'll modify the example program from earlier … with two shoppers that have a data race … as the concurrently increment the amount of garlic to buy. … First, I'll import the java.util.concurrent.locks package … into this program. … Then I'll create a new lock object within the shopper class … and because Olivia and I used the pencil, … I'll give it the creative name of pencil. … And I've declared it as a static variable … to make it a class variable. … In Java, the name, lock, is just an interface … for one of several variations of locks. … There's not actually a simple lock class, … so I'll need to use one of Java's actual concrete classes … and, for now, I'll choose to make it a reentrant lock … and I'll explain what makes that special in a later video. … Now, to keep my two threads from modifying … the shared garlic count variable at the same time, … I'll call the pencil's lock method … at the beginning of the run method …
- 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.