From the course: Parallel and Concurrent Programming with Java 1
Unlock the full course today
Join today to access over 22,600 courses taught by industry experts or purchase this course individually.
Read-write lock: Java demo - Java Tutorial
From the course: Parallel and Concurrent Programming with Java 1
Read-write lock: Java demo
- [Instructor] To demonstrate using read/write locks in Java, I've created this example program in which 10 threads are reading what day it is from a shared calendar, while two other threads concurrently change the date. The CalendarUser class has a constant array of strings to represent the days of the week, on line nine, as well as an integer to indicate which day today is. In the reentrant log named marker, which will act as our mutex to control access as threads read and change the value of the today variable. Down in the CalendarUsers run method, inside of the while loop on line 18, I'll execute one of two cases, depending on whether the name I assign this CalendarUser object indicates that it's a reader or a writer. The if statement on line 19 checks to see if this CalendarUser is a writer thread, and, if so, the thread will acquire the marker.lock, change the calendar to the next day, on line 22, it prints a message about doing so, and then, finally, it unlocks the marker on…
Practice while you learn with exercise files
Download the files the instructor uses to teach the course. Follow along and learn by watching, listening and practicing.