How to get Data from a Task in afterExecute of ScheduledThreadPoolExecutor - java

I'm using ScheduledThreadPoolExecutor and I don't know hot to deal with something.
I'm scheduling some tasks this way:
scheduledExecService = new ExtendedScheduledExecutor(numThreads, myThreadFactory);
TareaActualizacion act = new TareaActualizacion(inst);
ScheduledFuture<?> handle = scheduledExecService.scheduleWithFixedDelay(act, retrasoInicial, segundosRefresco, TimeUnit.SECONDS);
act is a Runnable class that recive some data by parameter:
public class TareaActualizacion implements Runnable {
private Instalacion instalacion;
public TareaActualizacion(Instalacion instalacion) {
this.instalacion = instalacion;
}
#Override
public void run() {
//Do something
}
public Instalacion getInstalacion() {
return instalacion;
}
}
Now in the afterExecute method of the ExtendedSecheduledExecutor I want to get the object Instalacion of the task TareaActualizacion but I don't know how to do it.
My ExtendedScheduledExecutor class looks like this:
public class ExtendedScheduledExecutor extends ScheduledThreadPoolExecutor{
public ExtendedScheduledExecutor(int arg0) {
super(arg0);
}
public ExtendedScheduledExecutor(int arg0, ThreadFactory arg1) {
super(arg0, arg1);
}
#Override
protected void afterExecute(Runnable r, Throwable t)
{
super.afterExecute(r, t);
System.out.println("Executing afterExecute. Throwable is " + t);
if (t != null)
t.printStackTrace();
//I need to get the Instalacion attribute from TareaActualizacion task. How can I do it??
}
}
Any idea of how can I solve it??
Thank you!
Neus

As Stephan already pointed out in https://stackoverflow.com/a/22145530 , you should try to decouple the scheduling and execution from the notification.
One approach for this could be to wrap the actual task (TareaActualizacion) into another implementation of the Runnable interface that only executes the actual task, and afterwards notifies a callback about the task that has been executed.
Depending on your precise requirements, there may be several degrees of freedom for the implementation, but a general approach could roughly look like this:
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class ScheduledTaskNotification
{
public static void main(String[] args) throws Exception
{
ScheduledExecutorService executor = Executors.newScheduledThreadPool(4);
int n = 3;
for (int i = 0; i < n; i++)
{
UpdateTask updateTask = new UpdateTask(i);
RunnableCallback<UpdateTask> callback = new RunnableCallback<UpdateTask>()
{
#Override
public void runnableFinished(UpdateTask updateTask)
{
System.out.println("Finished "+updateTask+", id "+updateTask.getID());
}
};
Runnable runnableWithCallback =
createRunnableWithCallback(updateTask, callback);
executor.scheduleWithFixedDelay(
runnableWithCallback, 1000, 200+i*200,
TimeUnit.MILLISECONDS);
}
}
static interface RunnableCallback<T extends Runnable>
{
void runnableFinished(T runnable);
}
private static <T extends Runnable> Runnable createRunnableWithCallback(
final T runnable, final RunnableCallback<T> callback)
{
return new Runnable()
{
#Override
public void run()
{
runnable.run();
callback.runnableFinished(runnable);
}
};
}
private static class UpdateTask implements Runnable
{
private final int id;
UpdateTask(int id)
{
this.id = id;
}
#Override
public void run()
{
System.out.println("Run "+this);
}
int getID()
{
return id;
}
#Override
public String toString()
{
return "UpdateTask "+id;
}
}
}

This is a bay way. You should not trying to get the result out of the Executor, because it is only responsible for scheduling and executing tasks, not whats happening inside of them.
Your TareaActualizacion runnable should post the result to another piece of code, where you need it. This can be achieved using a queue or in the easiest case SwingUtilities.invokeLater().

Related

Binding an API callback to an RxJava Observable

I'm trying make a reactive application that listens to a network socket on a separate thread for prices and got a bit stumped with how exactly to construct the Observable. Much of the interfaces I have are constrained by the API I am using and therefore cannot change. I distilled what I am trying to do as a test below, but I can't see how to fill in the body of the getPriceReactive() method such that the prices are printed on the console by the subscriber (see the comment in the code).
public class PriceObservableTest {
// This interface is defined externally and used by the API
private interface ITickHandler {
void priceReceived(double price);
}
// Stores the price (currently just one double for illustration)
private class Tick {
double price = Double.NaN;
}
// Implementation of handler called by API when it receives a price
private class TickHandler implements ITickHandler {
private final Tick tick;
TickHandler() { this.tick = new Tick(); }
#Override public void priceReceived(double x) { tick.price = x; }
}
// This class emulates the API delivering prices from the socket
private class PriceSource {
private final Thread thread;
PriceSource(final ITickHandler handler) {
thread = new Thread(new Runnable() {
final Random r = new Random();
#Override public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
Thread.sleep(100);
handler.priceReceived(r.nextDouble() * 100);
} catch (InterruptedException e) {
break;
}
}
System.out.println("Price thread closed");
}
});
}
void subscribe() { thread.start(); }
void unsubscribe() { thread.interrupt(); }
}
#Test
public void simpleTest() throws Exception {
final ITickHandler handler = new TickHandler();
// Simulate some prices received periodically from a socket
PriceSource prices = new PriceSource(handler);
Observable<Tick> reactive = getPriceReactive(handler);
reactive.subscribe(new Subscriber<Tick>() {
#Override public void onCompleted() { }
#Override public void onError(Throwable e) { }
#Override public void onNext(Tick tick) {
System.out.println("Received price: " + tick.price);
}});
// Observe prices for 1 second. The subscriber should print them to console
prices.subscribe();
Thread.sleep(1000);
prices.unsubscribe();
}
// Returns an observable that reacts to price changes
private Observable<Tick> getPriceReactive(ITickHandler handler) {
return Observable.create(new Observable.OnSubscribe<Tick>() {
#Override public void call(Subscriber<? super Tick> subscriber) {
// How to call subscriber.onNext() whenever
// priceReceived() is called with a new price?
}
});
}
}
Somehow subscriber.onNext() needs to be called whenever the API calls priceReceived(), but I can't quite see how to achieve this. Of course I could store a reference to the subscriber in the TickHandler but this kind of defeats the purpose of having an Observable, doesn't it?
Transition to Observable in ITickHandler implementation. You are not controlling the subscriber(s) but the publisher
private class TickHandler implements ITickHandler {
private final Tick tick;
private final PublishSubject<Tick> priceSubject;
TickHandler() {
this.tick = new Tick();
this.priceSubject = PublishSubject.create();
}
#Override public void priceReceived(double x)
{
tick.price = x;
priceSubject.onNext(tick);
}
public Observable<Tick> priceReceivedObservable()
{
return priceSubject.asObservable();
}
}
And you can use it in your tests like:
final ITickHandler handler = new TickHandler();
PriceSource prices = new PriceSource(handler);
handler.priceReceivedObservable()
.subscribe(new Subscriber<Tick>() {
#Override public void onCompleted() { }
#Override public void onError(Throwable e) { }
#Override public void onNext(Tick tick) {
System.out.println("Received price: " + tick.price);
}});
I warn you, it's not tested since I don't do a lot of Java :)

is this a correct way to use Java FutureTask & Callable?

I'm implementing a layer to wrap a 3rd party communication layer.
The contract I need to implement is:
FutureTask<SomeData> send(Request request);
My layer has an onMessageReceived method, which is called by the 3rd party when a response arrives.
The approach I've taken to implement my layer is as follows:
I have a callable, which waits on a condition with a timeout:
interface MyCallable<T> extends Callable<T> {
void signal();
}
class CallableWithSignal<T> implements MyCallable<T> {
private Lock lock = new ReentrantLock();
private Condition condition = lock.newCondition();
private long waitTime;
public CallableWithSignal(int waitTimeSeconds){
this.waitTime=waitTimeSeconds;
}
#Override
public T call() throws Exception {
lock.lock();
try {
boolean wasSignaled = condition.await(waitTime, TimeUnit.SECONDS);
if(wasSignaled)
return null;
System.out.println("throwing exeption");
throw new Exception("timeout");
} finally {
lock.unlock();
}
}
#Override
public void signal() {
lock.lock();
try {
condition.signal();
} finally {
lock.unlock();
}
}
}
I also have extended FutureTask to expose the set method, as follows:
class MyFutureTask<V> extends FutureTask<V> {
private MyCallable<V> myCallable;
public MyFutureTask(MyCallable<V> r) { super(r); myCallable = r;}
#Override
public void set(V x) { super.set(x); }
#Override
public void setException(Throwable t) { super.setException(t); }
#Override
protected void done() {
super.done();
myCallable.signal();
}
}
When the task is done, I signal the callable to stop it.
So every time a send is called, I create a new MyFutureTask, run it using an executor, save it in a map and return it.
When onMessageReceived is called I find the task in the map and set its result with the set method.
Is this a good approach?
And another question: is it a good approach to move the executor logic inside the task? I mean, to create a start method for it, which will run the task using the executor.
please advice.

