Question

I have done my own small concurrency framework (just for learning purposes) inspired by the java.util.concurrency package. This is about the Callable/Future mechanism. My code below is the whole one and is compilable and very easy to understand.

My problem is that sometimes I run into a deadlock where the first thread (the main thread) awaits for a signal from the other thread. But then the other thread has already notified the main thread before the main thread went into waiting state, so the main thread cannot wake up.

FutureTask.get() should always be run before FutureTask.run() but sometimes the run() method (which is called by new thread) runs before the get() method (which is called by main thread). I don´t know how I can prevent that.

This is a pseudo code of how I want the two threads to be run.

//From main thread:
Executor.submit().get() (in get() the main thread waits for new thread to notify)
         ->submit() calls Executor.execute(FutureTask object)
                                   -> execute() starts new thread
                                                 -> new thread shall notify `main thread`

I cannot understand how the new thread can start up and run faster than the main thread that actually starts the new thread.

Was it helpful?

Solution

before condition.await(); check if result is already set.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top