Calling async method from another method without waiting/blocking - java

I have one webservice which is called by client.
public class MyWebServiceClass {
public int myMethod() {
myAsyncMethodInAnotherClass();
return 2;
}
}
I have another class which is acync, this class have method
public void myAsyncMethodInAnotherClass() throws InterruptedException, ExecutionException {
final Receiver receiver = new Receiver();
ExecutorService executorService = Executors.newFixedThreadPool(10);
Future future = executorService.submit(new Runnable() {
public void run() {
System.out.println("Asynchronous task");
receiver.doSomeThingElse();
}
});
executorService.shutdown();
}
I want myMethod() inside MyWebServiceClass should return 2 to the client, without waiting for process inside myAsyncMethodInAnotherClass(). Though I have created executorService but it is still waiting for method to complete before returning 2.

Related

closing statically created executorservice blocks assigned variables itself?

I just wonder explanation of how this code is working
assume we have Work class in below
public class Work {
private static ThreadPoolExecutor executorService;
private Work(){};
public static void instansiate(int numberOfThread){
executorService= (ThreadPoolExecutor) Executors.newFixedThreadPool(numberOfThread);
}
public static void shutDown(){
executorService.shutdown();
}
public static ExecutorService getExecutorService() {
return executorService;
}
public static int getThreadCount(){
return executorService.getCorePoolSize();
}
}
and im calling this class somewhere in method like below
public static void xx() throws ExecutionException, InterruptedException {
Work.instansiate(2);
System.out.println("Thread count= " + Work.getThreadCount());
ExecutorService executorService = Work.getExecutorService();
Future<String> future1 = executorService.submit(new Callable<String>() {
#Override
public String call() throws Exception {
return "future1";
}
});
String resFuture1 = future1.get();
System.out.println(resFuture1);
Work.shutDown();
Future<String> future2 = executorService.submit(new Callable<String>() {
#Override
public String call() throws Exception {
return "future2";
}
});
String resFuture2 = future2.get();
System.out.println(resFuture2);
}
This code is throwing exception after Work.shutDown() line and says rejected from java.util.concurrent.ThreadPoolExecutor#234bef66[Terminated, pool size = 0, active threads = 0 ...
I had assigned Work.getExecutorService to another executorService how closing Work executorservice can block assigned one.
Actually executorService holding same reference with Work.executorService(), Thus it was affected of closing Work's executorservice.

How to set and check interruption status of Runnable added to ExecutorService?

I need a correct way how can I implement this using new approach such as ExecutorService. In the Thread we have interrupt(), in the ExecutorService there is shutdown. So, how can I signal all threads to stop? How can I determine that Runnable must stop itself?
public class OldStyle {
public static void main(String[] args) throws InterruptedException {
MyTask task = new MyTask();
task.start();
Thread.sleep(10000);
task.interrupt();
}
static class MyTask extends Thread {
#Override
public void run() {
while (!isInterrupted()) {
// ...do work...
}
}
}
}
I suppose to do something like this, but there is no isInterrupted() :
class ModernWay {
public static void main(String[] args) throws InterruptedException {
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(new MyTask());
executor.shutdown();
executor.awaitTermination(1L, TimeUnit.DAYS);
}
static class MyTask implements Runnable {
#Override
public void run() {
while (!isInterrupted()) {
// ...do work...
}
}
}
}

How to return value from Runnable Interface using FutureTask

I did lot of google but I could not find how to return value from Runnable interface using FutureTask.
I need to return outcome of run method using FutureTask, I know that same can be archived using Callable Interface but how it can be done using Runnable Interface.
FutureTask constructor accepts second parameter for return value.
public FutureTask(Runnable runnable,V result)
How to assign outcome of run() method to V result.
FutureTask<String> futureTask=new FutureTask<String>(new Runnable() {
#Override
public void run() {
String outcome="Task Completed Successfully";
}
},null);
I am using
ExecutorService exec = Executors.newSingleThreadExecutor(new ThreadFactory() {
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
t.setDaemon(true);
return t;
}
});
Future fs = exec.submit(new Callable() {
public Object call() throws Exception {
return null;//yourObject
}
});
fs.get();//your object
The null value in your call is the return value. To have it return "Task Completed Successfully", you'd need:
FutureTask<String> futureTask=new FutureTask<String>(new Runnable() {
#Override
public void run() {
}
}, "Task Completed Successfully");
This is clearly not very useful if you want the Runnable to compute a result, however.
Use a Callable, instead.

How can i know threads jobs are done?

