Theorical questions are in REPORT.md and practical tasks are implemented
This commit is contained in:
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://repo.maven.apache.org/maven2" />
|
||||
</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>
|
||||
@@ -0,0 +1,75 @@
|
||||
# REPORT
|
||||
### Hesam Ghazi
|
||||
### 403222015
|
||||
## 1. Atomic Variables
|
||||
Atomic variables provide thread-safe single-variable operations performed atomically using CPU-supported compare-and-swap (CAS) instructions. Unlike ordinary variables, they prevent race conditions without explicit synchronization for simple operations.
|
||||
|
||||
## 2. Atomic Classes
|
||||
- `AtomicInteger`
|
||||
- `AtomicLong`
|
||||
- `AtomicBoolean`
|
||||
- `AtomicReference<T>`
|
||||
|
||||
**Use case:** `AtomicInteger` is commonly used as a thread-safe counter shared among multiple threads.
|
||||
|
||||
## 3. Locks vs Atomic Variables
|
||||
**Atomic variables**
|
||||
- Best for simple read-modify-write operations.
|
||||
- Non-blocking and usually faster under low contention.
|
||||
- Limited to simple operations.
|
||||
|
||||
**Locks**
|
||||
- Suitable for protecting multiple variables or complex critical sections.
|
||||
- Easier to implement compound operations atomically.
|
||||
- Introduce blocking and context-switch overhead.
|
||||
|
||||
## Bonus Task
|
||||
|
||||
```java
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
public class AtomicDemo {
|
||||
static int normal = 0;
|
||||
static AtomicInteger atomic = new AtomicInteger(0);
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
Thread[] threads = new Thread[10];
|
||||
for (int i = 0; i < threads.length; i++) {
|
||||
threads[i] = new Thread(() -> {
|
||||
for (int j = 0; j < 100000; j++) {
|
||||
normal++;
|
||||
atomic.incrementAndGet();
|
||||
}
|
||||
});
|
||||
}
|
||||
for (Thread t : threads) t.start();
|
||||
for (Thread t : threads) t.join();
|
||||
|
||||
System.out.println("Normal: " + normal);
|
||||
System.out.println("Atomic: " + atomic.get());
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Expected: `AtomicInteger` always prints 1000000, while `normal` is usually smaller because of race conditions.
|
||||
|
||||
## 4. Correct but Poor Performance
|
||||
A program may be race-free but still scale poorly because:
|
||||
1. High lock contention forces threads to wait.
|
||||
2. Excessive synchronization increases overhead.
|
||||
3. False sharing and cache coherence traffic reduce CPU efficiency.
|
||||
4. Frequent blocking decreases parallelism.
|
||||
|
||||
## 5. Why More Threads Can Hurt
|
||||
- **Context switching:** CPU spends time switching threads.
|
||||
- **Contention:** Threads compete for shared resources.
|
||||
- **Cache coherence:** Shared data invalidates CPU caches.
|
||||
- **Synchronization overhead:** Locks and coordination consume execution time.
|
||||
- Too many threads may exceed available CPU cores, reducing throughput.
|
||||
|
||||
## 6. Why Deadlocks Often Appear Only in Production
|
||||
Deadlocks depend on thread scheduling, which is nondeterministic. Testing usually explores only a small subset of possible execution orders, whereas production workloads create many timing combinations.
|
||||
|
||||
Two strategies to expose deadlocks:
|
||||
1. Perform stress tests with many threads and randomized execution timing.
|
||||
2. Insert artificial delays (sleep/yield) around lock acquisition to increase unfavorable interleavings.
|
||||
@@ -1,18 +1,15 @@
|
||||
package dev.banking.model;
|
||||
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
|
||||
public class BankAccount {
|
||||
|
||||
private final int accountId;
|
||||
private long balance;
|
||||
|
||||
/*
|
||||
* Students may introduce additional fields
|
||||
* such as:
|
||||
* - Lock / ReentrantLock
|
||||
* - ReadWriteLock
|
||||
* - Object monitor
|
||||
* - etc.
|
||||
*/
|
||||
// explicit ReentrantLock associated with each individual account
|
||||
// to provide independent lock contention per account
|
||||
private final ReentrantLock lock = new ReentrantLock();
|
||||
|
||||
public BankAccount(int accountId, long initialBalance) {
|
||||
this.accountId = accountId;
|
||||
@@ -24,55 +21,75 @@ public class BankAccount {
|
||||
}
|
||||
|
||||
/*
|
||||
* TODO:
|
||||
* Return the current balance in a thread-safe way.
|
||||
*
|
||||
* Requirements:
|
||||
* - Must be safe under concurrent reads/writes
|
||||
* - Should not block unnecessarily if using read/write locks
|
||||
*/
|
||||
public long getBalance() {
|
||||
throw new UnsupportedOperationException("TODO: implement thread-safe balance read");
|
||||
lock.lock();
|
||||
try {
|
||||
return this.balance;
|
||||
} finally {
|
||||
lock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* TODO:
|
||||
* Increase balance atomically.
|
||||
*
|
||||
* Requirements:
|
||||
* - Must not lose updates under concurrency
|
||||
* increase balance atomically
|
||||
*/
|
||||
public void deposit(long amount) {
|
||||
throw new UnsupportedOperationException("TODO: implement thread-safe deposit");
|
||||
if (amount <= 0) {
|
||||
throw new IllegalArgumentException("Deposit amount must be positive.");
|
||||
}
|
||||
lock.lock();
|
||||
try {
|
||||
this.balance += amount;
|
||||
} finally {
|
||||
lock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* TODO:
|
||||
* Decrease balance atomically.
|
||||
*
|
||||
* Requirements:
|
||||
* - Must not cause race conditions
|
||||
* - Negative balance handling is NOT required unless you decide
|
||||
* to extend the system (optional)
|
||||
* Decrease balance atomically
|
||||
*/
|
||||
public void withdraw(long amount) {
|
||||
throw new UnsupportedOperationException("TODO: implement thread-safe withdraw");
|
||||
if (amount <= 0) {
|
||||
throw new IllegalArgumentException("Withdrawal amount must be positive.");
|
||||
}
|
||||
lock.lock();
|
||||
try {
|
||||
this.balance -= amount;
|
||||
} finally {
|
||||
lock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* TODO:
|
||||
* Transfer money between two accounts atomically.
|
||||
*
|
||||
* IMPORTANT REQUIREMENTS:
|
||||
* - Must be atomic (no partial transfer)
|
||||
* - Must be deadlock-free
|
||||
* - Must protect both source and target accounts
|
||||
*
|
||||
* HINT:
|
||||
* - Consider global lock ordering using accountId
|
||||
* - Or tryLock with retry strategy
|
||||
*/
|
||||
|
||||
public void transfer(BankAccount target, long amount) {
|
||||
throw new UnsupportedOperationException("TODO: implement atomic deadlock-free transfer");
|
||||
if (target == null) {
|
||||
throw new IllegalArgumentException("Target account cannot be null.");
|
||||
}
|
||||
if (this.accountId == target.getAccountId()) {
|
||||
throw new IllegalArgumentException("Cannot transfer to the same account.");
|
||||
}
|
||||
if (amount <= 0) {
|
||||
throw new IllegalArgumentException("Transfer amount must be positive.");
|
||||
}
|
||||
|
||||
// Establish an absolute ordering to acquire locks
|
||||
BankAccount firstLock = this.accountId < target.getAccountId() ? this : target;
|
||||
BankAccount secondLock = this.accountId < target.getAccountId() ? target : this;
|
||||
|
||||
firstLock.lock.lock();
|
||||
try {
|
||||
secondLock.lock.lock();
|
||||
try {
|
||||
// Perform the atomic transfer operations
|
||||
this.withdraw(amount);
|
||||
target.deposit(amount);
|
||||
} finally {
|
||||
secondLock.lock.unlock();
|
||||
}
|
||||
} finally {
|
||||
firstLock.lock.unlock();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user