generated from JavaLabs2025/concurrency-lab1
-
Notifications
You must be signed in to change notification settings - Fork 37
LAB-1 Реализация задачи об обедающих программистах #1
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
NobleBeer
wants to merge
6
commits into
JavaLabs2025:review1
Choose a base branch
from
JavaLabs2025:master
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
6 commits
Select commit
Hold shift + click to select a range
67b02d9
add deadline
github-classroom[bot] ac1eab3
LAB-1 Реализация задачи об обедающих программистах
NobleBeer 37919d8
LAB-1 Добавление logback.xml, актуализация конфигурационных параметров
NobleBeer 2c3781c
LAB-1 Рефакторинг: разделение зон ответственности
NobleBeer 11d614b
LAB-1 Ренейминг объектов
NobleBeer e7b2c39
LAB-1 Доработки
NobleBeer 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,106 @@ | ||
| package org.labs; | ||
|
|
||
| import lombok.extern.slf4j.Slf4j; | ||
| import org.labs.common.AsyncUtils; | ||
| import org.labs.config.Config; | ||
| import org.labs.developer.model.DeveloperModel; | ||
| import org.labs.spoon.model.SpoonModel; | ||
| import org.labs.kitchen.model.KitchenModel; | ||
| import org.labs.state.model.StateModel; | ||
| import org.labs.waiter.model.WaiterModel; | ||
|
|
||
| import java.util.Arrays; | ||
| import java.util.concurrent.ExecutorService; | ||
| import java.util.concurrent.Executors; | ||
| import java.util.concurrent.TimeUnit; | ||
| import java.util.concurrent.atomic.AtomicInteger; | ||
| import java.util.stream.IntStream; | ||
|
|
||
| @Slf4j | ||
| public class DinnerProcessingService { | ||
|
|
||
| private static final int TARGET_RESOURCE_COUNT = Config.DEVELOPER_COUNT; | ||
| private static final int DISH_COUNT = Config.DISH_COUNT; | ||
| private static final int WAITER_COUNT = Config.WAITER_COUNT; | ||
|
|
||
| private final ExecutorService developerPool = Executors.newWorkStealingPool(TARGET_RESOURCE_COUNT); | ||
| private final ExecutorService waiterPool = Executors.newWorkStealingPool(WAITER_COUNT); | ||
|
|
||
| public DeveloperModel[] runDinner() { | ||
| var startDate = System.currentTimeMillis(); | ||
| log.info("Время {} мс. Обед начался", startDate); | ||
|
|
||
| var kitchen = new KitchenModel(new AtomicInteger(DISH_COUNT)); | ||
| var spoons = createSpoons(); | ||
| var developers = createDevelopers(spoons, kitchen); | ||
| var waiters = createWaiters(kitchen); | ||
|
|
||
| startDeveloperTasks(developers); | ||
| startWaiterTasks(waiters); | ||
|
|
||
| monitorDinner(kitchen); | ||
|
|
||
| stopDinner(); | ||
|
|
||
| log.info("Время выполнения: {} мс. Обед завершен", System.currentTimeMillis() - startDate); | ||
|
|
||
| return developers; | ||
| } | ||
|
|
||
| private SpoonModel[] createSpoons() { | ||
| return IntStream.range(0, TARGET_RESOURCE_COUNT) | ||
| .mapToObj(SpoonModel::new) | ||
| .toArray(SpoonModel[]::new); | ||
| } | ||
|
|
||
| private DeveloperModel[] createDevelopers(SpoonModel[] spoons, KitchenModel kitchen) { | ||
| var developers = new DeveloperModel[TARGET_RESOURCE_COUNT]; | ||
| var state = new StateModel(developers); | ||
|
|
||
| IntStream.range(0, developers.length).forEach(number -> { | ||
| var leftSpoon = spoons[number]; | ||
| var rightSpoon = spoons[(number + 1) % spoons.length]; | ||
| developers[number] = new DeveloperModel(number, leftSpoon, rightSpoon, state, kitchen); | ||
| }); | ||
| return developers; | ||
| } | ||
|
|
||
| private WaiterModel[] createWaiters(KitchenModel kitchen) { | ||
| var waiters = new WaiterModel[WAITER_COUNT]; | ||
| IntStream.range(0, WAITER_COUNT).forEach(number -> waiters[number] = new WaiterModel(number, kitchen)); | ||
| return waiters; | ||
| } | ||
|
|
||
| private void startDeveloperTasks(DeveloperModel[] developers) { | ||
| Arrays.stream(developers).forEach(developerPool::submit); | ||
| } | ||
|
|
||
| private void startWaiterTasks(WaiterModel[] waiters) { | ||
| Arrays.stream(waiters).forEach(waiterPool::submit); | ||
| } | ||
|
|
||
| private void monitorDinner(KitchenModel kitchen) { | ||
| while (kitchen.getRemainingDishCount() > 0) { | ||
| AsyncUtils.waitMillis(200); | ||
| log.debug("Оставшееся количество блюд на кухне {}", kitchen.getRemainingDishCount()); | ||
| } | ||
| } | ||
|
|
||
| private void stopDinner() { | ||
| AsyncUtils.waitMillis(Config.DINNER_DURATION_IN_MS); | ||
| shutdownAndAwaitTermination(developerPool); | ||
| shutdownAndAwaitTermination(waiterPool); | ||
| } | ||
|
|
||
| private void shutdownAndAwaitTermination(ExecutorService pool) { | ||
| pool.shutdown(); | ||
| try { | ||
| if (!pool.awaitTermination(5, TimeUnit.SECONDS)) { | ||
| pool.shutdownNow(); | ||
| } | ||
| } catch (InterruptedException e) { | ||
| pool.shutdownNow(); | ||
| Thread.currentThread().interrupt(); | ||
| } | ||
| } | ||
| } |
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,38 @@ | ||
| package org.labs; | ||
|
|
||
| import lombok.RequiredArgsConstructor; | ||
| import lombok.extern.slf4j.Slf4j; | ||
| import org.labs.common.MathUtils; | ||
| import org.labs.developer.model.DeveloperModel; | ||
|
|
||
| import java.util.Arrays; | ||
| import java.util.stream.IntStream; | ||
|
|
||
| @Slf4j | ||
| @RequiredArgsConstructor | ||
| public class Main { | ||
|
|
||
| private static final DinnerProcessingService dinnerProcessingService = new DinnerProcessingService(); | ||
|
|
||
| public static void main(String[] args) { | ||
| System.out.println("Hello, World!"); | ||
| var developers = dinnerProcessingService.runDinner(); | ||
| printStates(developers); | ||
| } | ||
|
|
||
| private static void printStates(DeveloperModel[] developers) { | ||
| int totalCount = Arrays.stream(developers) | ||
| .mapToInt(developer -> developer.getEatCount().intValue()) | ||
| .sum(); | ||
|
|
||
| if (totalCount > 0) { | ||
| log.info("Итоговое состояние:"); | ||
| log.info("Всего съедено: {}", totalCount); | ||
|
|
||
| IntStream.range(0, developers.length) | ||
| .forEachOrdered(i -> { | ||
| var value = 100.0 * developers[i].getEatCount().intValue() / totalCount; | ||
| log.info("Разработчик {} съел {}% блюд", i + 1, MathUtils.roundTo2Digits(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,22 @@ | ||
| package org.labs.common; | ||
|
|
||
| import lombok.extern.slf4j.Slf4j; | ||
|
|
||
| import java.util.concurrent.ThreadLocalRandom; | ||
|
|
||
| @Slf4j | ||
| public class AsyncUtils { | ||
|
|
||
| public static void waitMillis(long maxMillis) { | ||
| if (maxMillis <= 0) { | ||
| return; | ||
| } | ||
| try { | ||
| long delay = ThreadLocalRandom.current().nextLong(maxMillis + 1); | ||
| Thread.sleep(delay); | ||
| } catch (InterruptedException e) { | ||
| log.warn("Поток {} был прерван", Thread.currentThread().getName()); | ||
| Thread.currentThread().interrupt(); | ||
| } | ||
| } | ||
| } |
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,14 @@ | ||
| package org.labs.common; | ||
|
|
||
| import org.labs.config.Config; | ||
|
|
||
| public class MathUtils { | ||
|
|
||
| public static double roundTo2Digits(double value) { | ||
| return Math.round(value * 100) / 100.0; | ||
| } | ||
|
|
||
| public static int getRandomInt() { | ||
| return (int) (Math.random() * Config.MAX_WAIT_MS); | ||
| } | ||
| } | ||
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,13 @@ | ||
| package org.labs.config; | ||
|
|
||
| import lombok.AccessLevel; | ||
| import lombok.NoArgsConstructor; | ||
|
|
||
| @NoArgsConstructor(access = AccessLevel.PRIVATE) | ||
| public class Config { | ||
kechinvv marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| public static int DEVELOPER_COUNT = 7; | ||
| public static int MAX_WAIT_MS = 1; | ||
| public static int DINNER_DURATION_IN_MS = 10; | ||
| public static int DISH_COUNT = 1000000; | ||
| public static int WAITER_COUNT = 2; | ||
| } | ||
77 changes: 77 additions & 0 deletions
77
src/main/java/org/labs/developer/model/DeveloperModel.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,77 @@ | ||
| package org.labs.developer.model; | ||
|
|
||
| import lombok.Getter; | ||
| import lombok.RequiredArgsConstructor; | ||
| import lombok.extern.slf4j.Slf4j; | ||
| import org.labs.common.MathUtils; | ||
| import org.labs.spoon.model.SpoonModel; | ||
| import org.labs.kitchen.model.KitchenModel; | ||
| import org.labs.serverequest.model.ServeRequest; | ||
| import org.labs.state.model.StateModel; | ||
|
|
||
| import java.util.concurrent.ExecutionException; | ||
| import java.util.concurrent.atomic.AtomicBoolean; | ||
| import java.util.concurrent.atomic.AtomicInteger; | ||
|
|
||
| @Slf4j | ||
| @Getter | ||
| @RequiredArgsConstructor | ||
| public class DeveloperModel implements Runnable { | ||
|
|
||
| private final int id; | ||
| private final SpoonModel leftSpoon; | ||
| private final SpoonModel rightSpoon; | ||
| private final StateModel state; | ||
| private final KitchenModel kitchen; | ||
|
|
||
| public final AtomicBoolean isStopped = new AtomicBoolean(); | ||
|
|
||
| public AtomicInteger eatCount = new AtomicInteger(); | ||
|
|
||
| @Override | ||
| public void run() { | ||
| try { | ||
| while (!isStopped.get()) { | ||
| think(); | ||
| var served = placeOrder(); | ||
| if (!served) { | ||
| isStopped.set(true); | ||
| break; | ||
| } | ||
|
|
||
| state.takeSpoons(id, leftSpoon, rightSpoon); | ||
| eat(); | ||
| state.putSpoons(id, leftSpoon, rightSpoon); | ||
| } | ||
| } catch (InterruptedException ignored) { | ||
| log.warn("Поток {} был прерван", Thread.currentThread().getName()); | ||
| } | ||
| } | ||
|
|
||
| private void think() throws InterruptedException { | ||
| log.debug("Время: {} ms. Разработчик начал обсуждать преподавателей", System.currentTimeMillis()); | ||
| Thread.sleep(MathUtils.getRandomInt()); | ||
| } | ||
|
|
||
| private void eat() throws InterruptedException { | ||
| log.debug("Время: {} ms. Разработчик начал есть", System.currentTimeMillis()); | ||
| Thread.sleep(MathUtils.getRandomInt()); | ||
| eatCount.incrementAndGet(); | ||
| } | ||
|
|
||
| private boolean placeOrder() throws InterruptedException { | ||
| try { | ||
| var serveRequest = new ServeRequest(id); | ||
| kitchen.submitRequest(serveRequest); | ||
| var isServed = serveRequest.getServed().get(); | ||
| if (!isServed) { | ||
| log.info("Разработчик {} не может получить новую порцию. Его обед завершен", id + 1); | ||
| return false; | ||
| } | ||
| } catch (ExecutionException e) { | ||
| log.warn("Разработчик {} не смог вызвать официанта", id + 1, e); | ||
| return false; | ||
| } | ||
| return true; | ||
| } | ||
| } |
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,45 @@ | ||
| package org.labs.kitchen.model; | ||
|
|
||
| import lombok.RequiredArgsConstructor; | ||
| import org.labs.serverequest.model.ServeRequest; | ||
|
|
||
| import java.util.concurrent.BlockingQueue; | ||
| import java.util.concurrent.PriorityBlockingQueue; | ||
| import java.util.concurrent.atomic.AtomicInteger; | ||
|
|
||
| @RequiredArgsConstructor | ||
| public class KitchenModel { | ||
|
|
||
| private final AtomicInteger remainingDishCount; | ||
| private final BlockingQueue<ServeRequest> requestQueue = new PriorityBlockingQueue<>(); | ||
|
|
||
| public void submitRequest(ServeRequest req) throws InterruptedException { | ||
| requestQueue.put(req); | ||
| } | ||
|
|
||
| public ServeRequest takeRequest() throws InterruptedException { | ||
| return requestQueue.take(); | ||
| } | ||
|
|
||
| public boolean takeDishIfAvailable() { | ||
| int currentRemainingDishCount; | ||
| do { | ||
| currentRemainingDishCount = remainingDishCount.get(); | ||
| if (currentRemainingDishCount <= 0) return false; | ||
| } while (!remainingDishCount.compareAndSet(currentRemainingDishCount, currentRemainingDishCount - 1)); | ||
| return true; | ||
| } | ||
|
|
||
| public int getRemainingDishCount() { | ||
| return remainingDishCount.get(); | ||
| } | ||
|
|
||
| public boolean isDepleted() { | ||
| return remainingDishCount.get() <= 0; | ||
| } | ||
|
|
||
| public boolean isRequestQueueEmpty() { | ||
| return requestQueue.isEmpty(); | ||
| } | ||
|
|
||
| } |
19 changes: 19 additions & 0 deletions
19
src/main/java/org/labs/serverequest/model/ServeRequest.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,19 @@ | ||
| package org.labs.serverequest.model; | ||
|
|
||
| import lombok.Getter; | ||
| import lombok.RequiredArgsConstructor; | ||
|
|
||
| import java.util.concurrent.CompletableFuture; | ||
|
|
||
| @Getter | ||
| @RequiredArgsConstructor | ||
| public class ServeRequest implements Comparable<ServeRequest> { | ||
| private final int developerId; | ||
| private final long timestamp = System.nanoTime(); | ||
| private final CompletableFuture<Boolean> served = new CompletableFuture<>(); | ||
|
|
||
| @Override | ||
| public int compareTo(ServeRequest other) { | ||
| return Long.compare(this.timestamp, other.timestamp); | ||
| } | ||
| } |
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,14 @@ | ||
| package org.labs.spoon.model; | ||
|
|
||
| import lombok.Getter; | ||
| import lombok.RequiredArgsConstructor; | ||
| import lombok.Setter; | ||
|
|
||
|
|
||
| @Getter | ||
| @RequiredArgsConstructor | ||
| public class SpoonModel { | ||
| private final int id; | ||
| @Setter | ||
| private boolean isAvailable = true; | ||
| } |
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,11 @@ | ||
| package org.labs.state.model; | ||
|
|
||
| import lombok.AccessLevel; | ||
| import lombok.NoArgsConstructor; | ||
|
|
||
| @NoArgsConstructor(access = AccessLevel.PRIVATE) | ||
| public enum State { | ||
| HUNGRY, | ||
| EATING, | ||
| DISCUSS_TEACHERS | ||
| } |
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.