Aviran
Aviran

Reputation: 5458

Custom Future objects

I'd like to create custom Future objects.

The following code works fine

ThreadPoolExecutor mExecutor;
Future<?> f = mExecutor.submit(new DownloadRunnable(task, itemId));

I'd like to take the return value of submit and assign it to MyFuture object, with additional calls. I've made the following changes, and getting a cast exception... Any suggestions?

ThreadPoolExecutor mExecutor;
// cast exception
MyFuture<?> f = (MyFuture<?>) mExecutor.submit(new DownloadRunnable(task, itemId));
f.setVer(true);


public class MyFuture<?> implements Future<?> {
    Boolean myVar;

    public void setVar(Boolean v) {
        ...
    }
}

Upvotes: 1

Views: 2252

Answers (2)

user4624062
user4624062

Reputation:

You can make a constructor by passing Future<?>

 public class MyFuture<?> extends Future<?> 
{
      Boolean myVar;
      Future<?> fut;
      MyFuture<?>(Future<?> fut)
      {
           this.fut = fut;
      }

      public void setVar(Boolean v) 
      {
          ...
      }
}

So the following line

  MyFuture<?> f = (MyFuture<?>) mExecutor.submit(new DownloadRunnable(task, itemId));

becomes

  MyFuture<?> f = new MyFuture<?>(mExecutor.submit(new DownloadRunnable(task, itemId)));

Upvotes: 2

akhil_mittal
akhil_mittal

Reputation: 24157

Well Future is an interface and you should have written it like:

public class MuFuture<T> implements Future<T> {

}

And then I hope the code will work:

MyFuture<?> f = (MyFuture<?>) mExecutor.submit(new DownloadRunnable(task, itemId));
f.setVer(true);

Upvotes: 0

Related Questions