generated from JavaLabs2025/concurrency-lab1
-
Notifications
You must be signed in to change notification settings - Fork 37
ЛР1: Гараев Раиль #14
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
railolog
wants to merge
5
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
5 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,86 @@ | ||
| package org.labs; | ||
|
|
||
| import java.util.Map; | ||
| import java.util.concurrent.Executors; | ||
| import java.util.stream.Collectors; | ||
|
|
||
| import lombok.SneakyThrows; | ||
| import lombok.extern.slf4j.Slf4j; | ||
| import org.labs.hierarchy.DinnerFactory; | ||
| import org.labs.hierarchy.DinnerResult; | ||
|
|
||
| @Slf4j | ||
| public class Main { | ||
|
|
||
| public static final int[] PERCENTILES = {50, 90, 95, 100}; | ||
|
|
||
| @SneakyThrows | ||
| public static void main(String[] args) { | ||
| System.out.println("Hello, World!"); | ||
| int programmersCount; | ||
| int waitersCount; | ||
| int servings; | ||
| programmersCount = 2; | ||
| waitersCount = 1; | ||
| servings = 300; | ||
|
|
||
| dinnerSample(programmersCount, waitersCount, servings); | ||
|
|
||
| programmersCount = 20; | ||
| dinnerSample(programmersCount, waitersCount, servings); | ||
|
|
||
| programmersCount = 200; | ||
| dinnerSample(programmersCount, waitersCount, servings); | ||
| // | ||
| programmersCount = 10_000; | ||
| waitersCount = 1; | ||
| servings = 600_000; | ||
|
|
||
| dinnerSample(programmersCount, waitersCount, servings); | ||
|
|
||
| waitersCount = 10; | ||
| dinnerSample(programmersCount, waitersCount, servings); | ||
|
|
||
| waitersCount = 1000; | ||
| dinnerSample(programmersCount, waitersCount, servings); | ||
|
|
||
| programmersCount = 10_000; | ||
| waitersCount = 1000; | ||
| servings = 1_000_000; | ||
|
|
||
| dinnerSample(programmersCount, waitersCount, servings); | ||
|
|
||
| programmersCount = 20_000; | ||
| dinnerSample(programmersCount, waitersCount, servings); | ||
|
|
||
| programmersCount = 200_000; | ||
| dinnerSample(programmersCount, waitersCount, servings); | ||
| } | ||
|
|
||
| private static void dinnerSample(int programmersCount, int waitersCount, int servings) { | ||
| DinnerFactory dinnerFactory = new DinnerFactory( | ||
| programmersCount, | ||
| waitersCount, | ||
| servings, | ||
| Executors.newVirtualThreadPerTaskExecutor(), | ||
| Executors.newVirtualThreadPerTaskExecutor() | ||
| ); | ||
|
|
||
| DinnerResult dinnerResult = dinnerFactory.setupAndRun(); | ||
| logResults(dinnerResult); | ||
| } | ||
|
|
||
|
|
||
| private static void logResults(DinnerResult dinnerResult) { | ||
| log.info("Each programmer had servings by percentiles: \n{}", printPercentiles(Utils.calculatePercentiles( | ||
| dinnerResult.servingsEaten(), | ||
| PERCENTILES | ||
| ))); | ||
| } | ||
|
|
||
| private static String printPercentiles(Map<Integer, Double> percentilesTable) { | ||
| return percentilesTable.entrySet().stream() | ||
| .map(e -> String.format(" p%d: %10.2f", e.getKey(), e.getValue())) | ||
| .collect(Collectors.joining("\n")); | ||
|
|
||
| } | ||
| } | ||
| } |
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,63 @@ | ||
| package org.labs; | ||
|
|
||
| import java.util.ArrayList; | ||
| import java.util.Collections; | ||
| import java.util.LinkedHashMap; | ||
| import java.util.List; | ||
| import java.util.Map; | ||
| import java.util.Random; | ||
|
|
||
| public class Utils { | ||
| private static final Random RANDOM = new Random(); | ||
|
|
||
| public static int discussTime() { | ||
| return random(10, 20); | ||
| } | ||
|
|
||
| public static int eatTime() { | ||
| return random(20, 40); | ||
| } | ||
|
|
||
| public static int random(int min, int max) { | ||
| return RANDOM.nextInt(min, max); | ||
| } | ||
|
|
||
| public static Map<Integer, Double> calculatePercentiles(List<Integer> data, int... percentiles) { | ||
| List<Integer> sortedData = new ArrayList<>(data); | ||
| Collections.sort(sortedData); | ||
|
|
||
| Map<Integer, Double> results = new LinkedHashMap<>(); | ||
| for (int p : percentiles) { | ||
| results.put(p, calculatePercentile(sortedData, p)); | ||
| } | ||
| return results; | ||
| } | ||
|
|
||
| private static double calculatePercentile(List<Integer> sortedList, int percentile) { | ||
| if (sortedList == null || sortedList.isEmpty()) { | ||
| throw new IllegalArgumentException("List cannot be null or empty"); | ||
| } | ||
| if (percentile < 0 || percentile > 100) { | ||
| throw new IllegalArgumentException("Percentile must be between 0 and 100"); | ||
| } | ||
|
|
||
| int n = sortedList.size(); | ||
|
|
||
| if (percentile == 0) return sortedList.getFirst(); | ||
| if (percentile == 100) return sortedList.get(n - 1); | ||
|
|
||
| double rank = percentile / 100.0 * (n - 1); | ||
| int lowerIndex = (int) Math.floor(rank); | ||
| int upperIndex = (int) Math.ceil(rank); | ||
|
|
||
| if (lowerIndex == upperIndex) { | ||
| return sortedList.get(lowerIndex); | ||
| } | ||
|
|
||
| double lowerValue = sortedList.get(lowerIndex); | ||
| double upperValue = sortedList.get(upperIndex); | ||
| double fraction = rank - lowerIndex; | ||
|
|
||
| return lowerValue + fraction * (upperValue - lowerValue); | ||
| } | ||
| } |
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,99 @@ | ||
| package org.labs.hierarchy; | ||
|
|
||
| import java.util.List; | ||
| import java.util.concurrent.ExecutorService; | ||
| import java.util.concurrent.TimeUnit; | ||
| import java.util.stream.Collectors; | ||
| import java.util.stream.IntStream; | ||
|
|
||
| import lombok.RequiredArgsConstructor; | ||
| import lombok.SneakyThrows; | ||
| import lombok.extern.slf4j.Slf4j; | ||
|
|
||
| @Slf4j | ||
| @RequiredArgsConstructor | ||
| public class DinnerFactory { | ||
|
|
||
| private final int programmersCount; | ||
| private final int waitersCount; | ||
| private final int servingsCount; | ||
| private final ExecutorService programmersPool; | ||
| private final ExecutorService waitersPool; | ||
|
|
||
| @SneakyThrows | ||
| public DinnerResult setupAndRun() { | ||
| log.info( | ||
| "Starting dinner with \n{} programmers \n{} waiters \n{} servings", | ||
| programmersCount, | ||
| waitersCount, | ||
| servingsCount | ||
| ); | ||
|
|
||
| List<Spoon> spoons = createSpoons(); | ||
| Restaurant restaurant = new Restaurant(servingsCount); | ||
| List<Programmer> programmers = createProgrammers(restaurant, spoons); | ||
| List<Waiter> waiters = createWaiters(restaurant); | ||
|
|
||
| long startTime = (long) (System.nanoTime() / 1e6); | ||
|
|
||
| programmers.forEach(programmersPool::submit); | ||
| waiters.forEach(waitersPool::submit); | ||
|
|
||
| // blocking current thread | ||
| monitorRestaurant(restaurant); | ||
|
|
||
| long finishTime = (long) (System.nanoTime() / 1e6); | ||
|
|
||
| programmersPool.shutdown(); | ||
| waitersPool.shutdown(); | ||
| try { | ||
| if (!programmersPool.awaitTermination(2, TimeUnit.SECONDS)) { | ||
| programmersPool.shutdownNow(); | ||
| } | ||
| } catch (InterruptedException e) { | ||
| programmersPool.shutdownNow(); | ||
| } | ||
|
|
||
| try { | ||
| if (!waitersPool.awaitTermination(2, TimeUnit.SECONDS)) { | ||
| waitersPool.shutdownNow(); | ||
| } | ||
| } catch (InterruptedException e) { | ||
| waitersPool.shutdownNow(); | ||
| } | ||
|
|
||
| log.info("All servings were eaten in {} ms", finishTime - startTime); | ||
| return new DinnerResult( | ||
| programmers.stream() | ||
| .map(Programmer::getTotalServings) | ||
| .collect(Collectors.toList()), | ||
| restaurant.getFoodServings() | ||
| ); | ||
| } | ||
|
|
||
| @SneakyThrows | ||
| private void monitorRestaurant(Restaurant restaurant) { | ||
| while (restaurant.isFoodAvailable()) { | ||
| Thread.sleep(500); | ||
| // log.info("Restaurant have {} servings left", restaurant.getFoodServings()); | ||
| } | ||
| } | ||
|
|
||
| private List<Spoon> createSpoons() { | ||
| return IntStream.range(0, programmersCount) | ||
| .mapToObj(Spoon::new) | ||
| .toList(); | ||
| } | ||
|
|
||
| private List<Programmer> createProgrammers(Restaurant restaurant, List<Spoon> spoons) { | ||
| return IntStream.range(0, programmersCount) | ||
| .mapToObj(i -> new Programmer(i, spoons.get(i), spoons.get((i + 1) % programmersCount), restaurant)) | ||
| .toList(); | ||
| } | ||
|
|
||
| private List<Waiter> createWaiters(Restaurant restaurant) { | ||
| return IntStream.range(0, waitersCount) | ||
| .mapToObj(i -> new Waiter(restaurant)) | ||
| .toList(); | ||
| } | ||
| } | ||
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,9 @@ | ||
| package org.labs.hierarchy; | ||
|
|
||
| import java.util.List; | ||
|
|
||
| public record DinnerResult( | ||
| List<Integer> servingsEaten, | ||
| int servingsLeft | ||
| ) { | ||
| } |
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,36 @@ | ||
| package org.labs.hierarchy; | ||
|
|
||
| import java.util.concurrent.CountDownLatch; | ||
|
|
||
| import lombok.RequiredArgsConstructor; | ||
| import lombok.SneakyThrows; | ||
|
|
||
| @RequiredArgsConstructor | ||
| public final class FoodRequest implements Comparable<FoodRequest> { | ||
| private final int clientId; | ||
| private final int alreadyEaten; | ||
| private final CountDownLatch latch = new CountDownLatch(1); | ||
| private boolean isServed = false; | ||
|
|
||
| @SneakyThrows | ||
| public boolean getServed() { | ||
| latch.await(); | ||
| return isServed; | ||
| } | ||
|
|
||
| public void setServed() { | ||
| isServed = true; | ||
| latch.countDown(); | ||
| } | ||
|
|
||
| public void setUnserved() { | ||
| isServed = false; | ||
| latch.countDown(); | ||
| } | ||
|
|
||
|
|
||
| @Override | ||
| public int compareTo(FoodRequest o) { | ||
| return Integer.compare(alreadyEaten, o.alreadyEaten); | ||
| } | ||
| } |
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.
Чисто как симуляция норм, но фактически -- может можно обойтись и без очереди официантов? Да/нет и почему?