0
\$\begingroup\$

I am looking to multi-thread the resource allocation routines (i.e world loading) in my game so that they can occur in the background whilst rendering a loading screen etc... The problem is, I used to have code like this (pseudo)

void foo()
{
    ...
    try
    {
        mWorld = world.create(...)
    } catch(EntityNotFoundException e)
    {
        ...
    }
}

However, now that the world is being loaded on another thread, I need to register a listener that will recieve notification when the world is ready. The problem is that if an exception occurs inside of the newly created thread, I cannot surround it in a try-catch like I have here. How is this problem solved?

I am thinking of having the loading thread interface with a handler that looks like this:

public interface IInitializationMonitor<T> extends IInitializationProgressMonitor
{
void begin();
void completed(T item);
void failed(Throwable error);
}

The problem being that error would need to be tested against multiple times with instanceof, or rethrown inside of a try block. I am curious if there is a more elegant solution...

Thanks.

\$\endgroup\$
2
\$\begingroup\$

The Future interface will help here, when the call function of the Callable throws then the get of the Future will throw a ExecutionException where its cause is the original exception.

You can subclass FutureTask and override the done which will notify the world when the computation is either successful or failed and let the world handle the failure condition.

| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.