• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

ExecutorService is forcing me to cast to (Callable<T>)

 
Rooks Forgenal
Ranch Hand
Posts: 82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Purpose:
Make it easy to multi-thread a group of callable objects, using a variable number of threads. Have the thread that ran the Thread_Handler.setupThreads() block until all the threads finish. Then return the finished objects back the the thread that ran Thread_Handler.setupThreads().Please note the comment. This error is requiring me to cast the executed object... I don't see why I would have to. Any suggestions?
 
Steve Luke
Bartender
Posts: 4181
22
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rooks Forgenal wrote:Please note the comment. This error is requiring me to cast the executed object... I don't see why I would have to. Any suggestions?

T, at that point, can be of any type. ExecutorService#submit() takes a Future. Not all Objects are Futures, therefore the compiler can not assume that object to run is a Callable. Try making it like:
Then, the compiler should know that every possible T is a callable, and you should not have to cast it. I think - I haven't tried.
 
Rooks Forgenal
Ranch Hand
Posts: 82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
OK, I tried it and yes, that works great. I should have known it need to know the object was callable. However, How do I instantiate this object now?This does not work....
 
Steve Luke
Bartender
Posts: 4181
22
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
MyObj has to implement Callable<MyObj>
 
Rooks Forgenal
Ranch Hand
Posts: 82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Works like a charm! Thank you so much for your help. I have updated the code to match what was said in this thread. Thanks again!
 
Rooks Forgenal
Ranch Hand
Posts: 82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Do I have to change this:To:
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic