#Dining Philosopher async method call

1 messages ยท Page 1 of 1 (latest)

heady wadi
#

I want to implement the philosopher problem and now have a class "philosopher" which implements the runnable interface. I want certain methods like think() to run asynchronously and others like eat() to run synchronously. Does anyone have any ideas for me on how to make methods run asynchronously?

ripe auroraBOT
#

<@&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.

high igloo
#

@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);
           }
       });
   }
}
heady wadi
#

And from where i would call it?

high igloo
#

i am just showing you the mechanism to do things in the background

#

you tell me

heady wadi
#

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?

high igloo
#

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

heady wadi
#

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()?

high igloo
#

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

heady wadi
#

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

upper cedar
#

there are a few ways to do it

#

you could use synchronized, you could use semaphores, you could use await/notify, lock, etc

native glen
#

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:

  1. You have philosophers sitting next to each other on a round table
  2. They have a knife and fork on each side of them (shared between each neighbour)
  3. You have to pick up a fork, pick up a knife and then once you have both eat.
  4. 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

upper cedar
heady wadi
native glen
#

Nope, just call lock/unlock on the Lock

#

When you call lock, it'll wait until it's available

high igloo
#

Wait, here's some relevant cringe

native glen
#

10/10 for the suspense

high igloo
#

Show drips dumb juice

heady wadi
#

So for pick up and release forks i use lock and for eat() and think() just Threas.sleep?

heady wadi
ripe auroraBOT
#

@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 ๐Ÿ‘