#Dining Philosopher async method call
1 messages ยท Page 1 of 1 (latest)
<@&987246399047479336> please have a look, thanks.
Here is an AI assisted attempt to answer your question ๐ค. Maybe it helps! In any case, a human is on the way ๐. To continue talking to the AI, you can use </chatgpt:1108714622413963314>.
asynchronously. How can I achieve this?
To run methods asynchronously in Java, you can make use of the CompletableFuture class from the java.util.concurrent package. Here's an example of how you can implement the think() method to run asynchronously:
import java.util.concurrent.CompletableFuture;
public class Philosopher implements Runnable {
private String name;
public Philosopher(String name) {
this.name = name;
}
public void think() {
System.out.println(name + " is thinking...");
// Simulating some thinking time
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(name + " has finished thinking.");
}
@Override
public void run() {
CompletableFuture.runAsync(this::think);
}
public static void main(String[] args) {
Philosopher philosopher = new Philosopher("Philosopher 1");
philosopher.run(); // Start running asynchronously
// Do other tasks while the philosopher is thinking asynchronously
// Wait for the philosopher to finish thinking
CompletableFuture<Void> future = CompletableFuture.runAsync(philosopher::run);
future.join();
// Continue with other tasks after the philosopher has finished thinking
}
}
In this example, the think() method is wrapped inside a CompletableFuture.runAsync() call, which runs it asynchronously in a separate thread. The run() method of the Runnable interface is also implemented to start running the think() method asynchronously.
In the main() method, you can start running the philosopher asynchronously by calling philosopher.run(). You can then continue with other tasks while the philosopher is thinking. Finally, you can wait for the philosopher to finish thinking by using a CompletableFuture and calling its join() method.
Note that in this example, the think() method is simply sleeping for 2 seconds to simulate thinking. You can replace this with your actual logic for thinking.
@heady wadi Do the work in a different thread
class Philosopher {
void think() {
Thread.startVirtualThread(() -> {
try {
Thread.sleep(1000);
System.out.println("I GOT IT");
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
}
}
And from where i would call it?
I have a sequence diagram, where i define which method is called sync or async. And i want to use ExecutorService to run all tasks. And if i implement the methods like you tell me in "Philosopher" how i should call them if executorservice just call run?
imma smash my head on a table
okay so an executor service is another way to run things in the background
just have the philosipher submit a task to the executor service
I know that philosopher itself is a thread, so do you mean that I should implement every method that should be called asynchronously as in your example and call it in run()?
no
okay i think i see whats happening
you need a bunch of locks
so the philosiphers are running in parallel
but every now and then they need to coordinate over access to a resource
I am aware of that yeah
According to my prof we should define which calls are synchronous and asynchronous, that's why I was worried about it, so i thought about which methods in philosopher could have an async call
there are a few ways to do it
you could use synchronized, you could use semaphores, you could use await/notify, lock, etc
omg i remember dining philosopher from when i was at uni, we had to do it in erlang ๐
(then we all got caught for plagerism because we all happened to have found the same stackoverflow)
what dining philosopher tries to model is:
- You have philosophers sitting next to each other on a round table
- They have a knife and fork on each side of them (shared between each neighbour)
- You have to pick up a fork, pick up a knife and then once you have both eat.
- There's the problem: The philosopher next to you might have already taken a knife/fork so you have to wait for it to become available before you can pick it up.
You should try implement the methods first before tackling the whole running of the system. I.e. add code to take, eat, return
if you represent the cutlerly as a java.util.concurrent.locks.Lock it becomes pretty easy.
the "thinking" and "eat" step is just a Thread.sleep
oh yea, forgot lock too, that's another way to do it
We have to implement it in a distributed system but does it change the context?
Nope, just call lock/unlock on the Lock
When you call lock, it'll wait until it's available
A little
Wait, here's some relevant cringe
I really love this scene for educational purpose.
It explain Concurrent algorithm problem in short mount of time.
All the credit go to AMC
https://www.youtube.com/watch?v=9rht4XTs2Sw&t=2070s
Pantheon AMC series.
Wait this was really good lol
10/10 for the suspense
Show drips dumb juice
So for pick up and release forks i use lock and for eat() and think() just Threas.sleep?
Thats very cool
@heady wadi
Your question has been closed due to inactivity.
If it was not resolved yet, feel free to just post a message below
to reopen it, or create a new thread.
Note that usually the reason for nobody calling back is that your
question may have been not well asked and hence no one felt confident
enough answering.
When you reopen the thread, try to use your time to improve the quality
of the question by elaborating, providing details, context, all relevant code
snippets, any errors you are getting, concrete examples and perhaps also some
screenshots. Share your attempt, explain the expected results and compare
them to the current results.
Also try to make the information easily accessible by sharing code
or assignment descriptions directly on Discord, not behind a link or
PDF-file; provide some guidance for long code snippets and ensure
the code is well formatted and has syntax highlighting. Kindly read through
https://stackoverflow.com/help/how-to-ask for more.
With enough info, someone knows the answer for sure ๐