Skip to content

Commit 01dce9c

Browse files
lechtenMax-Hailperin
authored andcommitted
Explain synchronizedList (#119)
1 parent 370610d commit 01dce9c

1 file changed

Lines changed: 14 additions & 4 deletions

File tree

synchronization.tex

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1438,16 +1438,26 @@ \section{Semaphores}\label{semaphores-section}
14381438
condition variables.
14391439

14401440
In order to show semaphores in the best possible light, I also moved
1441-
away from using an array to store the buffer. Instead, I used a
1442-
\texttt{List}, provided by the Java API. If, in Programming Project~\ref{semaphore-array-bb-project}, you try rewriting
1441+
away from using an array to store the buffer. Instead, I used the
1442+
method \verb|synchronizedList| to create a thread-safe list for the
1443+
buffer. Behind the scenes, Java's monitor mechanism with
1444+
\verb|synchronized| (which was explained in
1445+
Section~\ref{monitors-section}) ensures mutual exclusion for methods
1446+
on the resulting list; in particular, \verb|add| and \verb|remove| are
1447+
executed under mutual exclusion on the shared buffer to prevent races
1448+
that could otherwise lead to corruption of the buffer's underlying
1449+
data structure.
1450+
If, in Programming Project~\ref{semaphore-array-bb-project}, you try rewriting
14431451
this example to use an array (as in Figure~\ref{BoundedBuffer.java}),
14441452
you will discover two blemishes. First, you will need the
1445-
\verb|numOccupied| integer variable, as in Figure~\ref{BoundedBuffer.java}. This duplicates the information contained in
1453+
\verb|numOccupied| integer variable, as in Figure~\ref{BoundedBuffer.java}.
1454+
This duplicates the information contained in
14461455
\verb|occupiedSem|, simply in a different form. Second, you will need
14471456
to introduce explicit mutex synchronization with \verb|synchronized|
14481457
statements around the code that updates the nonsemaphore state
14491458
variables. With those complications, semaphores lose some of their
1450-
charm. However, by using a \texttt{List}, I hid the extra complexity.
1459+
charm. However, by using a thread-safe list, I hid the extra
1460+
complexity.
14511461

14521462
\section{Deadlock}\label{deadlock-section}
14531463

0 commit comments

Comments
 (0)