Binary and Counting Semaphores in Java

Опубликовано: 04 Июнь 2026
на канале: Merlin Wellington
331
9

Binary and counting semaphores allow threads to signal each other to share data safely. Java has built in abilities to do use both of these techniques. Any object can be a binary semaphore and we can use that to signal binary conditions like "Queue full". Using this feature requires synchronizing on the object and there is a risk of spurious wake up that we have to be careful about. For counting semaphores, Java gives us the Semaphore class that allows much richer signaling capabilities. In this video, I show both of those techniques and how we combine them with synchronize blocks to prevent race conditions in various Producer/Consumer scenarios.


TIMESTAMPS
0:00 Introduction
0:19 Binary Semaphores
0:58 Shared Queue Example
1:18 Synchronizing on the semaphore object
2:03 Notifies When No One is Waiting
2:39 Spurious Wakeup
3:17 Counting Semaphores
4:07 Ping Pong Example of Alternating Threads
5:48 Producer/Consumer Problem
6:12 One Producer and One Consumer
6:28 One Producer and Multiple Consumers
7:32 Producer Code
8:34 Consumer Code


ABOUT MY CHANNEL
My channel is about good software engineering practices. We cover introductions to programming in C and Java. But I also have lots of software and computer engineering topics like PIC programming, advanced programming techniques, and things that distinguish good code from code that works.

Check out our channel here:
   / @wizardcraftcode  

Don’t forget to like and subscribe!

CHECK OUT MY OTHER VIDEOS:

C Programming Playlist:    • Coding in C  
Intro to Java Playlist:    • Introduction to Java Programming based on ...  
Software Engineering Topics Playlist:    • General Software Engineering Topics