In class B how can i know jobs of threads are finished? In after properties some worker are running. In class B, I need to know if worker are done?
public class A implements InitializingBean{
public void method1(){
...
}
#Override
public void afterPropertiesSet() throws Exception {
System.out.print("test after properties set");
// send threads to executorService
ExecutorService executorService = Executors
.newFixedThreadPool(4);
for (int i = 0; i < 4; i++) {
Worker worker = new Worker();
executorService.submit(worker);
}
}
}
public class Worker implements Callable<Void>{
#Override
public void call(){
...
}
}
public class B{
public void methodB(){
A a = new A();
a.method1();
///Here How can i know the job of the workers are finished?
}
}
Use a listener/callback pattern to have the thread report completion to a listener. This simple example should show the process:
public interface ThreadCompleteListener {
void workComplete();
}
public class NotifyingThread extends Thread {
private Set<ThreadCompleteListener> listeners;
// setter method(s) for adding/removing listeners to go here
#Override
public void run() {
// do stuff
notifyListeners();
}
private void notifyListeners() {
for (ThreadCompleteListener listener : listeners) {
listener.workComplete(); // notify the listening class
}
}
}
in your listening class:
NotifyingThread t = new NotifyingThread();
t.addListener(new ThreadCompleteListener() {
void workComplete() {
// do something
}
});
t.start();
You could use a Future implementation for your thread. It provides a Future#isDone()
http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Future.html#isDone()
In general, it is usually more useful to be notified via a callback when jobs complete. However, since others have posted answers which follow that model, I'll instead post a solution that simply allows you to poll and ask whether the jobs are finished, in case this is what fits the needs of your application better.
public static interface InitializingBean{
public void afterPropertiesSet() throws Exception;
}
public static class A implements InitializingBean{
private List<Future<Void>> submittedJobs = Collections.synchronizedList(new ArrayList<Future<Void>>());
public void method1(){
//do stuff
}
#Override
public void afterPropertiesSet() throws Exception {
System.out.print("test after properties set");
// send threads to executorService
ExecutorService executorService = Executors
.newFixedThreadPool(4);
synchronized (submittedJobs) {
for (int i = 0; i < 4; i++) {
Worker worker = new Worker();
submittedJobs.add(executorService.submit(worker));
}
}
}
/**
* Allows you to poll whether all jobs are finished or not.
* #return
*/
public boolean areAllJobsFinished(){
synchronized (submittedJobs) {
for(Future<Void> task : submittedJobs){
if(!task.isDone()){
return false;
}
}
return true;
}
}
}
public static class Worker implements Callable<Void>{
#Override
public Void call(){
//do worker job
return null; //to satisfy compiler that we're returning something.
}
}
public static class B{
public void methodB(){
A a = new A();
a.method1();
if(a.areAllJobsFinished()){
System.out.println("Congrats, everything is done!");
} else {
System.out.println("There's still some work being done :-(");
}
}
}
If you'd like to wait in that thread that starts the ExecutorService, you can actually use the awaitTermination method.
At the end of you afterPropertiesSet method, you should add:
executorService.shutdown();
After this you then add:
executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS)
This causes the thread to wait for all the executorService's tasks to be done and then continues. So place any code you want to execute after the call to awaitTermination.

How to get the output stream from a thread

I currently have several runnable classes, each printing a string upon completion using System.out.println().
In the main() I execute them using a ExecutorService ,executor.execute() for each of them.
I am wondering after executing those threads, how to get the output stream from them for future use ?
Pretty much like using .getInputStream for processes but there's no such method in the Thread class. Thanks!
There's a class which implements runnable interface like this:
public class A implements Runnable {
public void run() {
System.out.println(5); //this thread always print out number 5
}
}
and in the main function I need to get the printed number and store it
public static void main(String[] args) {
ExecutorService ThreadPool = Executors.newFixedThreadPool(1);
ThreadPool.execute(new A()); //This statement will cause the thread object A
//to print out number 5 on the screen
ThreadPool.shutdown();
......
}
Now I need to get the printed number 5 and store it into, say an integer variable.
I think below code will satisfy your requirement.
class MyCallable implements Callable<InputStream>
{
#Override
public InputStream call() throws Exception {
//InputStream inputStreamObject = create object for InputStream
return inputStreamObject;
}
}
class Main
{
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(5);
List<Future<InputStream>> list = new ArrayList<Future<InputStream>>();
for (int i = 0; i < 25; i++) {
Callable<InputStream> worker = new MyCallable();
Future<InputStream> submit = executor.submit(worker);
list.add(submit);
}
InputStream inputStreamObject = null;
for (Future<InputStream> future : list) {
try {
inputStreamObject = future.get();
//use inputStreamObject as your needs
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
executor.shutdown();
}
}
Runnable and Callable in thread:
runnable interface has a method public abstract void run(); void - which means after completing run method, it will not return anything. Callable<V> interface has a method V call() throws Exception; which means after completing call method, it will return Object V that is parametrized as
public class Run_Vs_Call {
public static void main(String...args){
CallableTask call = new CallableTask();
RunnableTask run = new RunnableTask();
try{
FutureTask<String> callTask = new FutureTask<String>(call);
Thread runTask = new Thread(run);
callTask.run();
runTask.start();
System.out.println(callTask.get());
}catch(Exception e){
e.printStackTrace();
}
}
public static class CallableTask implements Callable<String>{
public String call( ){
String stringObject = "Inside call method..!! I am returning this string";
System.out.println(stringObject);
return stringObject;
}
}
public static class RunnableTask implements Runnable{
public void run(){
String stringObject = "Inside Run Method, I can not return any thing";
System.out.println(stringObject);
}
}
}
you can use new static class:
public class Global{
//example
public static ..
public static ..
}

Categories

Resources