Race conditions, synchronized ומוניטוריםRace conditions, synchronized & monitors
למה count++ מאבד עדכונים, קטע קריטי, synchronized על מתודות ועל בלוקים, ומוניטורים.
Why count++ loses updates, critical sections, synchronized methods and blocks, and monitors.
בסוף המפגש תדעוBy the end you will
- להבין מרוץ (race condition): למה
count++משני threads מאבד עדכוניםUnderstand a race condition: whycount++from two threads loses updates - לזהות קטע קריטי ולהגן עליו עם synchronized (מתודה או בלוק)Spot a critical section and protect it with synchronized (a method or a block)
- להבין מוניטור: לכל עצם יש מנעול אחד, והוא reentrantUnderstand a monitor: every object has one lock, and it's reentrant
- לתקן בדיקה ואז פעולה על ידי שתיהן בתוך אותו מנעולFix check-then-act by putting both inside the same lock
לפני שמתחיליםBefore you start
זמן: Time: כ-3 שעות (כולל הפסקה)About 3 hours (with a break)
דרישות קודמות: Prerequisites: מפגשים 1–31Sessions 1–31
מה צריך: You need: מחשב עם JDK 21 ו-IntelliJ IDEA מותקנים (מפגש 1). אפשר גם רק דפדפן: כל הקוד מוצג עם הפלט האמיתי שלו, ורץ גם כאן כשהדפדפן מאפשר.A computer with JDK 21 and IntelliJ IDEA (session 1). A browser alone also works: every example shows its real output, and runs here when the browser allows it.
סדר המפגשSession plan
- 0:00פתיחה וחזרה קצרהOpening and quick review
- 0:10מונחיםTerms
- 0:34count++ מאבד עדכוניםcount++ loses updates
- 0:58synchronized: אחד בכל פעםsynchronized: one at a time
- 1:22הפסקהBreak
- 1:32בדיקה ואז פעולהCheck, then act
- 1:56פרויקט מדףShelf project
- 2:20תרגולPractice
- 2:50סיכום ושאלותWrap-up and questions
למה count++ מאבד עדכונים, קטע קריטי, synchronized על מתודות ועל בלוקים, ומוניטורים. בסוף המפגש מוסיפים צעד לפרויקט המלווה.
Why count++ loses updates, critical sections, synchronized methods and blocks, and monitors. At the end we add a step to the companion project.
הפרויקט המלווהThe companion project: מדף: ספרייה אישיתShelf: a personal library
פרויקט אחד שגדל איתכם לאורך כל הקורס: מתחיל כתוכנית של 10 שורות, הופך למחלקות, ל-interfaces ול-streams, מייבא ספרים במקביל עם Threads, ונגמר כ-REST API.
One project that grows with you through the whole course: it starts as a 10-line program, becomes classes, interfaces and streams, imports books in parallel with threads, and ends as a REST API.
השלב של היוםToday's step מונה השאלות בטוח ל-threadsA thread-safe loan counter. לתרגילGo to the exercise