2 Commits
Author SHA1 Message Date
MehrdadShirvani 022be2bd13 Merge PR 'Advansed molti threading + report' (#1) from develop into main
80/100 (answers to the theory part has some issues)
2/3 of bonus points (issues in the transfer method)
2026-07-10 17:44:44 +00:00
ZahraSadatMirvakili 492957ebce Advansed molti threading + report 2026-06-10 14:57:02 +03:30
9 changed files with 216 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="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>
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Central Repository" />
<option name="url" value="https://mirror-maven.runflare.com/maven2" />
</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>
@@ -1,10 +1,14 @@
package dev.banking.model;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class BankAccount {
private final int accountId;
private long balance;
private final ReentrantLock lock = new ReentrantLock();
private final Condition sufficientFunds = lock.newCondition();
/*
* Students may introduce additional fields
* such as:
@@ -23,56 +27,76 @@ public class BankAccount {
return accountId;
}
/*
* 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 balance;
}finally {
lock.unlock();
}
}
/*
* TODO:
* Increase balance atomically.
*
* Requirements:
* - Must not lose updates under concurrency
*/
public void deposit(long amount) {
throw new UnsupportedOperationException("TODO: implement thread-safe deposit");
lock.lock();
try {
this.balance += amount;
sufficientFunds.signalAll();
}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)
*/
public void withdraw(long amount) {
throw new UnsupportedOperationException("TODO: implement thread-safe withdraw");
lock.lock();
try {
while (balance < amount){
sufficientFunds.await();
}
balance -= amount;
} catch (InterruptedException e) {
throw new RuntimeException(e);
} 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 (this == target){
return;
}
BankAccount first = this.accountId < target.getAccountId() ? this : target;
BankAccount second = this.accountId < target.getAccountId() ? target : this;
first.lock.lock();
try{
second.lock.lock();
try{
BankAccount source = this;
BankAccount dest = target;
if (first == target){
source = target;
dest = this;
}
while (source.balance < amount){
source.sufficientFunds.await();
}
source.balance -= amount;
dest.balance += amount;
dest.sufficientFunds.signalAll();
} catch (InterruptedException e) {
throw new RuntimeException(e);
} finally {
second.lock.unlock();
}
}finally {
first.lock.unlock();
}
}
}
@@ -0,0 +1,27 @@
package dev.banking.model;
import java.util.concurrent.atomic.AtomicInteger;
public class RaceConditionDemo {
private static int normalCounter;
private static AtomicInteger atomicCounter = new AtomicInteger(0);
public static void main(String[] args) throws InterruptedException{
Thread [] thread = new Thread[1000];
for (int i = 0; i < 1000; i++) {
thread[i] = new Thread(() -> {
for (int j = 0; j < 1000; j++) {
normalCounter ++;
atomicCounter.incrementAndGet();
}
});
thread[i].start();
}
for (Thread t : thread){
t.join();
}
System.out.println("Normal: " + normalCounter);
System.out.println("Atomic: " + atomicCounter);
}
}
+55
View File
@@ -0,0 +1,55 @@
# Answer - Theoretical Questions
## 1.What are atomic variable?
Atomic variables are variables that support lock-free, thread-safe operations on single variables.
They ensure that read-modify-write operations (like increment, compare-and-set) are performed atomically without interruption.
**Difference from ordinary variables: ** ordinary variables are not thread safe ; concurrent access can race conditions.
Atomic variables provide built-in thread safety without explicit synchronization.
## 2.Four classes from java.util.concurrent.atomic
- 'AtomicInteger'
- 'AtomicLong'
- 'AtomicBoolean'
- 'AtomicReference'
**Use case for AtomicInteger:** A request counter in a web server that is incremented concurrently by multiple threads.
AtomicInteger ensures the count never misses an increment.
## 3.Compare locks with atomic variables
| Scenario | Better Choice |
|-------------------------------------------------|----------------|
| Simple counter or single variable update | Atomic variable (lower overhead) |
| Multiple related variables (like bank transfer) | Lock (to ensure multi-step atomicity) |
**Conclusion:** Use atomics for simple state, locks for compound actions.
## 4. A program free of race conditions but poor under high contention
This happens due to **scalability limitations** even when correctness is guaranteed. Possible factors:
1. **Lock contention** Threads spend time waiting for locks instead of doing work.
2. **Context switching overhead** Frequent thread switching wastes CPU cycles.
3. **Cache coherence traffic** Cores invalidate and refresh cache lines repeatedly.
## 5. Why adding more threads does not always improve performance
- **Context switching** Saving/restoring thread state has cost.
- **Contention** Threads compete for shared resources.
- **Cache coherence** Multiple cores must synchronize caches.
- **Synchronization overhead** Locks and barriers slow execution.
Adding more threads beyond CPU core count typically increases overhead without benefit.
## 6. Why deadlocks appear in production, not testing
**From thread-scheduling perspective:** Testing environments have predictable scheduling,
low load, and short runtimes. Production has unpredictable interleaving, high concurrency, and longer execution windows.
**Two strategies to expose deadlocks during testing:**
1. Run tests thousands of times with randomized thread interleavings.
2. Use tools or `Thread.sleep` at random points to force rare scheduling patterns.