Skip to content

Commit 7b55a27

Browse files
committed
Migrate development environment from Windows to macOS and continue project updates
- Shifted primary development environment from Windows to macOS to ensure better performance, stability, and streamlined workflow for Java development. - Removed OS-specific metadata and ensured platform-agnostic project compatibility. - Normalized line endings to LF for cross-platform consistency. - Verified and adjusted file paths, permissions, and encoding settings to suit macOS environment. - Cleaned up unnecessary Windows-generated files and updated Git configuration accordingly. - Future commits and development will now be managed entirely from macOS. This migration ensures a cleaner, more consistent setup moving forward and prepares the project for scalable development across Unix-based systems. Future development will continue on macOS for a smoother, Unix-based experience. Signed-off-by: Someshdiwan <[email protected]>
1 parent ade0208 commit 7b55a27

11 files changed

+381
-0
lines changed
815 Bytes
Binary file not shown.

out/production/DeadLock/DeadLocks

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
It is a situation in multi-threading where two or more threads
2+
are blocked forever waiting for each other to release a resources.
3+
4+
This typically occurs when two or more threads have circular dependencies on a set of locks.
5+
necessary conditions for a deadlock to occur in a system:
6+
7+
Mutual Exclusion: A resource can only be used by one thread/process at a time.
8+
Hold and Wait: A thread holding a resource is waiting for another resource held by another thread.
9+
No Preemption: A resource cannot be forcibly taken away from a thread holding it.
10+
Circular Wait: A circular chain of two or more threads exists, where each thread waits for a resource held by the next.
11+
12+
Deadlock Prevention, Detection, and Resolution
13+
14+
1. Deadlock Prevention:
15+
16+
To prevent deadlocks, we must eliminate at least one of the four necessary conditions.
17+
18+
- Breaking Mutual Exclusion
19+
- Make resources shareable whenever possible.
20+
- Example: Read-only files can be accessed by multiple processes.
21+
22+
- Breaking Hold and Wait
23+
- Require a process to request all required resources at once (resource allocation in a single request).
24+
- Example: Database transactions acquire all locks before proceeding.
25+
26+
- Breaking No Preemption
27+
- Allow resources to be preempted (taken away) from a process if needed.
28+
- Example: CPU scheduling can forcefully remove a process from execution.
29+
30+
- Breaking Circular Wait
31+
- Impose an **ordering on resource requests** (number resources and require them to be requested in increasing order).
32+
- Example: If a process holds Resource 1, it must request Resource 2 before Resource 3.
33+
34+
35+
2. Deadlock Detection:
36+
37+
If prevention is not feasible, we use detection mechanisms:
38+
39+
- Resource Allocation Graph (RAG)
40+
- Used for single-instance resource systems. A cycle in the graph indicates a deadlock.
41+
42+
- Wait-for Graph
43+
- Derived from RAG by removing resource nodes. A cycle in this graph confirms a deadlock.
44+
45+
- Detection Algorithm (Banker's Algorithm for Deadlock Detection)
46+
- Periodically checks for circular dependencies in multi-instance resource systems.
47+
48+
---
49+
50+
3. Deadlock Resolution (Recovery):
51+
52+
Once a deadlock is detected, recovery strategies include:
53+
54+
- Process Termination**
55+
- Kill one or more processes involved in the deadlock.
56+
- Either terminate all deadlocked processes or terminate one at a time until deadlock is resolved.
57+
58+
- Resource Preemption
59+
- Take resources from some processes and reallocate them.
60+
- Requires rollback mechanisms to avoid inconsistencies.
61+
62+
---
63+
64+
Choosing the Right Strategy:
65+
66+
- Prevention is best if system design allows.
67+
- Detection & Recovery are necessary in dynamic systems like OS and databases.
68+
- Avoidance (Banker’s Algorithm) is used when processes declare maximum resource needs in advance.
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
Deep Dive into Thread Safety Techniques
2+
3+
Now, let’s break down three key techniques used to ensure thread safety in real-world applications:
4+
5+
1. Database Transactions & ACID Properties
6+
2. Locking Mechanisms (Synchronized, ReentrantLock, Distributed Locks)
7+
3. Atomic Operations (Atomic Variables & Compare-and-Swap - CAS)
8+
9+
---
10+
11+
1. Database Transactions & ACID Properties:
12+
13+
Problem: Race Condition in a Banking System:
14+
15+
Imagine two people withdrawing money from the same account at the exact same time.
16+
17+
- User A wants to withdraw $500
18+
- User B wants to withdraw $600
19+
- The initial balance is $1000, so both requests think they have enough funds.
20+
- If the system is not thread-safe, it may allow both transactions to happen, making the balance negative (-$100).
21+
22+
Solution: ACID Transactions in Databases:
23+
24+
ACID (Atomicity, Consistency, Isolation, Durability) ensures that transactions are processed safely.
25+
26+
- Atomicity: The transaction is all or nothing. If one step fails, everything rolls back.
27+
- Consistency: The database remains in a valid state before and after a transaction.
28+
- Isolation: No two transactions interfere with each other.
29+
- Durability: Once committed, data is permanently stored, even in case of a crash.
30+
31+
Real-world Example: If you’ve ever had a failed online payment and saw
32+
"Transaction Reversed," that’s Atomicity in action!
33+
34+
---
35+
36+
2. Locking Mechanisms (Preventing Deadlocks & Race Conditions):
37+
38+
Types of Locks:
39+
40+
1. Synchronized Locks (Java's synchronized keyword):
41+
42+
- Ensures only one thread can execute a method at a time.
43+
- Example: If a user is editing a shared document, another user must wait before making changes.
44+
45+
2. ReentrantLock (More Flexible than `synchronized`):
46+
- Allows fine-grained control over locks, including timeouts and fairness policies.
47+
- Example: Uber ensures that only one person can book a driver at a time using a lock.
48+
49+
3. Distributed Locks (Used in Cloud Applications):
50+
- Used when multiple servers are involved (e.g., Google Docs, Uber, Banking).
51+
- Redis-based locks, Zookeeper locks, and AWS DynamoDB locks ensure global thread safety across multiple servers.
52+
53+
54+
Real-world Example: When two people try to book the last ticket, one gets it, and the other sees "Seat Unavailable".
55+
That's locking in action!
56+
57+
---
58+
59+
3. Atomic Operations & Compare-and-Swap (CAS):
60+
61+
Problem: Incrementing a Shared Counter in Multi-threaded Systems
62+
63+
Imagine you have a website tracking visitor count using a shared variable.
64+
65+
- If 1000 users visit at the same time, they might **all read the same old value**, causing **wrong counts**.
66+
67+
Solution: Atomic Variables (Thread-Safe Counters):
68+
69+
Instead of using normal integers, we use atomic variables like `AtomicInteger` (Java) or CAS operations.
70+
71+
- Atomic operations ensure that a value is updated safely, without explicit locks.
72+
- Compare-and-Swap (CAS) is a low-level operation that compares the old value and updates
73+
it only if it hasn’t changed (ensuring no race conditions).
74+
75+
Real-world Example: Websites like YouTube, Facebook, and Twitter use atomic counters to
76+
accurately track likes, views, and shares!
77+
78+
---
79+
80+
Key Takeaways for Interviews
81+
1. ACID Transactions → Used in banking, stock trading, and online payments to ensure correctness.
82+
2. Locking Mechanisms** → Used in Uber, Google Docs, and ticket booking systems to prevent double bookings.
83+
3. Atomic Operations & CAS → Used in **social media platforms (likes, shares, views) and
84+
distributed systems for high-speed counters.
85+
86+
deadlocks, optimistic locking, or distributed locking techniques? 🚀
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
Detailed Real-World Examples of Thread Safety:
2+
3+
I'll break down **two critical real-world scenarios where thread safety plays a major role, along with solutions.
4+
5+
1. Online Banking System - Preventing Race Conditions:
6+
7+
Scenario:
8+
9+
Imagine a bank account where two users (threads) are trying to withdraw money at the same time.
10+
11+
- Account Balance: $1000
12+
- User 1 (Thread A) wants to withdraw: $800
13+
- User 2 (Thread B) wants to withdraw: $500
14+
15+
- Both threads check the balance at the same time (before the transaction is processed).
16+
- Each sees $1000 and believes there is enough money.
17+
- Both transactions proceed, and the total withdrawal is $1300, even though only $1000 was available.
18+
- Final balance becomes negative (-$300), which should not be possible!
19+
20+
What Went Wrong?
21+
- This is a race condition where multiple threads are accessing and modifying shared data without synchronization.
22+
- The balance check and update should be done atomically (as a single operation).
23+
24+
Solution
25+
- Use synchronization to ensure that only one withdrawal happens at a time.
26+
- Use atomic variables (like AtomicInteger in Java) to ensure thread-safe balance updates.
27+
- Implement database transactions to lock the balance during the withdrawal process.
28+
29+
📌 Real-world example: If you've ever seen a failed transaction message like "Insufficient Funds",
30+
it means the banking system is handling this properly.
31+
32+
2. Ticket Booking System - Avoiding Double Booking**
33+
34+
Scenario: Imagine an online movie ticket booking system where two users are trying to book the last available seat
35+
at the same time.
36+
37+
- User 1 (Thread A) selects the seat at 10:00:05 AM
38+
- User 2 (Thread B) selects the same seat at 10:00:06 AM
39+
40+
- If the system is not thread-safe, both users might be assigned the same seat.
41+
- When they arrive at the theater, both have the same seat number, causing a conflict.
42+
43+
What Went Wrong?
44+
45+
- The system is checking seat availability without properly locking it, leading to double booking.
46+
- The seat allocation is not an atomic operation (it checks and updates separately).
47+
48+
Solution:
49+
50+
1. Use Thread-Safe Collections
51+
- Use a ConcurrentHashMap or synchronized list to manage available seats.
52+
53+
2. Locking Mechanism
54+
- When a seat is selected, lock it until payment is completed.
55+
56+
3. Database Transactions
57+
- Use ACID-compliant transactions in the database to ensure that once a seat is booked,
58+
it cannot be selected by another user.
59+
60+
📌 Real-world example: If you've ever seen "Seat already booked, please select another" in a booking app,
61+
that's the system handling concurrency properly.
62+
63+
64+
Key Takeaways:
65+
66+
- Thread safety prevents critical real-world issues like double booking and financial errors.
67+
- Race conditions happen when multiple threads modify shared data simultaneously.
68+
- Using synchronization, atomic variables, and database transactions can prevent these issues.
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
More Real-World Examples of Thread Safety with Deep Explanations:
2+
3+
Now, let’s dive into two more complex and real-world scenarios where thread safety is crucial.
4+
5+
6+
3. Cloud Document Editing – Avoiding Inconsistent Updates (Google Docs Example)
7+
8+
Scenario
9+
Imagine multiple users are editing the same Google Docs file in real time.
10+
11+
- User 1 (Thread A) edits Line 5 and changes "Hello" to "Hi".
12+
- User 2 (Thread B) edits Line 5 at the same time and changes "Hello" to "Hey".
13+
- If both changes happen simultaneously **without synchronization, the document
14+
could end up with an inconsistent state (one user’s edit might overwrite another’s).
15+
16+
What Went Wrong?
17+
- Both users fetched the old text before updating it, leading to data loss when one update overwrites the other.
18+
- This is called a **lost update problem**, a common issue in multi-user collaborative editing.
19+
20+
Solution
21+
1. Operational Transformation (OT) or Conflict-Free Replicated Data Types (CRDTs)
22+
- Google Docs and similar tools use OT or CRDTs to merge changes in real time.
23+
- Instead of overwriting, it **tracks individual changes and intelligently merges them**.
24+
25+
2. Locking Mechanism for Critical Sections
26+
- Some document editing tools lock sections of a document so only one user can edit a specific line at a time.
27+
28+
3. Version Control with Timestamps
29+
- Every edit is assigned a timestamp and version number to track which change should be applied first.
30+
31+
📌 Real-world example: In Google Docs, when two people edit the same word, both edits are preserved intelligently
32+
instead of getting lost.
33+
34+
4. Ride-Sharing App (Uber) – Handling Concurrent Ride Requests**
35+
36+
Scenario
37+
Imagine a ride-sharing app like Uber, where multiple riders request the same nearby driver at the same time.
38+
39+
- User 1 (Thread A) books Driver X at 10:00:10 AM.
40+
- User 2 (Thread B) also books Driver X at 10:00:11 AM.
41+
- If the system is not thread-safe, both users may be assigned the same driver, leading to booking conflicts.
42+
43+
What Went Wrong?
44+
- Multiple requests were processed simultaneously, leading to the same driver being booked twice.
45+
- There was no synchronization on driver availability before confirming the ride.
46+
47+
Solution:
48+
1. Atomic Database Transactions
49+
- When a ride request is made, the database **locks the driver** entry until the booking is confirmed.
50+
51+
2. Distributed Locking Mechanism
52+
- Uber uses a distributed lock system** across multiple servers to ensure **only one rider gets a driver** at a time.
53+
54+
3. Queue-Based Processing
55+
- Instead of handling all ride requests at once, they queue ride requests and process them one by one.
56+
57+
📌 Real-world example: Have you ever tried booking an Uber and seen Driver Unavailable even though you
58+
just clicked? That’s the system ensuring thread safety to prevent double bookings.
59+
60+
61+
-- Key Takeaways for Interviews
62+
- Thread safety is critical in cloud-based applications, ride-sharing, and banking systems.
63+
- Techniques like Operational Transformation (OT), database transactions, and distributed locks prevent data inconsistencies.
64+
- Real-world services like Google Docs, Uber, and banking apps use sophisticated thread safety techniques to avoid issues.
65+
66+
deep dive into any specific technique, such as database transactions, locking mechanisms, or atomic operations* 🚀
1.44 KB
Binary file not shown.

out/production/DeadLock/Pen.class

1.38 KB
Binary file not shown.
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
Real-World Examples of Thread Safety:
2+
3+
1. Online Banking System (Race Condition Example)
4+
5+
Imagine two users trying to withdraw money from the same bank account at the same time:
6+
7+
Thread 1: Withdraws $500 from an account with $1000.
8+
9+
Thread 2: Withdraws $600 at the same time.
10+
11+
If both transactions read the balance simultaneously, they might both think there is enough money, leading to an
12+
overdrawn account.
13+
14+
Solution: The banking system must ensure that only one transaction is processed at a time using thread-safe mechanisms
15+
like synchronization or atomic transactions.
16+
17+
2. Ticket Booking System (Thread-safe Collections)
18+
19+
Suppose multiple users are trying to book the last available seat in a theater at the same time.
20+
21+
If the system is not thread-safe, two users might end up booking the same seat, causing a double booking.
22+
23+
Solution: The ticketing system can use thread-safe data structures like a concurrent queue or synchronized database
24+
transactions to prevent such conflicts.
25+
26+
3. Shared File Editing (Deadlock Scenario)
27+
28+
Imagine two users editing the same file in a cloud-based application.
29+
Thread A locks the file and tries to access the metadata.
30+
Thread B locks the metadata and tries to access the file.
31+
32+
Both threads are waiting for each other to release their locks, leading to a deadlock, where neither can proceed.
33+
34+
Solution: A proper locking strategy (e.g., acquiring locks in a predefined order) ensures that deadlocks don’t happen.
35+
36+
4. E-Commerce Website (Thread-safe Counters)
37+
38+
During a flash sale, thousands of users are adding products to their carts.
39+
40+
If a non-thread-safe counter is used to track the available stock, multiple users might be shown the same last product,
41+
leading to overselling.
42+
43+
Solution: Using atomic operations ensures that each stock update is correctly processed.
44+
45+
Key Takeaways for Interviews:
46+
47+
Thread safety is essential when multiple threads share a resource.
48+
Common issues include race conditions, deadlocks, and data inconsistency.
49+
Solutions include synchronization, locks, atomic variables, thread-safe collections, and immutable objects.
50+
Real-world applications include banking, ticket booking, cloud file editing, and e-commerce.
542 Bytes
Binary file not shown.
662 Bytes
Binary file not shown.

0 commit comments

Comments
 (0)