Reputation: 2072
I need to return two different types of variables (Future , ExecutorService) from a method. How can I move along?? here is the piece of code.. I have a class A and I m trying to call the run() method in 'B' class. 'startExecutorService' is the method which starts the threadExecutor and 'stopExecutorService' is the method which stops the threadExecutor
public class A{
public static void main(String[] args){
A AObj= new A();
Future<?> task = null;
ExecutorService threadexec = null;
task = AObj.startExecutorService(task, threadexec);
AObj.stopExecutorService(task, threadexec);
}
public Future<?> startExecutorService(Future<?> control, ExecutorService threadExecutor){
//'noOfThreads' determines the total no of threads to be created in threadpool
int noOfThreads = 1;
// Creating an object for class 'B' which has the run() method
B ThreadTaskOne = new ExecutorServiceThreadClass();
// Calling the ExecutorService to create Threadpool with specified number of threads
threadExecutor = Executors.newFixedThreadPool(noOfThreads);
// Creating a Future object 'control' and thereby starting the thread 'ThreadTaskOne'
control = threadExecutor.submit(ThreadTaskOne);
return control;
}
public void stopExecutorService(Future<?> task, ExecutorService threadExecutor){
// Interrupting the thread created by threadExecutor
task.cancel(true);
if(task.isCancelled()){
System.out.println("Task has been cancelled !!");
}
// Closing the threadExecutor
threadExecutor.shutdownNow();
}
}
I m getting ' NullPointerException' at 'stopExecutorService' method in line 'threadExecutor.shutdownNow();'The reason for this error is because, the threadExecutor value is unchanged in main method.. it has changed only in 'startExecutorService' method. So I want to return the changed value of threadExecutor back to main method, along with the Future..
Kindly help me out
Upvotes: 0
Views: 209
Reputation: 25725
Make a composite class and return an object of that class?
class A{
}
class B{
}
class Composite{
A varA;
B varB;
public Composite(A ax, B by){ varA = ax; varB = by;}
public A returnA(){ return varA;}
public B returnB(){ return varB;}
}
class Executor{
A a;
B b;
////// code here
public Composite returnComposite{
Composite c = new Composite(a,b);
return c;
}
}
Upvotes: 2