generated from JavaLabs2025/concurrency-lab1
-
Notifications
You must be signed in to change notification settings - Fork 37
Lab-1 | Dinning Programmers | Барковская Мария Александровна #9
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
mmmmarryyy
wants to merge
4
commits into
JavaLabs2025:master
Choose a base branch
from
JavaLabs2025:master
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,7 +1,70 @@ | ||
| package org.labs; | ||
|
|
||
| import org.apache.commons.cli.*; | ||
| import org.slf4j.Logger; | ||
| import org.slf4j.LoggerFactory; | ||
|
|
||
| import org.labs.lunch.Restaurant; | ||
|
|
||
| import java.util.concurrent.TimeUnit; | ||
|
|
||
| public class Main { | ||
| public static void main(String[] args) { | ||
| System.out.println("Hello, World!"); | ||
| final Logger logger = LoggerFactory.getLogger(Main.class); | ||
|
|
||
| int programmersCount = 7; | ||
| int waitersCount = 2; | ||
| int portionsCount = 5_000; | ||
| int timeout = 60; | ||
|
|
||
| Options options = new Options(); | ||
| options.addOption("p", "programmers", true, "Number of programmers"); | ||
| options.addOption("w", "waiters", true, "Number of waiters"); | ||
| options.addOption("f", "food", true, "Total portions count"); | ||
| options.addOption("t", "timeout", true, "Timeout in seconds"); | ||
|
|
||
| CommandLineParser parser = new DefaultParser(); | ||
| try { | ||
| CommandLine cmd = parser.parse(options, args); | ||
|
|
||
| if (cmd.hasOption("p")) { | ||
| programmersCount = Integer.parseInt(cmd.getOptionValue("p")); | ||
| } | ||
| if (cmd.hasOption("w")) { | ||
| waitersCount = Integer.parseInt(cmd.getOptionValue("w")); | ||
| } | ||
| if (cmd.hasOption("f")) { | ||
| portionsCount = Integer.parseInt(cmd.getOptionValue("f")); | ||
| } | ||
| if (cmd.hasOption("t")) { | ||
| timeout = Integer.parseInt(cmd.getOptionValue("t")); | ||
| } | ||
| } catch (ParseException e) { | ||
| logger.error("Error parsing arguments", e); | ||
| new HelpFormatter().printHelp("dining-philosophers", options); | ||
| return; | ||
| } | ||
|
|
||
| logger.info( | ||
| "Starting simulation with {} programmers, {} waiters, {} portions", | ||
| programmersCount, | ||
| waitersCount, | ||
| portionsCount | ||
| ); | ||
|
|
||
| Restaurant restaurant = new Restaurant(programmersCount, waitersCount, portionsCount); | ||
| restaurant.start(); | ||
|
|
||
| try { | ||
| if (!restaurant.awaitCompletion(timeout, TimeUnit.SECONDS)) { | ||
| logger.error("Simulation timed out!"); | ||
| restaurant.shutdownNow(); | ||
| } | ||
| } catch (InterruptedException e) { | ||
| Thread.currentThread().interrupt(); | ||
| restaurant.shutdownNow(); | ||
| } finally { | ||
| restaurant.printStatistics(); | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,52 @@ | ||
| package org.labs.lunch; | ||
|
|
||
| public class DinningTable { | ||
|
|
||
| private final int programmersCount; | ||
| private final Spoon[] spoons; | ||
|
|
||
| public DinningTable(int programmersCount) { | ||
| this.programmersCount = programmersCount; | ||
|
|
||
| this.spoons = new Spoon[programmersCount]; | ||
| for (int i = 0; i < programmersCount; i++) { | ||
| this.spoons[i] = new Spoon(i); | ||
| } | ||
|
|
||
| } | ||
|
|
||
| private class SpoonPair { | ||
| int firstSpoonId; | ||
| int secondSpoonId; | ||
|
|
||
| SpoonPair(int firstSpoonId, int secondSpoonId) { | ||
| this.firstSpoonId = firstSpoonId; | ||
| this.secondSpoonId = secondSpoonId; | ||
| } | ||
| } | ||
|
|
||
| private SpoonPair getOrderedSpoonIds(int programmerId) { | ||
| int leftSpoonId = programmerId; | ||
| int rightSpoonId = (programmerId + 1) % programmersCount; | ||
|
|
||
| if (leftSpoonId < rightSpoonId) { | ||
| return new SpoonPair(leftSpoonId, rightSpoonId); | ||
| } else { | ||
| return new SpoonPair(rightSpoonId, leftSpoonId); | ||
| } | ||
| } | ||
|
|
||
| void takeSpoons(int programmerId) { | ||
| SpoonPair spoonPair = getOrderedSpoonIds(programmerId); | ||
|
|
||
| spoons[spoonPair.firstSpoonId].lock(); | ||
| spoons[spoonPair.secondSpoonId].lock(); | ||
| } | ||
|
|
||
| void putSpoons(int programmerId) { | ||
| SpoonPair spoonPair = getOrderedSpoonIds(programmerId); | ||
|
|
||
| spoons[spoonPair.secondSpoonId].unlock(); | ||
| spoons[spoonPair.firstSpoonId].unlock(); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,84 @@ | ||
| package org.labs.lunch; | ||
|
|
||
| import org.slf4j.Logger; | ||
| import org.slf4j.LoggerFactory; | ||
|
|
||
| import java.util.concurrent.ThreadLocalRandom; | ||
|
|
||
| public class Programmer implements Runnable { | ||
| private static final Logger logger = LoggerFactory.getLogger(Programmer.class); | ||
|
|
||
| private final int id; | ||
| private int portionsEaten = 0; | ||
| private volatile boolean hasSoupPortion; | ||
| private final Restaurant restaurant; | ||
| private final ThreadLocalRandom random = ThreadLocalRandom.current(); | ||
| private final Object plateMonitor = new Object(); | ||
|
|
||
| private final long minThinkTime = 20; | ||
| private final long maxThinkTime = 40; | ||
| private final long minEatTime = 10; | ||
| private final long maxEatTime = 20; | ||
|
|
||
| public Programmer(int programmerId, Restaurant restaurant) { | ||
| this.id = programmerId; | ||
| this.hasSoupPortion = false; | ||
| this.restaurant = restaurant; | ||
| } | ||
|
|
||
| @Override | ||
| public void run() { | ||
| try { | ||
| while (restaurant.isRunning() && (restaurant.getPortionsCount().get() > 0 || hasSoupPortion)) { | ||
| think(); | ||
|
|
||
| synchronized (plateMonitor) { | ||
| while (!hasSoupPortion && restaurant.isRunning()) { | ||
| if (restaurant.getPortionsCount().get() == 0) { | ||
| return; | ||
| } | ||
|
|
||
| restaurant.requestPortion(this); | ||
| plateMonitor.wait(); | ||
| } | ||
| } | ||
|
|
||
| restaurant.getDinningTable().takeSpoons(id); | ||
| eat(); | ||
| restaurant.getDinningTable().putSpoons(id); | ||
| } | ||
| } catch (InterruptedException ex) { | ||
| logger.debug("Programmer {} interrupted", id); | ||
| Thread.currentThread().interrupt(); | ||
| } catch (Exception ex) { | ||
| logger.error("Programmer {} encountered unexpected exception", id, ex); | ||
| } | ||
| } | ||
|
|
||
| private void think() throws InterruptedException { | ||
| long duration = random.nextLong(minThinkTime, maxThinkTime); | ||
| logger.debug("Programmer {} thinking for {}ms", id, duration); | ||
| Thread.sleep(duration); | ||
| } | ||
|
|
||
| private void eat() throws InterruptedException { | ||
| long duration = random.nextLong(minEatTime, maxEatTime); | ||
| logger.debug("Programmer {} eating for {}ms", id, duration); | ||
| Thread.sleep(duration); | ||
|
|
||
| hasSoupPortion = false; | ||
| portionsEaten += 1; | ||
| } | ||
|
|
||
| public void refillPlateWithSoup() { | ||
| synchronized (plateMonitor) { | ||
kechinvv marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| hasSoupPortion = true; | ||
| plateMonitor.notifyAll(); | ||
| } | ||
| } | ||
|
|
||
|
|
||
| public int getId() { return id; } | ||
| public int getPortionsEaten() { return portionsEaten; } | ||
| public Object getPlateMonitor() { return plateMonitor; } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,106 @@ | ||
| package org.labs.lunch; | ||
|
|
||
| import org.slf4j.Logger; | ||
| import org.slf4j.LoggerFactory; | ||
|
|
||
| import java.util.ArrayList; | ||
| import java.util.Comparator; | ||
| import java.util.List; | ||
| import java.util.concurrent.ExecutorService; | ||
| import java.util.concurrent.Executors; | ||
| import java.util.concurrent.PriorityBlockingQueue; | ||
| import java.util.concurrent.TimeUnit; | ||
| import java.util.concurrent.atomic.AtomicInteger; | ||
|
|
||
| public class Restaurant { | ||
| private static final Logger logger = LoggerFactory.getLogger(Restaurant.class); | ||
|
|
||
| private final AtomicInteger portionsCount; | ||
| private final PriorityBlockingQueue<Programmer> portionsAskQueue; | ||
|
|
||
| private final List<Programmer> programmersList; | ||
| private final ExecutorService programmersExecutor; | ||
|
|
||
| private final int waitersCount; | ||
| private final ExecutorService waitersExecutor; | ||
|
|
||
| private final DinningTable dinningTable; | ||
|
|
||
| private volatile boolean isRunning = true; | ||
|
|
||
| public Restaurant(int programmersCount, int waiterCount, int portionsCount) { | ||
| this.portionsCount = new AtomicInteger(portionsCount); | ||
| this.portionsAskQueue = new PriorityBlockingQueue<>( | ||
| programmersCount, | ||
| Comparator.comparingInt(Programmer::getPortionsEaten) | ||
| ); | ||
| this.programmersList = new ArrayList<>(); | ||
| this.programmersExecutor = Executors.newFixedThreadPool(programmersCount); | ||
kechinvv marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| this.waitersCount = waiterCount; | ||
| this.waitersExecutor = Executors.newFixedThreadPool(waiterCount); | ||
| this.dinningTable = new DinningTable(programmersCount); | ||
|
|
||
| for (int i = 0; i < programmersCount; i++) { | ||
| Programmer programmer = new Programmer(i, this); | ||
| programmersList.add(programmer); | ||
| } | ||
| } | ||
|
|
||
| public void start() { | ||
| for (Programmer programmer : programmersList) { | ||
| programmersExecutor.submit(programmer); | ||
| } | ||
|
|
||
| for (int i = 0; i < this.waitersCount; i++) { | ||
| Waiter waiter = new Waiter(i, this); | ||
| waitersExecutor.submit(waiter); | ||
| } | ||
| } | ||
|
|
||
| public boolean awaitCompletion(long timeout, TimeUnit unit) throws InterruptedException { | ||
| programmersExecutor.shutdown(); | ||
| boolean completed = programmersExecutor.awaitTermination(timeout, unit); | ||
| isRunning = false; | ||
| waitersExecutor.shutdownNow(); | ||
| return completed; | ||
| } | ||
|
|
||
| public void shutdownNow() { | ||
| isRunning = false; | ||
| programmersExecutor.shutdownNow(); | ||
| waitersExecutor.shutdownNow(); | ||
| } | ||
|
|
||
| public void printStatistics() { | ||
| int totalEaten = 0; | ||
| for (Programmer programmer : programmersList) { | ||
| int eaten = programmer.getPortionsEaten(); | ||
| logger.info("Programmer {} ate {} portions", programmer.getId(), eaten); | ||
| totalEaten += eaten; | ||
| } | ||
|
|
||
| logger.info("Total portions eaten: {} (remaining: {})", totalEaten, portionsCount.get()); | ||
|
|
||
| double average = totalEaten / (double) programmersList.size(); | ||
| double fairnessThreshold = average * 0.01; | ||
|
|
||
| for (Programmer programmer : programmersList) { | ||
| int eaten = programmer.getPortionsEaten(); | ||
| double deviation = Math.abs(eaten - average); | ||
| if (deviation > fairnessThreshold) { | ||
| logger.warn("Programmer {} deviation too high: {} > {}", programmer.getId(), deviation, fairnessThreshold); | ||
kechinvv marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } | ||
| } | ||
| } | ||
|
|
||
| void requestPortion(Programmer programmer) throws InterruptedException { | ||
| portionsAskQueue.put(programmer); | ||
| } | ||
|
|
||
|
|
||
| public AtomicInteger getPortionsCount() { return portionsCount; } | ||
| public PriorityBlockingQueue<Programmer> getPortionsAskQueue() { return portionsAskQueue; } | ||
| public List<Programmer> getProgrammersList() { return programmersList; } | ||
| public DinningTable getDinningTable() { return dinningTable; } | ||
| public boolean isRunning() { return isRunning; } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,21 @@ | ||
| package org.labs.lunch; | ||
|
|
||
| import java.util.concurrent.locks.ReentrantLock; | ||
|
|
||
| public class Spoon { | ||
| private final int id; | ||
| private final ReentrantLock lock; | ||
|
|
||
| public Spoon(int id) { | ||
| this.id = id; | ||
| lock = new ReentrantLock(true); | ||
| } | ||
|
|
||
| public void lock() { | ||
| lock.lock(); | ||
| } | ||
|
|
||
| public void unlock() { | ||
| lock.unlock(); | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.