generated from JavaLabs2025/concurrency-lab1
-
Notifications
You must be signed in to change notification settings - Fork 37
Lab-1: implement dining programmers problem solution #16
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
Kkkkkk58
wants to merge
5
commits into
JavaLabs2025:master
Choose a base branch
from
JavaLabs2025:review1
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
5 commits
Select commit
Hold shift + click to select a range
574ea75
add deadline
github-classroom[bot] 241dd60
feat: implement dining programmers problem solution
Kkkkkk58 80325b1
test: add tests
Kkkkkk58 02f5458
chore: add java build workflow
Kkkkkk58 bed9ec1
chore: make gradlew executable
Kkkkkk58 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,25 @@ | ||
| name: Build Java | ||
|
|
||
| on: | ||
| push: | ||
| branches: [ "master" ] | ||
| pull_request: | ||
| branches: [ "master" ] | ||
|
|
||
| jobs: | ||
| build: | ||
| runs-on: ubuntu-latest | ||
|
|
||
| steps: | ||
| - uses: actions/checkout@v5 | ||
| - name: Set up JDK 21 | ||
| uses: actions/setup-java@v5 | ||
| with: | ||
| java-version: '21' | ||
| distribution: 'temurin' | ||
| - name: Validate Gradle wrapper | ||
| uses: gradle/actions/wrapper-validation@v5 | ||
| - name: Setup Gradle | ||
| uses: gradle/actions/setup-gradle@v5 | ||
| - name: Build with Gradle | ||
| run: ./gradlew build |
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.
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 |
|---|---|---|
| @@ -0,0 +1,143 @@ | ||
| package org.labs; | ||
|
|
||
| import java.time.Duration; | ||
| import java.util.List; | ||
| import java.util.concurrent.ExecutorService; | ||
| import java.util.concurrent.TimeUnit; | ||
| import java.util.stream.IntStream; | ||
|
|
||
| import org.labs.actor.Programmer; | ||
| import org.labs.actor.Waiter; | ||
| import org.labs.config.DiningProgrammersConfigProperties; | ||
| import org.labs.config.ProgrammerTimeConfigProperties; | ||
| import org.labs.resource.Spoon; | ||
| import org.labs.result.DiningProgrammersResult; | ||
| import org.labs.service.FoodProvider; | ||
| import org.labs.service.Restaurant; | ||
| import org.labs.utils.TimeWatch; | ||
| import org.slf4j.Logger; | ||
| import org.slf4j.LoggerFactory; | ||
|
|
||
| public class DiningProgrammersProblem { | ||
| private static final Logger log = LoggerFactory.getLogger(DiningProgrammersProblem.class); | ||
| private static final long DEFAULT_PROGRESS_INTERVAL_SECONDS = 1; | ||
|
|
||
| private final ExecutorService programmersPool; | ||
| private final ExecutorService waitersPool; | ||
| private final DiningProgrammersConfigProperties configProperties; | ||
| private final TimeWatch timeWatch; | ||
|
|
||
| public DiningProgrammersProblem( | ||
| ExecutorService programmersPool, | ||
| ExecutorService waitersPool, | ||
| DiningProgrammersConfigProperties configProperties, | ||
| TimeWatch timeWatch | ||
| ) { | ||
| this.programmersPool = programmersPool; | ||
| this.waitersPool = waitersPool; | ||
| this.configProperties = configProperties; | ||
| this.timeWatch = timeWatch; | ||
| } | ||
|
|
||
| public DiningProgrammersResult solve() { | ||
| var actors = createActors(); | ||
| log.info("[DiningProgrammersProblem] Simulation is initialized and ready to start"); | ||
|
|
||
| timeWatch.start(); | ||
| runActors(actors.programmers, programmersPool); | ||
| runActors(actors.waiters, waitersPool); | ||
|
|
||
| awaitExecution(actors.restaurant); | ||
|
|
||
| return makeResults(actors, timeWatch.tick()); | ||
| } | ||
|
|
||
| private DiningProgrammersActorsAndServices createActors() { | ||
| var restaurant = new Restaurant(configProperties.totalSoupPortions(), configProperties.programmersCount()); | ||
| var spoons = IntStream.range(0, configProperties.programmersCount()) | ||
| .mapToObj(Spoon::new) | ||
| .toList(); | ||
|
|
||
| var programmers = IntStream.range(0, configProperties.programmersCount()) | ||
| .mapToObj(id -> | ||
| createProgrammer(id, spoons, configProperties.programmerTimeConfigProperties(), restaurant) | ||
| ).toList(); | ||
|
|
||
| var waiters = IntStream.range(0, configProperties.waitersCount()) | ||
| .mapToObj(id -> | ||
| new Waiter(id, configProperties.waiterTimeConfigProperties(), restaurant) | ||
| ).toList(); | ||
|
|
||
| return new DiningProgrammersActorsAndServices(programmers, waiters, restaurant); | ||
| } | ||
|
|
||
| private Programmer createProgrammer( | ||
| int id, | ||
| List<Spoon> spoons, | ||
| ProgrammerTimeConfigProperties configProperties, | ||
| FoodProvider foodProvider | ||
| ) { | ||
| var leftSpoon = spoons.get(id); | ||
| var rightSpoon = spoons.get((id + 1) % spoons.size()); | ||
|
|
||
| return new Programmer(id, leftSpoon, rightSpoon, configProperties, foodProvider); | ||
| } | ||
|
|
||
| private void runActors(List<? extends Runnable> actors, ExecutorService pool) { | ||
| actors.forEach(pool::submit); | ||
| } | ||
|
|
||
| private void awaitExecution(Restaurant restaurant) { | ||
| programmersPool.shutdown(); | ||
| waitersPool.shutdown(); | ||
|
|
||
| try { | ||
| while (!programmersPool.awaitTermination(DEFAULT_PROGRESS_INTERVAL_SECONDS, TimeUnit.SECONDS)) { | ||
| logProgress(restaurant); | ||
| } | ||
| while (!waitersPool.awaitTermination(DEFAULT_PROGRESS_INTERVAL_SECONDS, TimeUnit.SECONDS)) { | ||
| logProgress(restaurant); | ||
| } | ||
| } catch (InterruptedException e) { | ||
| Thread.currentThread().interrupt(); | ||
| log.error("[DiningProgrammersProblem] Problem thread interrupted, problem is not solved"); | ||
|
|
||
| throw new RuntimeException(e); | ||
| } | ||
| } | ||
|
|
||
| private void logProgress(Restaurant restaurant) { | ||
| var elapsedSeconds = timeWatch.tick().getSeconds(); | ||
| log.info( | ||
| "[DiningProgrammersProblem] Currently running for {} seconds, available soup portions: {}," + | ||
| " plates to refill: {}", | ||
| elapsedSeconds, | ||
| restaurant.getRemainingSoupPortions(), | ||
| restaurant.getPlatesToRefillCount() | ||
| ); | ||
| } | ||
|
|
||
| private DiningProgrammersResult makeResults(DiningProgrammersActorsAndServices actors, Duration totalDuration) { | ||
| List<Integer> programmersPortions = actors.programmers.stream() | ||
| .map(Programmer::getConsumedSoupPortions) | ||
| .toList(); | ||
| int restaurantPortionsLeft = actors.restaurant.getRemainingSoupPortions(); | ||
|
|
||
| var statistics = programmersPortions.stream().mapToDouble(it -> it).summaryStatistics(); | ||
|
|
||
| return new DiningProgrammersResult( | ||
| restaurantPortionsLeft, | ||
| Double.valueOf(statistics.getSum()).intValue(), | ||
| Double.valueOf(statistics.getMin()).intValue(), | ||
| Double.valueOf(statistics.getMax()).intValue(), | ||
| statistics.getAverage(), | ||
| totalDuration.toMillis() | ||
| ); | ||
| } | ||
|
|
||
| private record DiningProgrammersActorsAndServices( | ||
| List<Programmer> programmers, | ||
| List<Waiter> waiters, | ||
| Restaurant restaurant | ||
| ) { } | ||
| } |
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,33 @@ | ||
| package org.labs; | ||
|
|
||
| import java.util.concurrent.Executors; | ||
|
|
||
| import com.fasterxml.jackson.databind.ObjectMapper; | ||
| import org.labs.config.impl.JsonDiningProgrammersConfigReader; | ||
| import org.labs.result.impl.LoggingDiningProgrammersResultPrinter; | ||
| import org.labs.utils.TimeWatch; | ||
|
|
||
| public class Main { | ||
| private static final String DEFAULT_CONFIG_FILE = "config.json"; | ||
|
|
||
| public static void main(String[] args) { | ||
| System.out.println("Hello, World!"); | ||
| var configPath = args.length > 0 ? args[0] : DEFAULT_CONFIG_FILE; | ||
| var objectMapper = new ObjectMapper(); | ||
| var configReader = new JsonDiningProgrammersConfigReader(objectMapper); | ||
| var configProperties = configReader.read(configPath); | ||
|
|
||
| try (var programmersPool = Executors.newVirtualThreadPerTaskExecutor(); | ||
| var waitersPool = Executors.newVirtualThreadPerTaskExecutor() | ||
| ) { | ||
| var problem = new DiningProgrammersProblem( | ||
| programmersPool, | ||
| waitersPool, | ||
| configProperties, | ||
| new TimeWatch() | ||
| ); | ||
| var result = problem.solve(); | ||
| var resultPrinter = new LoggingDiningProgrammersResultPrinter(objectMapper); | ||
| resultPrinter.print(result); | ||
| } | ||
| } | ||
| } | ||
| } |
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,130 @@ | ||
| package org.labs.actor; | ||
|
|
||
| import java.util.concurrent.ThreadLocalRandom; | ||
|
|
||
| import org.labs.config.ProgrammerTimeConfigProperties; | ||
| import org.labs.resource.Plate; | ||
| import org.labs.resource.Spoon; | ||
| import org.labs.service.FoodProvider; | ||
| import org.slf4j.Logger; | ||
| import org.slf4j.LoggerFactory; | ||
|
|
||
| public class Programmer implements Runnable { | ||
| private static final Logger log = LoggerFactory.getLogger(Programmer.class); | ||
|
|
||
| private final int id; | ||
| private final Spoon leftSpoon; | ||
| private final Spoon rightSpoon; | ||
| private final ProgrammerTimeConfigProperties programmerTimeConfigProperties; | ||
| private final FoodProvider foodProvider; | ||
| private final ThreadLocalRandom random = ThreadLocalRandom.current(); | ||
| private int consumedSoupPortions = 0; | ||
|
|
||
| public Programmer( | ||
| int id, | ||
| Spoon leftSpoon, | ||
| Spoon rightSpoon, | ||
| ProgrammerTimeConfigProperties programmerTimeConfigProperties, | ||
| FoodProvider foodProvider | ||
| ) { | ||
| this.id = id; | ||
|
|
||
| if (leftSpoon.getId() < rightSpoon.getId()) { | ||
| this.leftSpoon = leftSpoon; | ||
| this.rightSpoon = rightSpoon; | ||
| } else { | ||
| this.leftSpoon = rightSpoon; | ||
| this.rightSpoon = leftSpoon; | ||
| } | ||
|
|
||
| this.programmerTimeConfigProperties = programmerTimeConfigProperties; | ||
| this.foodProvider = foodProvider; | ||
| } | ||
|
|
||
| public int getConsumedSoupPortions() { | ||
| return consumedSoupPortions; | ||
| } | ||
|
|
||
| @Override | ||
| public void run() { | ||
| try { | ||
| haveDinner(); | ||
| } catch (InterruptedException e) { | ||
| Thread.currentThread().interrupt(); | ||
| log.error("[Programmer] [id={}] Was interrupted. Reason: {}", id, e.getMessage(), e); | ||
| } | ||
| log.info("[Programmer] [id={}] Finished dinner. Consumed soup portions: {}", id, consumedSoupPortions); | ||
| } | ||
|
|
||
| private void haveDinner() throws InterruptedException { | ||
| while (foodProvider.isServing()) { | ||
| discussTeachers(); | ||
|
|
||
| var plate = refillPlate(); | ||
| if (plate.isEmpty()) { | ||
| continue; | ||
| } | ||
| takeSpoons(); | ||
|
|
||
| try { | ||
| eat(); | ||
| } finally { | ||
| releaseSpoons(); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| private void discussTeachers() throws InterruptedException { | ||
| var discussTimeMillis = random.nextInt( | ||
| programmerTimeConfigProperties.discussMillisMin(), | ||
| programmerTimeConfigProperties.discussMillisMax() | ||
| ); | ||
|
|
||
| log.debug("[Programmer] [id={}] Will discuss teachers for {} ms", id, discussTimeMillis); | ||
| Thread.sleep(discussTimeMillis); | ||
| log.debug("[Programmer] [id={}] Stopped discussing teachers", id); | ||
| } | ||
|
|
||
| private void takeSpoons() { | ||
| leftSpoon.acquire(); | ||
| log.debug("[Programmer] [id={}] [spoonId={}] Successfully acquired spoon", id, leftSpoon.getId()); | ||
| rightSpoon.acquire(); | ||
| log.debug("[Programmer] [id={}] [spoonId={}] Successfully acquired spoon", id, rightSpoon.getId()); | ||
| } | ||
|
|
||
| private Plate refillPlate() throws InterruptedException { | ||
| log.debug("[Programmer] [id={}] Will ask to refill his plate", id); | ||
|
|
||
| var plate = new Plate(id, consumedSoupPortions); | ||
| foodProvider.refillPlate(plate); | ||
| while (plate.isEmpty() && foodProvider.isServing()) { | ||
| plate.askToRefill(); | ||
| } | ||
|
|
||
| if (!plate.isEmpty()) { | ||
| log.debug("[Programmer] [id={}] Plate was refilled", id); | ||
| } | ||
|
|
||
| return plate; | ||
| } | ||
|
|
||
| private void eat() throws InterruptedException { | ||
| var eatingTimeMillis = random.nextInt( | ||
| programmerTimeConfigProperties.eatingMillisMin(), | ||
| programmerTimeConfigProperties.eatingMillisMax() | ||
| ); | ||
|
|
||
| log.debug("[Programmer] [id={}] Will be eating for {} ms", id, eatingTimeMillis); | ||
| Thread.sleep(eatingTimeMillis); | ||
| log.debug("[Programmer] [id={}] Stopped eating", id); | ||
|
|
||
| consumedSoupPortions += 1; | ||
| } | ||
|
|
||
| private void releaseSpoons() { | ||
| rightSpoon.release(); | ||
| log.debug("[Programmer] [id={}] [spoonId={}] Successfully released spoon", id, rightSpoon.getId()); | ||
| leftSpoon.release(); | ||
| log.debug("[Programmer] [id={}] [spoonId={}] Successfully released spoon", id, leftSpoon.getId()); | ||
| } | ||
| } | ||
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.
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.
Нет вайба, что можно попросить еду в тарелку перед тем как думать? Тогда будто не придется крутиться в цикле и постоянно что то спрашивать
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.
так суп остынет же!
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.
а если серьёзно - да, там действительно можно уйти от цикла.
изначально думал про подверженность spurious wakeups, но забыл проверить, есть ли такая проблема с CountDownLatch. судя по документации - нет, внезапных пробуждений быть не должно.