Wait for recursive Thread-Producer

I have a gatherer, that searches for moves in a game. I search in a recursive search, to get every possible move from the game.
For performance cause, I use a Threadpool and every found move adds a new Thread to the pool, to maybe extend the old move.
Here is some code:
protected static List<Runnable> threads;
private static ExecutorService threadPool;
protected final synchronized void hookThread(Runnable thread) {
if (threadPool == null) {
threadPool = Executors.newFixedThreadPool(15);
threads = new ArrayList<Runnable>();
}
threadPool.execute(thread);
threads.add(thread);
}
protected abstract class GathererRunnable implements Runnable {
#Override
public final void run() {
onRun();
threads.remove(this);
}
public abstract void onRun();
}
This is a snippet of the parent class. Now comes the child, that searches for the moves.
private void extendMove(final byte[] stones, final ByteLayMove move) {
Runnable r = new GathererRunnable() {
#Override
public void onRun() {
// fancy search stuff
if (moveIsFound)
extendMove(...);
}
};
hookThread(r);
}
The problem is now, that I don't know how I should can wait for the threads to finish.
I tried to use a int, that counts up on Thread Creation and down on Thread Completion, but that also resultet in a too early search abortion.
Do you have an idea if there is a nice way to wait for these threads?
I already thought about a BlockingQueue, but I don't have any idea how to implement it properly.
Greeting Kevin
Below program has implemented producer consumer scenario using BlockingQueue , you can use such approach while writing your own implementation.
import java.util.concurrent.*;
public class ThreadingExample {
public static void main(String args[]){
BlockingQueue<Message> blockingQueue = new ArrayBlockingQueue<Message>(100);
ExecutorService exec = Executors.newCachedThreadPool();
exec.execute(new Producer(blockingQueue));
exec.execute(new Consumer(blockingQueue));
}
}
class Message{
private static int count=0;
int messageId;
Message(){
this.messageId=count++;
System.out.print("message Id"+messageId+" Created ");
}
}
class Producer implements Runnable{
private BlockingQueue<Message> blockingQueue;
Producer(BlockingQueue<Message> blockingQueue){
this.blockingQueue=blockingQueue;
}
#Override
public void run(){
while(!Thread.interrupted()){
System.out.print("Producer Started");
try {
blockingQueue.put(new Message());
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Producer Done");
}
}
}
class Consumer implements Runnable{
private BlockingQueue<Message> blockingQueue;
Consumer(BlockingQueue<Message> blockingQueue){
this.blockingQueue=blockingQueue;
}
#Override
public void run(){
while(!Thread.interrupted()){
System.out.print("Concumer Started");
try{
Message message = blockingQueue.take();
System.out.print("message Id"+message.messageId+" Consumed ");
}
catch(InterruptedException e){
e.printStackTrace();
}
System.out.println("Concumer Done");
}
}
}

Java one shot timer to terminate main function

I implemented a simple timer with Observer pattern. I wanted to terminate the main function when 5 minutes passes while it is running. Basically what I need is a simple one shot timeout functionality. How can I achieve this? My code is not working. Below is the timer class
public class OneShotTimer extends Observable implements Runnable{
#Override
public void run() {
// TODO Auto-generated method stub
try {
Thread.sleep(30);
} catch (Exception e) {
// TODO: handle exception
System.out.println("Exception in timer");
}
notifyObservers();
}
In main class's constructor I initialize that timer.
public GreenOverlayMain(){
timer = new OneShotTimer();
timer.addObserver(this);
Thread t = new Thread(timer, "mythread");
t.start();
}
However the update() function of main class is never executed because timeout never happens. MainClass implements Observer interface. Below is the update function.
#Override
public void update(Observable o, Object arg) {
// TODO Auto-generated method stub
System.gc();
System.exit(0);
}
This example print update end finish execution.
public static void main(String[] args){
//scheduler executor is a lot more sophisticated solution
final ScheduledExecutorService sheduler = Executors.newScheduledThreadPool(1);
class MyO extends Observable {
public void trackChanged(){
setChanged(); //this method is protected in super class
}
};
//must be final because it used in nested class
final MyO o = new MyO();
o.addObserver(new Observer() {
#Override
public void update(Observable o, Object arg) {
//your processing here
System.out.println("update");
sheduler.shutdown();
}
});
sheduler.schedule(new Runnable() {
#Override
public void run() {
o.trackChanged();
o.notifyObservers();
}
}, 3, TimeUnit.SECONDS); //set any timout
}
Here is a reusable OneShotTimer.
new OneShotTimer(3, () -> setChange());
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class OneShotTimer
{
final ScheduledExecutorService sheduler = Executors.newScheduledThreadPool(1);
/// Call [callback] after [duration] seconds.
public OneShotTimer(int duration, OneShotCallback callback)
{
sheduler.schedule(() -> _callback(callback), duration, TimeUnit.SECONDS);
}
void _callback(OneShotCallback callback)
{
sheduler.shutdown();
callback.callback();
}
public interface OneShotCallback
{
void callback();
}
}

Multiple Runnable in a single thread -java

I am trying to have a bunch of runnable threads that can be started one at a time.
Something like
First(new Thread() {
public void run() {
//do something
}
});
Is what I'm trying to do impossible?
You can use a single threaded Executor
ExecutorService service = Executors.newSingleThreadedPool();
service.submit(runnable1);
service.submit(runnable2);
service.submit(runnable3);
i want to have several runnables in one thread. they will be doing different things at different times.
This sounds like a bad design to me. If your class is doing different things at different times then it should be split into different classes.
If you are talking about re-using the same background thread to do different things, then I would use a single threaded pool as in #Peter's answer:
private ExecutorService threadPool = Executors.newSingleThreadedPool();
...
threadPool.submit(new First());
threadPool.submit(new Second());
threadPool.submit(new Third());
...
// when you are done submitting, always shutdown your pool
threadPool.shutdown();
The First, Second, and Third classes would implement Runnable. They can take constructor arguments if they need to share some state.
Yes, just have multiple private methods:
public class FirstCaller {
private void method1() { }
private void method2() { }
private void method3() { }
public void someMethod() {
First(new Thread() {
public void run() {
//do something
method1();
method2();
method3();
}
});
}
}
OR as pointed out by Ted Hopp
public class FirstCaller {
public void someMethod() {
new First(new Thread() {
private void method1() { }
private void method2() { }
private void method3() { }
public void run() {
//do something
method1();
method2();
method3();
}
});
}
}
If you want to start a few threads at the same time CountDownLatch is what you need. See an example here: http://www.javamex.com/tutorials/threads/CountDownLatch.shtml.
Are you trying to execute multiple runnables sequentially in a single Thread? One after the other?
public class MultiRunnable implements Runnable {
private Runnable runnable1;
private Runnable runnable2;
public MultiRunnable(Runnable runnable1, Runnable runnable2) {
this.runnable1 = runnable1;
this.runnable2 = runnable2;
}
#Override
public void run() {
runnable1.run();
runnable2.run();
}
}
You could then call (new Thread(new MultiRunnable(... , ...))).start();
This will execute the first Runnable first, and when that is finnished it will execute the second.
Or generalised to more Runnables:
import java.util.Arrays;
import java.util.List;
public class MultiRunnable implements Runnable {
private List<Runnable> runnables;
public MultiRunnable(Runnable... runnables) {
this.runnables = Arrays.asList(runnables);
}
public MultiRunnable(List<Runnable> runnables) {
this.runnables = runnables;
}
#Override
public void run() {
for(Runnable runnable : runnables)
runnable.run();
}
}
The easiest thing to do is to define several Thread subclass instances and call the appropriate one depending on what you are trying to do.
However, if you really need a single Thread object that behaves differently in different circumstances, you can define a Thread subclass that has a state variable for controlling what it does.
class MyThread extends Thread {
public enum Action { A, B, C }
private Action mAction;
public void run() {
if (mAction == null) {
throw new IllegalStateException("Action must be specified");
}
switch (mAction) {
case A:
methodA();
break;
case B:
methodB();
break;
case C:
methodC();
break;
}
}
public void setAction(Action action) {
if (action == null) {
throw new IllegalArgumentException("Action cannot be null");
}
mAction = action;
}
private void methodA() { ... }
private void methodB() { ... }
private void methodC() { ... }
}
You could then create your thread and before calling start(), call setAction, passing one of the Action values.
As an alternative to a state variable, the run() method could examine external variables to determine the choice of action. Whether this makes sense (and whether it would be better) depends on your application.

Categories