generated from JavaLabs2025/concurrency-lab1
-
Notifications
You must be signed in to change notification settings - Fork 37
a.k.lysenko solution #3
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
kalin11
wants to merge
9
commits into
JavaLabs2025:review1
Choose a base branch
from
JavaLabs2025:a.k.lysenko-solution
base: review1
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
9 commits
Select commit
Hold shift + click to select a range
eec6dc8
add deadline
github-classroom[bot] db8338a
init commit
f202f2d
non-working draft
6d98726
no deadlock, but there's problem with sync eat count
54ad97e
fix peek with poll in QueueService
afb106f
tiny refactor
60cf979
working thing
b6738c9
add timeout_ms param to config
0c581a3
fix params reader
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
Empty file.
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,45 @@ | ||
| package org.labs; | ||
|
|
||
| import lombok.extern.slf4j.Slf4j; | ||
| import org.labs.io.ParamsReader; | ||
| import org.labs.service.FoodService; | ||
| import org.labs.service.QueueService; | ||
|
|
||
| import java.util.concurrent.Executors; | ||
| import java.util.concurrent.TimeUnit; | ||
|
|
||
| import static org.labs.configuration.ConfigurationParam.EAT_COUNT; | ||
| import static org.labs.configuration.ConfigurationParam.PROGRAMMERS_COUNT; | ||
| import static org.labs.configuration.ConfigurationParam.WAITERS_COUNT; | ||
|
|
||
| @Slf4j | ||
| public class Main { | ||
| public static void main(String[] args) { | ||
| System.out.println("Hello, World!"); | ||
| var reader = new ParamsReader(); | ||
|
|
||
| var params = reader.getParamsAsMap("src/main/resources/params"); | ||
| var eatCount = params.get(EAT_COUNT); | ||
|
|
||
| var queueService = new QueueService(); | ||
| var foodService = new FoodService(eatCount); | ||
|
|
||
| var waiters = Executors.newFixedThreadPool(params.get(WAITERS_COUNT)); | ||
| var programmers = Executors.newFixedThreadPool(params.get(PROGRAMMERS_COUNT)); | ||
|
|
||
| var simulation = new Simulation(params, queueService, foodService); | ||
| simulation.run(waiters, programmers); | ||
|
|
||
| waiters.shutdown(); | ||
| programmers.shutdown(); | ||
| try { | ||
| waiters.awaitTermination(60, TimeUnit.SECONDS); | ||
| programmers.awaitTermination(60, TimeUnit.SECONDS); | ||
| } catch (InterruptedException e) { | ||
| Thread.currentThread().interrupt(); | ||
| } | ||
|
|
||
| log.info("Симуляция завершена. Сколько поел каждый:"); | ||
| foodService.getProgrammerIdToSoupCount().forEach((id, count) -> | ||
| log.info("Программист {} поел {} раз", id, count)); | ||
| } | ||
| } | ||
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,67 @@ | ||
| package org.labs; | ||
|
|
||
| import lombok.extern.slf4j.Slf4j; | ||
| import org.labs.configuration.ConfigurationParam; | ||
| import org.labs.model.Fork; | ||
| import org.labs.model.Programmer; | ||
| import org.labs.model.Waiter; | ||
| import org.labs.service.FoodService; | ||
| import org.labs.service.QueueService; | ||
|
|
||
| import java.util.ArrayList; | ||
| import java.util.List; | ||
| import java.util.Map; | ||
| import java.util.concurrent.ExecutorService; | ||
| import java.util.concurrent.locks.ReentrantLock; | ||
|
|
||
| import static org.labs.configuration.ConfigurationParam.PROGRAMMERS_COUNT; | ||
| import static org.labs.configuration.ConfigurationParam.TIMEOUT_MS; | ||
| import static org.labs.configuration.ConfigurationParam.WAITERS_COUNT; | ||
|
|
||
| @Slf4j | ||
| public class Simulation { | ||
| private final Map<ConfigurationParam, Integer> params; | ||
| private final QueueService queueService; | ||
| private final FoodService foodService; | ||
|
|
||
| private final List<Fork> forks; | ||
|
|
||
| public Simulation(Map<ConfigurationParam, Integer> params, QueueService queueService, FoodService foodService) { | ||
| this.params = params; | ||
| this.queueService = queueService; | ||
| this.foodService = foodService; | ||
| this.forks = new ArrayList<>(); | ||
| } | ||
|
|
||
| public void run(ExecutorService waiters, ExecutorService programmers) { | ||
| log.info("Начали симуляцию"); | ||
| foodService.initSoups(params.get(PROGRAMMERS_COUNT)); | ||
| fillForks(params.get(PROGRAMMERS_COUNT)); | ||
| fillProgrammers(params.get(PROGRAMMERS_COUNT), programmers, params.get(TIMEOUT_MS)); | ||
| createWaiters(params.get(WAITERS_COUNT), waiters, params.get(TIMEOUT_MS)); | ||
| } | ||
|
|
||
| private void fillForks(int forksCount) { | ||
| for (int i = 0; i < forksCount; i++) { | ||
| forks.add(new Fork(i + 1, new ReentrantLock())); | ||
| } | ||
| } | ||
|
|
||
| private void fillProgrammers(int programmersCount, ExecutorService executor, long timeoutMs) { | ||
| for (int i = 0; i < programmersCount; i++) { | ||
| var programmer = new Programmer(i + 1, foodService, queueService, timeoutMs); | ||
| programmer.setState(Programmer.State.HUNGRY); | ||
| var left = forks.get(i); | ||
| var right = forks.get((i + 1) % programmersCount); | ||
| programmer.setLeft(left.id() < right.id() ? left : right); | ||
| programmer.setRight(left.id() < right.id() ? right : left); | ||
| executor.submit(programmer); | ||
| } | ||
| } | ||
|
|
||
| private void createWaiters(int waitersCount, ExecutorService executor, long timeoutMs) { | ||
| for (int i = 0; i < waitersCount; i++) { | ||
| executor.submit(new Waiter(i + 1, queueService, foodService, timeoutMs)); | ||
| } | ||
| } | ||
| } |
27 changes: 27 additions & 0 deletions
27
src/main/java/org/labs/configuration/ConfigurationParam.java
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,27 @@ | ||
| package org.labs.configuration; | ||
|
|
||
| import lombok.Getter; | ||
|
|
||
| @Getter | ||
| public enum ConfigurationParam { | ||
| PROGRAMMERS_COUNT("programmers_count"), | ||
| EAT_COUNT("eat_count"), | ||
| WAITERS_COUNT("waiters_count"), | ||
| TIMEOUT_MS("timeout_ms"), | ||
| ; | ||
|
|
||
| private final String value; | ||
|
|
||
| ConfigurationParam(String value) { | ||
| this.value = value; | ||
| } | ||
|
|
||
| public static ConfigurationParam fromValue(String value) { | ||
| for (ConfigurationParam param : values()) { | ||
| if (param.value.equals(value)) { | ||
| return param; | ||
| } | ||
| } | ||
| throw new IllegalArgumentException("No enum constant with value " + value); | ||
| } | ||
| } |
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,26 @@ | ||
| package org.labs.io; | ||
|
|
||
| import org.labs.configuration.ConfigurationParam; | ||
|
|
||
| import java.io.IOException; | ||
| import java.nio.file.Files; | ||
| import java.nio.file.Paths; | ||
| import java.util.Map; | ||
| import java.util.stream.Collectors; | ||
|
|
||
| public class ParamsReader { | ||
| private static final String SEPARATOR = "="; | ||
|
|
||
| public Map<ConfigurationParam, Integer> getParamsAsMap(String filePath) { | ||
| try (var lines = Files.lines(Paths.get(filePath))) { | ||
| return lines | ||
| .map(line -> line.split(SEPARATOR)) | ||
| .collect(Collectors.toMap( | ||
| values -> ConfigurationParam.fromValue(values[0]), | ||
| values -> Integer.parseInt(values[1]) | ||
| )); | ||
| } catch (IOException e) { | ||
| throw new RuntimeException("Can't read file " + filePath, e); | ||
| } | ||
| } | ||
| } |
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.model; | ||
|
|
||
| import lombok.extern.slf4j.Slf4j; | ||
|
|
||
| import java.util.concurrent.locks.Lock; | ||
|
|
||
| @Slf4j | ||
| public record Fork( | ||
| int id, | ||
| Lock lock | ||
| ) { | ||
| public void pickUp(int programmerId) { | ||
| lock.lock(); | ||
| log.info("Программист {} взял вилку с id {}", programmerId, id); | ||
| } | ||
|
|
||
| public void pickDown(int programmerId) { | ||
| lock.unlock(); | ||
| log.info("Программист {} положил вилку с id {}", programmerId, id); | ||
| } | ||
| } |
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,86 @@ | ||
| package org.labs.model; | ||
|
|
||
| import lombok.Getter; | ||
| import lombok.RequiredArgsConstructor; | ||
| import lombok.Setter; | ||
| import lombok.SneakyThrows; | ||
| import lombok.extern.slf4j.Slf4j; | ||
| import org.labs.service.FoodService; | ||
| import org.labs.service.QueueService; | ||
|
|
||
| @Getter | ||
| @RequiredArgsConstructor | ||
| @Slf4j | ||
| public class Programmer implements Runnable { | ||
| private final int id; | ||
| @Setter | ||
| private State state; | ||
| @Setter | ||
| private Fork left; | ||
| @Setter | ||
| private Fork right; | ||
|
|
||
| private final FoodService foodService; | ||
| private final QueueService queueService; | ||
| private final long timeoutMs; | ||
|
|
||
| @Override | ||
| @SneakyThrows | ||
| public void run() { | ||
| while (foodService.getEatCount().get() > 0) { | ||
| this.state = State.HUNGRY; | ||
| log.info("Программист: {}, осталось еды - {}", id, foodService.getEatCount()); | ||
|
|
||
| while (!foodService.hasSoup(id)) { | ||
| if (foodService.getEatCount().get() < 1) { | ||
| break; | ||
| } | ||
| log.info("Нет супа, программист с id = {} не может поесть. Он будет ждать, когда пополнится порция", id); | ||
| if (queueService.contains(id)) { | ||
| log.warn("Программист {} уже в очереди", id); | ||
| } | ||
| if (!queueService.contains(id) && foodService.getEatCount().get() > 0) { | ||
| queueService.put(id); | ||
| } | ||
|
|
||
| Thread.sleep(timeoutMs); | ||
| // сказать, что нет супа и дождаться, пока он появиться, то есть кинуть поток в сон | ||
| } | ||
|
|
||
| if (foodService.hasSoup(id) && foodService.getEatCount().get() > 0) { | ||
| try { | ||
| left.pickUp(id); | ||
| right.pickUp(id); | ||
|
|
||
| state = State.EATING; | ||
|
|
||
| log.info("Программист {} начал кушать суп", id); | ||
|
|
||
| foodService.disableSoup(id); | ||
|
|
||
| } finally { | ||
| log.info("Программист {} закончил есть суп и собирается положить вилки", id); | ||
| right.pickDown(id); | ||
| left.pickDown(id); | ||
|
|
||
| log.info("Программист {} положил вилки", id); | ||
| } | ||
|
|
||
| log.info("Программист {} начал разговаривать", id); | ||
|
|
||
| state = State.TALKING; | ||
| Thread.sleep(timeoutMs); | ||
| } | ||
| } | ||
| // он должен думать | ||
| // посмотреть, есть ли у него суп | ||
| // если нет - попросить официанта налить и продолжить думать | ||
| // если есть - взять ложку раз, взять ложку два, начать есть суп (если все съел - отпустить ложки и начать думать) | ||
| } | ||
|
|
||
| public enum State { | ||
| TALKING, | ||
| EATING, | ||
| HUNGRY; | ||
| } | ||
| } |
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,34 @@ | ||
| package org.labs.model; | ||
|
|
||
| import lombok.RequiredArgsConstructor; | ||
| import lombok.SneakyThrows; | ||
| import lombok.extern.slf4j.Slf4j; | ||
| import org.labs.service.FoodService; | ||
| import org.labs.service.QueueService; | ||
|
|
||
| @RequiredArgsConstructor | ||
| @Slf4j | ||
| public class Waiter implements Runnable { | ||
| private final int id; | ||
| private final QueueService queueService; | ||
| private final FoodService foodService; | ||
| private final long timeoutMs; | ||
|
|
||
| @Override | ||
| @SneakyThrows | ||
| public void run() { | ||
| while (foodService.getEatCount().get() > 0) { | ||
| log.info("Официант {}, его очередь = {}", id, queueService.print()); | ||
| var programmerId = queueService.poll(); | ||
| log.info("Официант {} взял программиста с id = {}", id, programmerId); | ||
| if (programmerId != null) { | ||
| if (foodService.addSoupToProgrammer(programmerId)) { | ||
| log.info("Официант {} добавил программисту {} суп", id, programmerId); | ||
| } else { | ||
| break; | ||
| } | ||
| } | ||
| Thread.sleep(timeoutMs); | ||
| } | ||
| } | ||
| } |
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Хорошо, что взяли экзекуторы, но сможете объяснить, почему именно Fixed? Может есть варианты получше? Если есть, то почему (и если нет, то тот же вопрос)?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Число потоков (программистов) заранее известно из конфига и жить эти потоки должны на протяжении всей программы, что и делает метод newFixedThreadPool
Выписка из доки:
Другие реализации будто бы не подходят для данной задачи. Например, cachedThreadPool более применим к короткоживущим асинхронным задачам, это не подходит под описание задачи. ScheduledThreadPool тоже не подходит, так как у нас тут нет какого-то расписания выполнения.