Compare commits
3
Commits
fa95f2ebeb
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a0a2197e71 | ||
|
|
7e4527560e | ||
|
|
ca59d7e5ea |
Generated
+10
@@ -0,0 +1,10 @@
|
|||||||
|
# Default ignored files
|
||||||
|
/shelf/
|
||||||
|
/workspace.xml
|
||||||
|
# Ignored default folder with query files
|
||||||
|
/queries/
|
||||||
|
# Datasource local storage ignored files
|
||||||
|
/dataSources/
|
||||||
|
/dataSources.local.xml
|
||||||
|
# Editor-based HTTP Client requests
|
||||||
|
/httpRequests/
|
||||||
Generated
+13
@@ -0,0 +1,13 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="CompilerConfiguration">
|
||||||
|
<annotationProcessing>
|
||||||
|
<profile name="Maven default annotation processors profile" enabled="true">
|
||||||
|
<sourceOutputDir name="target/generated-sources/annotations" />
|
||||||
|
<sourceTestOutputDir name="target/generated-test-sources/test-annotations" />
|
||||||
|
<outputRelativeToContentRoot value="true" />
|
||||||
|
<module name="HW-09-Advanced-Multithreading" />
|
||||||
|
</profile>
|
||||||
|
</annotationProcessing>
|
||||||
|
</component>
|
||||||
|
</project>
|
||||||
Generated
+7
@@ -0,0 +1,7 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="Encoding">
|
||||||
|
<file url="file://$PROJECT_DIR$/src/main/java" charset="UTF-8" />
|
||||||
|
<file url="file://$PROJECT_DIR$/src/main/resources" charset="UTF-8" />
|
||||||
|
</component>
|
||||||
|
</project>
|
||||||
Generated
+20
@@ -0,0 +1,20 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="RemoteRepositoriesConfiguration">
|
||||||
|
<remote-repository>
|
||||||
|
<option name="id" value="central" />
|
||||||
|
<option name="name" value="Central Repository" />
|
||||||
|
<option name="url" value="https://maven.devneeds.ir/" />
|
||||||
|
</remote-repository>
|
||||||
|
<remote-repository>
|
||||||
|
<option name="id" value="central" />
|
||||||
|
<option name="name" value="Maven Central repository" />
|
||||||
|
<option name="url" value="https://repo1.maven.org/maven2" />
|
||||||
|
</remote-repository>
|
||||||
|
<remote-repository>
|
||||||
|
<option name="id" value="jboss.community" />
|
||||||
|
<option name="name" value="JBoss Community repository" />
|
||||||
|
<option name="url" value="https://repository.jboss.org/nexus/content/repositories/public/" />
|
||||||
|
</remote-repository>
|
||||||
|
</component>
|
||||||
|
</project>
|
||||||
Generated
+12
@@ -0,0 +1,12 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="ExternalStorageConfigurationManager" enabled="true" />
|
||||||
|
<component name="MavenProjectsManager">
|
||||||
|
<option name="originalFiles">
|
||||||
|
<list>
|
||||||
|
<option value="$PROJECT_DIR$/pom.xml" />
|
||||||
|
</list>
|
||||||
|
</option>
|
||||||
|
</component>
|
||||||
|
<component name="ProjectRootManager" version="2" project-jdk-name="25" project-jdk-type="JavaSDK" />
|
||||||
|
</project>
|
||||||
Generated
+6
@@ -0,0 +1,6 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="VcsDirectoryMappings">
|
||||||
|
<mapping directory="" vcs="Git" />
|
||||||
|
</component>
|
||||||
|
</project>
|
||||||
+133
@@ -0,0 +1,133 @@
|
|||||||
|
|
||||||
|
#### ****1 -** What are atomic variables?**
|
||||||
|
|
||||||
|
#### Explain their purpose and how they differ from ordinary (non-atomic) variables.
|
||||||
|
|
||||||
|
|
||||||
|
#### **Answer:**
|
||||||
|
Atomic variables are variables on which reading and writing operations are atomic.</br>
|
||||||
|
It means that when a Thread is making changes to a variable, no other Thread can interfere with it.</br>
|
||||||
|
They Use hardware-level instructions to ensure that only one thread can modify the value at a time without locks.</br>
|
||||||
|
But for ordinary variables, operations like balance += amount are not atomic for example if another thread interrupts between these steps, it causes Race Conditions and data corruption.</br>
|
||||||
|
---
|
||||||
|
|
||||||
|
#### **2 -** Name at least four classes from the `java.util.concurrent.atomic` package that provide atomic operations for different data types.
|
||||||
|
|
||||||
|
#### For one of them, briefly describe a typical use case.
|
||||||
|
|
||||||
|
|
||||||
|
#### **Answer:**
|
||||||
|
|
||||||
|
- AtomicInteger
|
||||||
|
- AtomicLong
|
||||||
|
- AtomicBoolean
|
||||||
|
- AtomicReference
|
||||||
|
|
||||||
|
Example :
|
||||||
|
```
|
||||||
|
private AtomicLong balance = new AtomicLong(0);
|
||||||
|
|
||||||
|
public void deposit(long amount)
|
||||||
|
{
|
||||||
|
balance.addAndGet(amount);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
Atomically adds amount to current balance.</br>
|
||||||
|
It is fast & it does not need `synchronized`
|
||||||
|
.<br>
|
||||||
|
But it is only good for simple operations on one variable.
|
||||||
|
|
||||||
|
|
||||||
|
---
|
||||||
|
#### **3 -** Compare locks with atomic variables.
|
||||||
|
|
||||||
|
#### In which scenarios is using a lock a better choice than an atomic variable, and vice versa?
|
||||||
|
|
||||||
|
|
||||||
|
#### **Answer:**
|
||||||
|
|
||||||
|
|
||||||
|
| Feature | Lock (ReentrantLock / synchronized) | Atomic Variables |
|
||||||
|
|:-------------------------|:----------------------------------------------------------------------------:|:------------------------------------------------------------------:|
|
||||||
|
| Complexity of operations | Great for complex, multi-step operations | Great for simple operations on a variable |
|
||||||
|
| Scope of Locking | You can lock blocks of code | It only locks the variable itself |
|
||||||
|
| Conditional Logic | Supports conditional checks;You can check if (balance > 0) and then withdraw | Difficult; requires loops with compareAndSet which can be complex. |
|
||||||
|
| Resource Management | Requires manual unlocking in finally | Automatic |
|
||||||
|
| Deadlock | Dangerous | None |
|
||||||
|
|
||||||
|
**When to Use Which?**
|
||||||
|
|
||||||
|
**Use Locks When:**
|
||||||
|
|
||||||
|
- You need to perform compound operations involving multiple state variables atomically (e.g., in our banking project: balance -= amount AND target.balance += amount must happen together).
|
||||||
|
- You need to wait for a condition (using Condition.await()/signal()).
|
||||||
|
- The critical section contains complex logic that cannot be reduced to a single atomic instruction.
|
||||||
|
|
||||||
|
**Use Atomic Variables When:**
|
||||||
|
|
||||||
|
- You are modifying a single variable (e.g., a global counter, a status flag).
|
||||||
|
- Performance is critical and contention is expected to be low.
|
||||||
|
- You want to avoid the complexity of managing lock lifecycles (acquire/release).
|
||||||
|
---
|
||||||
|
|
||||||
|
#### **4 -** A program is completely free of race conditions but still performs poorly under high contention.
|
||||||
|
|
||||||
|
#### Explain how this situation can occur.
|
||||||
|
|
||||||
|
#### Discuss at least three concurrency-related factors that may limit scalability even when correctness is guaranteed.
|
||||||
|
|
||||||
|
|
||||||
|
#### **Answer:**
|
||||||
|
|
||||||
|
|
||||||
|
Even without race conditions, high contention causes bottlenecks due to:
|
||||||
|
|
||||||
|
- **Thread Contention:** Threads block waiting for locks, turning parallel execution into sequential processing. CPU time is wasted managing queues rather than computing.
|
||||||
|
- **Context Switching Overhead:** Frequent blocking/unblocking forces the OS to save/restore thread states. High switch rates consume CPU cycles needed for actual work.
|
||||||
|
- **False Sharing:** Unrelated variables in the same cache line cause unnecessary cache invalidations across cores, forcing slow main memory accesses despite logical independence.
|
||||||
|
|
||||||
|
|
||||||
|
---
|
||||||
|
####
|
||||||
|
#### **5 -** Many concurrent systems experience performance degradation as the number of threads increases.
|
||||||
|
|
||||||
|
#### Explain why adding more threads does not always improve performance.
|
||||||
|
|
||||||
|
#### Your answer should discuss concepts such as:
|
||||||
|
|
||||||
|
#### Context switching
|
||||||
|
#### Contention
|
||||||
|
#### coherence
|
||||||
|
#### Synchronization overhead
|
||||||
|
|
||||||
|
|
||||||
|
#### **Answer:**
|
||||||
|
|
||||||
|
Performance degrades with excessive threads due to:
|
||||||
|
|
||||||
|
- **Synchronization Overhead:** Lock acquisition/release costs exceed computation time for small tasks.
|
||||||
|
- **Contention:** Increased probability of lock conflicts leads to long wait times, shifting from parallel to serialized execution.
|
||||||
|
- **Context Switching:** Beyond core limits, CPUs spend more time switching contexts than executing instructions (“thread explosion”).
|
||||||
|
- **Cache Coherence:** Frequent writes to shared data trigger inter-core synchronization (MESI protocol), saturating the communication bus and increasing latency
|
||||||
|
---
|
||||||
|
|
||||||
|
#### **6 -** Deadlocks often only appear in production, not during testing.
|
||||||
|
|
||||||
|
#### Explain why this might happen from a thread-scheduling perspective.
|
||||||
|
|
||||||
|
#### Describe two strategies a developer can use to increase the likelihood of exposing deadlocks during testing.
|
||||||
|
|
||||||
|
|
||||||
|
#### **Answer:**
|
||||||
|
|
||||||
|
**Why they hide in testing:**
|
||||||
|
|
||||||
|
- Timing: Tests are fast and deterministic; production has I/O/network delays that alter thread interleaving.
|
||||||
|
- Concurrency: Tests use few threads; deadlocks often require high concurrency to trigger naturally.
|
||||||
|
|
||||||
|
|
||||||
|
**Strategies to Expose Deadlocks:**
|
||||||
|
|
||||||
|
- Stress Testing: Spawn hundreds of threads performing random operations to exponentially increase the chance of hitting cyclic dependency windows.
|
||||||
|
- Inject Delays: Add Thread.sleep() or use tools like JMH to disrupt natural flow, increasing the likelihood that a thread holds one lock while waiting for another.
|
||||||
|
---
|
||||||
@@ -1,10 +1,16 @@
|
|||||||
package dev.banking.model;
|
package dev.banking.model;
|
||||||
|
|
||||||
|
import java.util.concurrent.locks.ReentrantLock;
|
||||||
|
import java.util.concurrent.locks.ReentrantReadWriteLock;
|
||||||
|
|
||||||
public class BankAccount {
|
public class BankAccount {
|
||||||
|
|
||||||
private final int accountId;
|
private final int accountId;
|
||||||
private long balance;
|
private long balance;
|
||||||
|
|
||||||
|
private final ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
|
||||||
|
private final ReentrantLock transferLock = new ReentrantLock();
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Students may introduce additional fields
|
* Students may introduce additional fields
|
||||||
* such as:
|
* such as:
|
||||||
@@ -32,7 +38,12 @@ public class BankAccount {
|
|||||||
* - Should not block unnecessarily if using read/write locks
|
* - Should not block unnecessarily if using read/write locks
|
||||||
*/
|
*/
|
||||||
public long getBalance() {
|
public long getBalance() {
|
||||||
throw new UnsupportedOperationException("TODO: implement thread-safe balance read");
|
rwLock.readLock().lock();
|
||||||
|
try {
|
||||||
|
return balance;
|
||||||
|
} finally {
|
||||||
|
rwLock.readLock().unlock();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -43,7 +54,12 @@ public class BankAccount {
|
|||||||
* - Must not lose updates under concurrency
|
* - Must not lose updates under concurrency
|
||||||
*/
|
*/
|
||||||
public void deposit(long amount) {
|
public void deposit(long amount) {
|
||||||
throw new UnsupportedOperationException("TODO: implement thread-safe deposit");
|
rwLock.writeLock().lock();
|
||||||
|
try {
|
||||||
|
balance += amount;
|
||||||
|
} finally {
|
||||||
|
rwLock.writeLock().unlock();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -56,7 +72,12 @@ public class BankAccount {
|
|||||||
* to extend the system (optional)
|
* to extend the system (optional)
|
||||||
*/
|
*/
|
||||||
public void withdraw(long amount) {
|
public void withdraw(long amount) {
|
||||||
throw new UnsupportedOperationException("TODO: implement thread-safe withdraw");
|
rwLock.writeLock().lock();
|
||||||
|
try {
|
||||||
|
balance -= amount;
|
||||||
|
} finally {
|
||||||
|
rwLock.writeLock().unlock();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -73,6 +94,29 @@ public class BankAccount {
|
|||||||
* - Or tryLock with retry strategy
|
* - Or tryLock with retry strategy
|
||||||
*/
|
*/
|
||||||
public void transfer(BankAccount target, long amount) {
|
public void transfer(BankAccount target, long amount) {
|
||||||
throw new UnsupportedOperationException("TODO: implement atomic deadlock-free transfer");
|
BankAccount first;
|
||||||
|
BankAccount second;
|
||||||
|
|
||||||
|
if (this.getAccountId() < target.getAccountId()) {
|
||||||
|
first = this;
|
||||||
|
second = target;
|
||||||
|
} else {
|
||||||
|
first = target;
|
||||||
|
second = this;
|
||||||
|
}
|
||||||
|
|
||||||
|
first.transferLock.lock();
|
||||||
|
|
||||||
|
try {
|
||||||
|
second.transferLock.lock();
|
||||||
|
try {
|
||||||
|
first.balance -= amount;
|
||||||
|
target.balance += amount;
|
||||||
|
} finally {
|
||||||
|
second.transferLock.unlock();
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
first.transferLock.unlock();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Reference in New Issue
Block a user