Latest / CyberSecurity Summary / Java 9 Concurrency Cookbook
Transcript
- 0:00Speaker 1: Every time you run a Java app that you know,
- 0:02Speaker 1: pulls data from a network, updates a user interface, and
- 0:05Speaker 1: writes to a database, all at the exact same time.
- 0:08Speaker 1: You're relying on this this incredibly high stakes traffic control system,
- 0:14Speaker 1: and it's operating at the microsecond.
- 0:16Speaker 2: Level, right, Yeah, it's happening so fast we just completely
- 0:19Speaker 2: ignore it exactly.
- 0:21Speaker 1: So today we are diving straight into the rulebook for
- 0:24Speaker 1: that infrastructure. We're looking at excerpts from the Java nine
- 0:27Speaker 1: Concurrency Cookbook by Javier Fernandez Gonzales.
- 0:31Speaker 2: Which is a fantastic resource by the way.
- 0:34Speaker 1: Oh. Absolutely. The mission for this deep dive is to
- 0:37Speaker 1: extract those core aha moments about multitasking and code. We
- 0:41Speaker 1: want to understand how systems share resources, prevent deadlocks, and
- 0:45Speaker 1: you know, avoid just totally corrupting data when thousands of
- 0:48Speaker 1: operations collide.
- 0:50Speaker 2: It really is a complex logistical operation. I mean, we
- 0:52Speaker 2: just take for granted that a background thread downloading a
- 0:55Speaker 2: file isn't going to somehow you know, overwrite the memory
- 0:59Speaker 2: space being used by the front end interface.
- 1:01Speaker 1: Yeah, that would be a disaster.
- 1:02Speaker 2: Total disaster. So understanding how it all works requires breaking
- 1:07Speaker 2: down how the operating system and the Java virtual machine
- 1:11Speaker 2: actually manage execution behind the scenes.
- 1:14Speaker 1: Right, And I think that starts with distinguishing between the
- 1:16Speaker 1: illusion of simultaneous execution and well, actual simultaneous execution.
- 1:21Speaker 2: Concurrency versus parallelism.
- 1:23Speaker 1: Exactly because in an older single core processor, the system
- 1:27Speaker 1: is executing concurrently, but it's not actually parallel. It's time slicing.
- 1:31Speaker 2: Yeah, it's a NAT trick.
- 1:33Speaker 1: It is. The OS scheduler is pulling one task onto
- 1:35Speaker 1: the CPU, letting it run for a tiny fraction of
- 1:38Speaker 1: a millisecond, saving its state, and then swapping in the
- 1:41Speaker 1: next task.
- 1:41Speaker 2: And that context switching happens so incredibly fast that human
- 1:45Speaker 2: perception just registers it as simultaneous. You think it's happening
- 1:48Speaker 2: at the same time, but it's not.
- 1:49Speaker 1: Okay, let's unpack this for a second. It's kind of
- 1:51Speaker 1: like a chef in a kitchen. Concurrency is one chef
- 1:56Speaker 1: rapidly switching between chopping onions and stirring soup like chopster chopster,
- 2:00Speaker 1: But parallelism is having two separate chefs.
- 2:02Speaker 2: That's a great way to look at it. Because parallelism
- 2:05Speaker 2: strictly requires a multicore architecture, you have multiple execution pipelines
- 2:11Speaker 2: physically processing different instructions at the exact same.
- 2:14Speaker 1: Clock cycle two actual chefs, right.
- 2:17Speaker 2: But regardless of whether the hardware is single core or multicore,
- 2:21Speaker 2: the software unit of execution within a Java process is the.
- 2:25Speaker 1: Thread, and the source material really breaks down the fixed
- 2:27Speaker 1: attributes of these threads, like you've got an immutable ID,
- 2:31Speaker 1: a name, a status, and a priority level from one to.
- 2:33Speaker 2: Ten, which is where a lot of people get tripped up.
- 2:35Speaker 1: Oh for sure, because my immediate instinct as a developer,
- 2:39Speaker 1: if I'm trying to optimize a critical path is to
- 2:41Speaker 1: just assign my most important thread a priority of ten
- 2:44Speaker 1: and assume it'll preempt everything else.
- 2:46Speaker 2: That is such a common assumption. But what's fascinating here
- 2:50Speaker 2: is that the Java priority system is essentially just a hint.
- 2:53Speaker 1: Wait, just a hint, Like it doesn't force it.
- 2:55Speaker 2: Not at all. You are basically signaling to the underlying
- 2:59Speaker 2: operating system, whether that's Linux, Windows, Mac, OS, whatever, that
- 3:03Speaker 2: you'd prefer this thread to get more CPU time.
- 3:06Speaker 1: Ah I see.
- 3:07Speaker 2: However, the OS scheduler operates on its own internal algorithms.
- 3:12Speaker 2: It has to balance your applications threads against system level processes,
- 3:16Speaker 2: network interrupts, UI responsiveness.
- 3:19Speaker 1: So it could just ignore my Priority ten completely.
- 3:22Speaker 2: Yep, it might throttle your priority ten thread if it
- 3:25Speaker 2: detects that a Priority five thread has been starved of
- 3:28Speaker 2: CPU cycles for too long. It's a recommendation, not an
- 3:32Speaker 2: absolute mandate.
- 3:33Speaker 1: That makes a lot of sense. Actually, the OS has
- 3:35Speaker 1: to prioritize system stability over one specific Java apps request exactly,
- 3:40Speaker 1: So we also need to look at how these threads
- 3:42Speaker 1: are managed in their life cycle. The source outlines six states.
- 3:46Speaker 1: You've got new, runnable, blocked, waiting, timed, waiting, and terminated.
- 3:51Speaker 2: And the distinction that seems most critical for performance tuning,
- 3:54Speaker 2: especially when things go wrong, is between blocked.
- 3:57Speaker 1: And waiting, because both mean the thread is an executing right,
- 4:00Speaker 1: but the mechanical reasons are different.
- 4:02Speaker 2: Yeah, totally different, And this distinction dictates how you debug
- 4:05Speaker 2: a bottleneck. A thread enters the block state entirely against
- 4:09Speaker 2: its will.
- 4:10Speaker 1: Like it hit a wall exactly.
- 4:12Speaker 2: It needs to access a memory space or a block
- 4:14Speaker 2: of code that is currently locked by another thread, so
- 4:18Speaker 2: it just has to sit in the queue, burning no
- 4:20Speaker 2: CPU cycles, just waiting for the OS to wake it
- 4:23Speaker 2: up when the lock is finally released.
- 4:25Speaker 1: But waiting is different.
- 4:27Speaker 2: Waiting is a cooperative state. A thread intentionally puts itself
- 4:31Speaker 2: into a waiting state because it's reached a point where
- 4:34Speaker 2: it literally cannot proceed until a specific condition.
- 4:37Speaker 1: Is met, like waiting for data to arrive over a
- 4:40Speaker 1: network socket.
- 4:41Speaker 2: Spot on. Yeah, and it will only wake up when
- 4:43Speaker 2: another thread sends it a deliberate signal.
- 4:45Speaker 1: Which brings up the broader concept of thread cooperation, which
- 4:49Speaker 1: I find super interesting, especially when it comes to shutting
- 4:52Speaker 1: them down.
- 4:52Speaker 2: Oh yeah, thread termination is.
- 4:54Speaker 1: Tricky because to start a thread you just explicitly call
- 4:57Speaker 1: the start method. Easy. But stop them. You don't just
- 5:00Speaker 1: kill a thread. You call interrupt, right.
- 5:02Speaker 2: Which just sets a boolean flag on the thread.
- 5:04Speaker 1: Yeah, the thread itself has to actively check this is
- 5:08Speaker 1: interrupted flag, and if it's true, it throws an interrupted exception.
- 5:11Speaker 1: So my question is, if a thread is stuck in
- 5:14Speaker 1: an infinite loop, why not just have the JVM ruthlessly
- 5:18Speaker 1: terminate the OS thread?
- 5:19Speaker 2: Like?
- 5:20Speaker 1: Why ask politely?
- 5:21Speaker 2: Because ruthless termination at the OS level leads the application
- 5:25Speaker 2: in an unpredictable, often completely corrupted state.
- 5:29Speaker 1: Okay, corrupted?
- 5:30Speaker 2: How well? Imagine a thread is midway through a complex
- 5:33Speaker 2: database transaction, or it's currently holding a critical lock on
- 5:37Speaker 2: some shared memory. If the JVM just kills it instantly,
- 5:41Speaker 2: that lock is never released.
- 5:42Speaker 1: Oh wow, so any other thread waiting for that lock
- 5:45Speaker 1: is now permanently blocked forever.
- 5:47Speaker 2: It's a disaster. By using the interruption mechanism, you force
- 5:51Speaker 2: the thread to catch the exception, execute its finely blocks,
- 5:54Speaker 2: close open file descriptors, roll back incomplete transactions, release its locks,
- 5:58Speaker 2: and then exit the execution stack cleanly.
- 6:00Speaker 1: Okay, so it's a highly controlled shutdown protocol to protect
- 6:03Speaker 1: the memory state. That makes perfect sense. But there is
- 6:05Speaker 1: an exception to how the JVM handles thread life cycles. Right.
- 6:09Speaker 1: Demon threads, ah yeah.
- 6:11Speaker 2: Demon threads operate under a totally different set of rules.
- 6:14Speaker 1: They're strictly background service providers. The classic example in the
- 6:18Speaker 1: text is a cleaner task that just runs in an
- 6:20Speaker 1: infinite loop, sweeping a queue and deleting events older than
- 6:24Speaker 1: ten seconds.
- 6:25Speaker 2: Right, And because it's an infinite loop, you'd think it
- 6:27Speaker 2: would keep the application running forever.
- 6:29Speaker 1: But if it's flagged as a demon thread, the JVM
- 6:33Speaker 1: just doesn't care. Once all the primary user threads have
- 6:37Speaker 1: finished their work and terminated, the JVM will just abruptly
- 6:40Speaker 1: halt and exit, taking the demon threads down with it.
- 6:43Speaker 2: Yeah, their existence is only justified by the presence of
- 6:46Speaker 2: user threads. Once the user threads are gone, the JVM
- 6:50Speaker 2: doesn't wait for demon threads to reach a clean state.
- 6:52Speaker 2: It just initiates the shutdown sequence immediately.
- 6:55Speaker 1: Okay, so we've got all these user threads and demon
- 6:58Speaker 1: threads executing concurrently, constantly being swapped in and out by
- 7:01Speaker 1: the OS scheduler. This leads directly to the core problem
- 7:05Speaker 1: of concurrency, which is shared resources and race.
- 7:08Speaker 2: Conditions the danger zone.
- 7:10Speaker 1: Yes, the source uses this parking garage simulation that I love.
- 7:14Speaker 1: So imagine we have sensors at different gates tracking vehicles entering,
- 7:18Speaker 1: and they are all updating a single short variable called cash.
- 7:21Speaker 2: Right to track the money. And to understand why this
- 7:24Speaker 2: fails without concurrency controls, you have to look at what
- 7:27Speaker 2: happens beneath the Java code.
- 7:29Speaker 1: Because a simple operation like cash equals cash plus two
- 7:32Speaker 1: is not a single atomic instruction for the CPU, is it.
- 7:36Speaker 2: No, not at all. It's a multi step process. At
- 7:38Speaker 2: the hardware level. The CPU has to fetch the current
- 7:41Speaker 2: value of cash from main memory into a local CPU register,
- 7:45Speaker 2: then it increments the value in that register.
- 7:48Speaker 1: And then Finally, it writes that updated value back to
- 7:51Speaker 1: main memory.
- 7:52Speaker 2: Exactly, and that multi step reality is where the race
- 7:55Speaker 2: condition lives.
- 7:55Speaker 1: Okay, wap me through it all right.
- 7:57Speaker 2: Imagine sensor A and censor B both detect a car
- 8:01Speaker 2: at nearly the exact same microsecond. The OS scheduler gives
- 8:04Speaker 2: censor A a time slice. It fetches the cash value
- 8:07Speaker 2: let's say it's one hundred dollars into its register. Right,
- 8:09Speaker 2: but before it can increment and write back it's time
- 8:12Speaker 2: slice expires, a context switch happens.
- 8:15Speaker 1: Oh man, So the OS saves censor a's state and
- 8:19Speaker 1: swaps in censor B.
- 8:20Speaker 2: Yep, and censor B fetches the cash value, which is
- 8:23Speaker 2: still one hundred in main memory because sensor A never
- 8:26Speaker 2: updated it sinceor B increments it to one oh two
- 8:29Speaker 2: and writes it back.
- 8:30Speaker 1: Okay, so main memory is now one hundred and two.
- 8:32Speaker 2: Right, then another context switch happens. Sensor A resumes exactly
- 8:36Speaker 2: where it left off, with one hundred in its local register.
- 8:39Speaker 1: Oh no, so it increments one hundred and two and
- 8:41Speaker 1: writes one hundred and two back to.
- 8:43Speaker 2: Main memory, completely overwriting censor b's work. You just lost
- 8:46Speaker 2: two dollars.
- 8:47Speaker 1: That is wild the book actually stimulates eight sensors processing
- 8:51Speaker 1: thirty vehicles each at two dollars vehicle. The mathematical certainty
- 8:55Speaker 1: is four hundred and eighty dollars.
- 8:56Speaker 2: But because of those inner leaved hardware instructions, running it
- 8:59Speaker 2: without rules give you four hundred and fifty eight or
- 9:02Speaker 2: four sixty two, you're just silently losing data.
- 9:04Speaker 1: And imagine if this wasn't a parking garage but your
- 9:07Speaker 1: bank account processing simultaneous deposits and withdrawals.
- 9:10Speaker 2: Yeah, that's when it stops being a fun simulation and
- 9:12Speaker 2: becomes a massive liability.
- 9:13Speaker 1: Seriously. So, the fundamental fixed Java provides for this is
- 9:17Speaker 1: the synchronized keyword. It turns a block of code into
- 9:21Speaker 1: a critical section. You use an object reference like usually.
- 9:24Speaker 2: This as a monitor lock, right, like a key to
- 9:26Speaker 2: a room.
- 9:27Speaker 1: Exactly, if a thread wants to execute that code, it
- 9:30Speaker 1: must acquire the lock. If it has the lock, no
- 9:33Speaker 1: other thread can enter. It forces that multi step fetch
- 9:37Speaker 1: increment right process to happen atomically.
- 9:40Speaker 2: Which is great. It resolves the data corruption. Correctness always
- 9:43Speaker 2: has to be prioritized over performance. But and this is
- 9:47Speaker 2: a big but, it introduces a severe performance penalty.
- 9:50Speaker 1: Right because synchronized is such a blunt instrument, very blunt.
- 9:54Speaker 2: When you use it, you're using a very rigid, mutually
- 9:56Speaker 2: exclusive lock. If you have ten threads hitting that method,
- 9:59Speaker 2: one g it's the CPU time to execute, and the
- 10:01Speaker 2: other nine are forced into that blsake state we.
- 10:03Speaker 1: Talked about earlier, just sitting there waiting.
- 10:05Speaker 2: Yeah, they're descheduled by the OS, moved into a weight queue,
- 10:09Speaker 2: and then they have to endure the overhead of being
- 10:11Speaker 2: woken up and rescheduled later. You essentially destroy the throughput
- 10:14Speaker 2: of your application.
- 10:15Speaker 1: You're forcing a concurrent system to operate sequentially, and because
- 10:19Speaker 1: it puts so many threads to sleep, Java had to
- 10:22Speaker 1: evolve better traffic signals, which brings us to advanced locks right.
- 10:28Speaker 2: Moving beyond the native synchronized keyword using the lock interface,
- 10:32Speaker 2: specifically implementations like re entrant lock.
- 10:36Speaker 1: So how does re entrent lock fix the bluntness.
- 10:38Speaker 2: Well, it provides programmatic flexibility. For example, it introduces the
- 10:42Speaker 2: concept of.
- 10:43Speaker 1: Fairness, fairness like polite threads.
- 10:46Speaker 2: Basically, yeah, by default, locks in Java are non fair.
- 10:50Speaker 2: When a lock is released, the OS doesn't care which
- 10:52Speaker 2: block thread has been waiting the longest. It just wakes
- 10:55Speaker 2: one up randomly, often based on whichever is most convenient
- 10:57Speaker 2: for the CPU cash.
- 10:58Speaker 1: But with reintrent lock you can pass a true boole
- 11:01Speaker 1: into the constructor to enforce a fair lock. The textbook
- 11:04Speaker 1: uses a print que as an example.
- 11:06Speaker 2: Which is a perfect example because you absolutely want jobs
- 11:09Speaker 2: processed in the order they were submitted, right.
- 11:11Speaker 1: A fair lock forces the system to maintain a strict
- 11:14Speaker 1: first in, first out queue of waiting threads, like a
- 11:17Speaker 1: polite line at a coffee shop.
- 11:19Speaker 2: There's a trade off, though, maintaining that strict queue adds overhead.
- 11:23Speaker 2: The system has to track thread arrival times and orchestrate
- 11:27Speaker 2: the wakeups in exact order. That lowers overall throughput compared
- 11:32Speaker 2: to a non fare lock, where the OS can just
- 11:35Speaker 2: optimize for raw speed.
- 11:36Speaker 1: Got it, But even with re entrent lock, we still
- 11:39Speaker 1: have the mutual exclusion problem. Right, Only one thread gets
- 11:42Speaker 1: in at a time.
- 11:43Speaker 2: Correct.
- 11:43Speaker 1: So if we have a data structure that is read
- 11:46Speaker 1: frequently but updated rarely, locking out all the readers just
- 11:49Speaker 1: because one thread is currently reading seems incredibly inefficient.
- 11:53Speaker 2: Well, it is because multiple threads reading a variable doesn't
- 11:56Speaker 2: cause a race condition. Nobody is writing new data back
- 11:59Speaker 2: to memory, right, and.
- 12:01Speaker 1: That realization led to the read right lock, Yeah, which
- 12:03Speaker 1: is a.
- 12:04Speaker 2: Huge step up. It mathematically separates a lock into two
- 12:07Speaker 2: distinct entities. Multiple threads can acquire the read lock simultaneously.
- 12:10Speaker 1: So the system just keeps a counter of active readers exactly.
- 12:14Speaker 2: As long as there are readers, the read lock remains open.
- 12:17Speaker 2: But if a thread wants to modify the data, it
- 12:19Speaker 2: requests the right lock.
- 12:21Speaker 1: And what happens then? Do the readers get kicked out?
- 12:23Speaker 2: No, the read right lock stops admitting new readers. It
- 12:27Speaker 2: waits for the current active readers to finish and drop
- 12:30Speaker 2: that counter to zero, and then it grants exclusive access
- 12:33Speaker 2: to the writer.
- 12:34Speaker 1: Okay, and once the writ is complete, the doors open
- 12:37Speaker 1: for readers again exactly.
- 12:38Speaker 2: It massively improves throughput for read heavy operations. However, it
- 12:43Speaker 2: introduces a new structural vulnerability.
- 12:46Speaker 1: Writer starvation.
- 12:47Speaker 2: Yeah. Writer's starvation is a real headache, right.
- 12:50Speaker 1: Because if you have a high traffic system where hundreds
- 12:53Speaker 1: of reader threads are constantly requesting the read lock, the
- 12:56Speaker 1: active reader counter might never actually hit zero never, so
- 12:59Speaker 1: the the right thread is essentially stuck in the queue forever,
- 13:02Speaker 1: waiting for a break in the traffic that just never comes.
- 13:05Speaker 2: Exactly and to resolve that specific bottleneck. Java eight introduce
- 13:10Speaker 2: the stamplock.
- 13:11Speaker 1: Oh, this is where it gets really interesting. Stamplock introduces
- 13:14Speaker 1: this concept of optimistic reading, which honestly is one of
- 13:18Speaker 1: the most advanced mechanics in the cookbook. What does it
- 13:21Speaker 1: actually mean for code to be optimistic?
- 13:23Speaker 2: It's a brilliant shift in strategy. Let's look at how
- 13:26Speaker 2: it functions at the memory level. With the traditional lock,
- 13:30Speaker 2: a thread has to write to a shared memory location
- 13:33Speaker 2: to declare, hey, I hold this lock right. That right
- 13:36Speaker 2: operation forces the CPU to invalidate caches across other cores,
- 13:41Speaker 2: which is an incredibly expensive hardware operation just.
- 13:44Speaker 1: To say I'm reading something right.
- 13:46Speaker 2: The stamplock circumvents that entirely for reads. When a thread
- 13:50Speaker 2: calls try optimistic read, it doesn't actually acquire a lock
- 13:53Speaker 2: or alter the state of the lock in memory at all.
- 13:56Speaker 1: Wait, it doesn't lock it.
- 13:57Speaker 2: Nope. Instead, the stamplock we're it turns a stamp, a
- 14:01Speaker 2: long integer that represents the current version or sequence number
- 14:05Speaker 2: of the lock state.
- 14:06Speaker 1: Okay, so it gets a stamp.
- 14:07Speaker 2: Then what the thread takes that stamp reads the shared
- 14:10Speaker 2: data into its own local private variables and then immediately
- 14:14Speaker 2: calls a validate method passing in that stamp.
- 14:16Speaker 1: Ah. So the validate method just checks if the internal
- 14:19Speaker 1: version number of the stamplock has changed since the stamp
- 14:22Speaker 1: was issued.
- 14:23Speaker 2: Exactly if no other thread acquired a right lock in
- 14:26Speaker 2: that tiny microsecond window while you were reading, the version
- 14:30Speaker 2: number still matches. The validation returns true.
- 14:33Speaker 1: Wow, so the thread successfully read the data without ever
- 14:37Speaker 1: locking the system or causing cash invalidation across the CPU cores.
- 14:41Speaker 2: Yep, it's a gamble. It's an assumption that collisions are rare.
- 14:45Speaker 2: You move fast, copy the data, and validate after the fact.
- 14:48Speaker 1: But what if you lose the gamble. What if a
- 14:50Speaker 1: writer thread did acquire the right lock during your read operation, then.
- 14:54Speaker 2: The lock's internal version number would have incremented. Your validation fails.
- 14:58Speaker 2: It returns false.
- 15:00Speaker 1: Because your local copy of the data is potentially corrupted
- 15:03Speaker 1: by a partial rite.
- 15:04Speaker 2: So in that scenario, your thread discards the local copy
- 15:08Speaker 2: and falls back to a heavier traditional read lock to
- 15:10Speaker 2: ensure it gets clean data. But in systems with massive
- 15:13Speaker 2: read to write ratios, the optimistic gamble pays off so
- 15:16Speaker 2: often that the performance gains are just huge.
- 15:19Speaker 1: That is, so cool. It's a complete shift from pessimistic
- 15:22Speaker 1: control to optimistic validation.
- 15:24Speaker 2: It really is.
- 15:25Speaker 1: Yeah.
- 15:25Speaker 2: But up to this point, all these locks re entrant
- 15:29Speaker 2: ReadWrite stamped in moorge. They are primarily about restricting access.
- 15:34Speaker 1: Right, keeping threads out.
- 15:35Speaker 2: Yeah, but the source material also dives into coordination. Sometimes
- 15:39Speaker 2: threads don't just need exclusive access, They need to orchestrate
- 15:43Speaker 2: complex handoffs.
- 15:44Speaker 1: Which brings us to advanced coordination. And the foundational scenario
- 15:49Speaker 1: here is the producer consumer.
- 15:51Speaker 2: Problem write a classic computer science problem. You have a
- 15:54Speaker 2: shared data buffer. Producer threads compute data and insert it.
- 15:58Speaker 2: Consumer threads extract data and process it.
- 16:01Speaker 1: But they have to communicate right, Because if the buffer
- 16:03Speaker 1: is full, a producer shouldn't just repeatedly pull the buffer
- 16:07Speaker 1: in a while loop, constantly checking if they're space No.
- 16:10Speaker 2: That's called spin waiting. It's terrible for performance. It burns
- 16:13Speaker 2: CPU cycles on a core that could actually be used
- 16:16Speaker 2: by a consumer thread to empty the buffer.
- 16:18Speaker 1: So how do we fix spinwaighting?
- 16:20Speaker 2: Java provides the condition interface for this, usually paired with
- 16:23Speaker 2: a reentrant lock. When a producer sees a full buffer,
- 16:26Speaker 2: it calls a weight on a specific condition object.
- 16:29Speaker 1: And that puts it to sleep.
- 16:31Speaker 2: Yes, the os de schedules the thread puts it in
- 16:34Speaker 2: a waiting state, and crucially, it atomically releases the lock
- 16:39Speaker 2: so consumers can actually get in.
- 16:40Speaker 1: Oh that's elegant. So then a consumer thread acquires the lock,
- 16:44Speaker 1: pulls an item from the buffer, and it needs to
- 16:47Speaker 1: tell the producer right right.
- 16:48Speaker 2: It calls signal on that exact same condition object.
- 16:51Speaker 1: And that triggers the os scheduler to wake up the
- 16:54Speaker 1: sleeping producer threads, letting them know, hey, the state changed
- 16:57Speaker 1: space is available exactly.
- 16:59Speaker 2: It's a high maily efficient event driven handoff instead of
- 17:02Speaker 2: constantly checking.
- 17:03Speaker 1: Okay, so that's handoffs. But this coordination also extends to
- 17:07Speaker 1: managing pools of identical resources, which brings us to semaphores,
- 17:12Speaker 1: originally invented by Edsgerdikstra back in what nineteen sixty five.
- 17:16Speaker 2: Yeah, they've been around for a while. Because a lock
- 17:18Speaker 2: is binary, it's either held or it isn't. But a
- 17:21Speaker 2: semaphore is a counter representing a finite number of permits.
- 17:24Speaker 1: The book uses a multiprinter queue to illustrate this, but
- 17:26Speaker 1: it kind of reminds me the bouncer at a club.
- 17:29Speaker 2: Oh I like that? How so well, a lock.
- 17:31Speaker 1: Is like a VIP bathroom, one person in, one person out,
- 17:35Speaker 1: but a semaphore is a bouncer keeping the club capacity
- 17:38Speaker 1: at exactly three people.
- 17:40Speaker 2: That's a great analogy. So if you have three physical printers,
- 17:43Speaker 2: you initialize a semaphore with a permit count of.
- 17:45Speaker 1: Three, and when a thread wants to print, it calls
- 17:48Speaker 1: a choir.
- 17:49Speaker 2: The semaphore checks the counter. If it's greater than zero,
- 17:52Speaker 2: it decrements the counter and grants the permit, So.
- 17:54Speaker 1: The first three threads get immediate access, dropping the counter
- 17:57Speaker 1: to zero.
- 17:58Speaker 2: Right when a fourth thread calls a CHOI. The semaphore
- 18:01Speaker 2: sees that zero count, it blocks that four thread, puts
- 18:04Speaker 2: it to sleep in a queue.
- 18:05Speaker 1: Just waiting in line outside the club exactly.
- 18:08Speaker 2: It stays there until one of the active threads finishes
- 18:11Speaker 2: its print job and calls release.
- 18:12Speaker 1: Which increments the counter back to one.
- 18:15Speaker 2: Yes, and then the semaphore unblocks the next thread in
- 18:17Speaker 2: the queue and hands it the newly available permit. It
- 18:20Speaker 2: regulates capacity without caring about the specific identity of the
- 18:24Speaker 2: threads inside.
- 18:25Speaker 1: It's just brilliant. But I mean this raises an important question.
- 18:29Speaker 1: While these tools locks conditions semaphors, they give you the
- 18:33Speaker 1: power to organize chaos, don't They also introduce a massive vulnerability.
- 18:38Speaker 2: Oh you mean deadlocks?
- 18:39Speaker 1: Yeah, deadlocks the ultimate concurrency nightmare, they really are.
- 18:42Speaker 2: This happens when the coordination logic loops back on itself.
- 18:45Speaker 1: The circular dependency exactly.
- 18:48Speaker 2: Imagine thread A acquires lock x at the exact same
- 18:52Speaker 2: time thread B acquires lock y.
- 18:54Speaker 1: Okay.
- 18:55Speaker 2: Then thread A tries to acquire lock why to finish
- 18:58Speaker 2: its operation, but it's b lock A because B holds it. Meanwhile,
- 19:03Speaker 2: thread B tries to acquire lock X, but it's block
- 19:06Speaker 2: AD because A holds it.
- 19:08Speaker 1: Wow. So both threads under this indefinite blocked ed state.
- 19:11Speaker 2: Yes, neither can proceed to the point where they would
- 19:13Speaker 2: release their current locks. The application state just freezes. Yeah,
- 19:17Speaker 2: and the only resolution is an OS level termination.
- 19:20Speaker 1: So how do you prevent that? Is there a specific
- 19:22Speaker 1: Java class for it?
- 19:23Speaker 2: No? Unfortunately, not preventing deadlocks isn't about using a magic class.
- 19:28Speaker 2: It requires strict architectural discipline. Usually that means enforcing a
- 19:33Speaker 2: global ordering system where threads are only allowed to request
- 19:36Speaker 2: locks in a specific, pre defined sequence.
- 19:39Speaker 1: You really have to have your whole system mapped out,
- 19:41Speaker 1: which I guess all comes back to that incredibly high
- 19:44Speaker 1: stakes traffic control system we talked about at the start.
- 19:47Speaker 2: It does.
- 19:47Speaker 1: We've really traced the mechanics from the ground up today,
- 19:50Speaker 1: from the OS time slicing that creates the illusion of
- 19:53Speaker 1: concurrency to the hardware level race conditions caused by those
- 19:57Speaker 1: multistep memory operations.
- 19:59Speaker 2: Yeah, and we've seeing how synchronized stops data corruption but
- 20:02Speaker 2: creates massive bottle mix which force the evolution toward reintrent locks,
- 20:07Speaker 2: read write locks, and eventually that highly optimized stamplock.
- 20:11Speaker 1: And we covered how threads communicate state changes without burning
- 20:14Speaker 1: CPU cycles using conditions, and how they pool resources using semaphores,
- 20:19Speaker 1: all while.
- 20:19Speaker 2: Having to mathematically prove their lock ordering to avoid those deadlocks.
- 20:24Speaker 1: It really is the invisible infrastructure of the modern software world.
- 20:28Speaker 1: Every smooth, glitch free app you use today, every scalable
- 20:32Speaker 1: back end, high frequency trading platform, they all rely on
- 20:35Speaker 1: these exact rules to keep the chaos organized behind the scenes.
- 20:40Speaker 2: Because without these mechanisms acting as the bedrock, concurrent programming
- 20:44Speaker 2: would just result in cascading data corruption.
- 20:46Speaker 1: Absolutely, And as a final takeaway, I want to loop
- 20:49Speaker 1: back to the concept of the stamplock and optimistic reading
- 20:53Speaker 1: because in systems design, we found that assuming no one
- 20:55Speaker 1: else is interfering, moving fast and just validating our assumptions
- 20:59Speaker 1: at the end is often exponentially faster than constantly locking
- 21:03Speaker 1: the system down. Just in case.
- 21:04Speaker 2: It's really powerful paradigm shift.
- 21:06Speaker 1: It really is, and it makes you wonder how that
- 21:08Speaker 1: applies beyond the CPU when managing complex projects you're dealing
- 21:11Speaker 1: with chaotic parallel workflows in our own lives. Do we
- 21:14Speaker 1: overuse the equivalent of a pessimistic lock? Do we bottleneck
- 21:18Speaker 1: our own throughput by trying to tightly control and restrict
- 21:21Speaker 1: every single variable, that's a great question. Or is there
- 21:23Speaker 1: room to adopt an optimistic read, you know, operating on
- 21:26Speaker 1: the assumption that the state hasn't changed, doing the work
- 21:30Speaker 1: and just building in a quick validation check at the end.
- 21:33Speaker 1: Something to ponder next time you're trying to multitask in
- 21:36Speaker 1: your own life. Thanks for diving deep with us today.