Theorical questions are in REPORT.md and practical tasks are implemented #1

Open
HesamGhazi wants to merge 1 commits from develop into main
8 changed files with 202 additions and 42 deletions
+10
View File
@@ -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/
+13
View File
@@ -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>
+7
View File
@@ -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>
+20
View File
@@ -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>
+12
View File
@@ -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
View File
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
</project>
+75
View File
@@ -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; package dev.banking.model;
import java.util.concurrent.locks.ReentrantLock;
public class BankAccount { public class BankAccount {
private final int accountId; private final int accountId;
private long balance; private long balance;
/* // explicit ReentrantLock associated with each individual account
* Students may introduce additional fields // to provide independent lock contention per account
* such as: private final ReentrantLock lock = new ReentrantLock();
* - Lock / ReentrantLock
* - ReadWriteLock
* - Object monitor
* - etc.
*/
public BankAccount(int accountId, long initialBalance) { public BankAccount(int accountId, long initialBalance) {
this.accountId = accountId; this.accountId = accountId;
@@ -24,55 +21,75 @@ public class BankAccount {
} }
/* /*
* TODO:
* Return the current balance in a thread-safe way. * 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() { 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
* Increase balance atomically.
*
* Requirements:
* - Must not lose updates under concurrency
*/ */
public void deposit(long amount) { 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
* Decrease balance atomically.
*
* Requirements:
* - Must not cause race conditions
* - Negative balance handling is NOT required unless you decide
* to extend the system (optional)
*/ */
public void withdraw(long amount) { 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) { 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();
}
} }
} }