Wait for method which return DeferredResult - java

I have service method which return DefferedResult<Foo> in few seconds, but I need my code will wait until that method finish and return deferred result with set result.
Here is sample code:
#Service
public class FooService {
// ...
public DeferredResult<Foo> fetchFoo(long id) throws InterruptedException {
DeferredResult<Foo> fooDeferredResult = new DeferredResult<>();
concurrentMap.put(id, fooDeferredResult);
return fooDeferredResult;
}
// this you can figure out as some handler or scheduler which receive messages and is called
public void anotherMethod(Foo foo) {
DeferredResult<Foo> remove = concurrentMap.remove(foo.getId());
remove.setResult(foo);
}
// ...
}
and I want call it in another service:
#Service
public class AnotherService {
#Autowired
FooService fooService;
public Foo bar(long id) {
// some logic
Foo foo = fooService.fetchFoo(id).getResult();
// another logic which depends on received foo
// there I need wait for result of fetchFoo method
return foo;
}
}
Can you tell me please how to ensure this behaviour? Thank you in advice.

You can use CountDownLatch for synchronize. Example:
public class Main {
public static void main(String[] args) throws InterruptedException {
System.out.println(1);
CountDownLatch latch = new CountDownLatch(1);
getResult()
.setResultHandler(result -> {
System.out.println(2 + " " + result);
latch.countDown();
});
latch.await();
System.out.println(3);
}
public static DeferredResult<String> getResult() {
DeferredResult<String> result = new DeferredResult<>();
new Thread(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
result.setResult("Hello");
})
.start();
return result;
}
}

Related

Stubbing #Async method run as sync

I am trying to test async method with timeout.
When I am calling the method directly the method run asynchronically and throw TimeoutException as expected. But when I stub the method, the method run synchronically and TimeoutException is not thrown. What am i doing wrong?
Class A()
{
#Async
public Future<Integer> asyncMethod(){
Thread.sleep(5000);
return new AsyncResult<>(1);
}
}
Class B()
{
A a;
#Autowired
B(A a)
{
this.a=a;
}
public void syncMethod()
{
Future<Integer> futureResult = a.asyncMehod();
// 2sec < 5sec, expect to throw TimeoutException
futureCount.get(2, TimeUnit.SECONDS);
}
}
Class TestBMockBean()
{
#MockBean
A a;
B b;
#BeforeAll
public void init()}{
this.b = new B(a);
}
// This test failed
#Test
void syncMethod() {
when(a.asyncMethod()).thenAnswer((Answer<AsyncResult<Integer>>) invocation -> {
Thread.sleep(5000);
return new AsyncResult<>(0);
});
}
assertThrows(TimeoutException.class,()-> b.syncMethod());
}
}
Class TestBAutowired()
{
#Autowired
B b:
// This test pass
#Test //success
void syncMethod_autowired() {
assertThrows(TimeoutException.class,()-> b.syncMethod());
}
}

JUnit5 check exception is thrown in thread

I have some service like this:
class SomeService{
private final Executor executor = Executors.newFixedThreadPool(10);
void handle(SomeEvent event) {
executor.execute(
() -> {
//... logic omitted
if (isBadCase()) {
throw new RuntimeException("Something bad happen");
}
//... time consuming logic continued
}
);
}
...
//other methods
}
And I want to test "badCase", that RuntimeException("Something bad happen") is thrown.
Is it possible to achieve using JUnit5?
For other cases "normal" or "notSoBad" I've implemented workaround which is just a wait cycle for some condition is met for corresponding case, like this:
private void awaitForNormalConditionIsMet(int seconds) {
for (int step = 1; step <= seconds * 40; step++) {
if (normalConditionIsMet()) return;
else {
try {
System.out.println("Waiting for condition - " + (step * 25) + "ms");
Thread.sleep(25);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Assertions.fail();
}
And this workaround works well when I have something corresponding to check.
But for the "badCase" nothing corresponding is changed, only the exception is thrown.
And I cannot extract the exception throwing logic from executor.
Could you please help?
You might want to refactor code especially if your Runnable has more complex logic.
If you make it a separate unit to test you have more control with it. And testing is more easy, for example:
public class SomeService {
private final Executor executor = Executors.newFixedThreadPool(10);
void handle(SomeEvent event) {
executor.execute(new MyRunnable(event));
}
// This is inner non-static in my example class because isBadCase()
// could be in service. Of course this isBadCase could be anywhere.
public class MyRunnable implements Runnable {
private SomeEvent event;
public MyRunnable(SomeEvent event) {
this.event = event;
}
#Override
public void run() {
if (isBadCase()) {
throw new RuntimeException("Something bad happen");
}
}
}
public boolean isBadCase() {
return false;
}
}
Now there is no problem with threads or so because you can catch the exception in main thread directly and at the same time you are doing more granular unit testing of your code:
#ExtendWith(MockitoExtension.class)
class SomeServiceTest {
// Spy is because you want to mock normal case for isBadCase = false
// to true so causing the exception to be thrown
#Spy
private SomeService someService;
#Test
void testOk() {
someService.new MyRunnable(new SomeEvent()).run();
}
#Test
void testBadCase() {
Mockito.when(someService.isBadCase()).thenReturn(true);
MyRunnable myRunnable = someService.new MyRunnable(new SomeEvent());
assertThrows(RuntimeException.class, () -> myRunnable.run());
}
}

custom naming for threads using threadfactory

I have a class that represent the world where subjects live in
public class WorldLifecycle {
private ExecutorService executorService;
public void startWorld() {
executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors(),
r -> {
String id = ((IdentifiableRunnable) r).getId();
return new Thread(r, id);
});
}
public void bringLife(LivingPerson ... people) {
Arrays.stream(people).forEach(executorService::submit);
}
public void endWorld() {
executorService.shutdownNow();
try {
executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
} catch (InterruptedException e) {
System.err.println("Failed to finish thread executor!");
}
}
}
Every LivingPerson looks like this
public class LivingPerson implements IdentifiableRunnable {
// investigate global world variable
private boolean isRunning = true;
private final StatefulPerson person;
public LivingPerson(StatefulPerson person) {
this.person = person;
}
#Override
public void run() {
System.out.println("Initial state: person=" + person.getRawPerson());
while (isRunning) { // for now forever
try {
Thread.sleep(1000); // do transition every 1 seconds
LifeState state = person.nextState();
System.out.println(getPerson().getName() + " " + state.getActionLabel());
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
System.out.println("End state: person=" + person.getRawPerson());
}
#Override
public String getId() {
Person person = getPerson();
return person.getId() + " - " + person.getName();
}
#Override
public void terminate() {
isRunning = false;
}
// returns clone instead of existing
private Person getPerson() {
return person.getRawPerson();
}
}
I want to name each thread by using person's name and unique identifier.
IdentifiableRunnable is a simple interface
public interface IdentifiableRunnable extends Runnable {
String getId();
void terminate();
}
I initialize everything like this
WorldLifecycle world = new WorldLifecycle();
LivingPerson male = createPerson("John", 40, Gender.MALE);
LivingPerson female = createPerson("Helen", 25, Gender.FEMALE);
System.out.println("Starting world...");
world.startWorld();
world.bringLife(male, female);
// just wait
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("Destroying world...");
world.endWorld();
But when I try to run it, I get the error
Exception in thread "main" java.lang.ClassCastException: java.util.concurrent.ThreadPoolExecutor$Worker cannot be cast to com.lapots.breed.lifecycle.api.Ide
ntifiableRunnable
at com.lapots.breed.lifecycle.WorldLifecycle.lambda$startWorld$0(WorldLifecycle.java:14)
at java.util.concurrent.ThreadPoolExecutor$Worker.<init>(ThreadPoolExecutor.java:612)
at java.util.concurrent.ThreadPoolExecutor.addWorker(ThreadPoolExecutor.java:925)
at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1357)
at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:112)
at java.util.Spliterators$ArraySpliterator.forEachRemaining(Spliterators.java:948)
at java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:580)
at com.lapots.breed.lifecycle.WorldLifecycle.bringLife(WorldLifecycle.java:20)
at com.lapots.breed.Sandbox.main(Sandbox.java:23)
As it seems it does not get my identifiableRunnable in the ThreadFactory.
How to solve it?
If you trace library calls with a debugger you will notice that your newThread method will be called like so:
Worker(Runnable firstTask) {
setState(-1); // inhibit interrupts until runWorker
this.firstTask = firstTask;
this.thread = getThreadFactory().newThread(this);
}
So it is passed an instance of the Worker class, which obviously can't be cast to your IdentifiableRunnable.
To execute your stream in parallel you should use ForkJoinPool how it is described in this post, in the first answer Custom thread pool in Java 8 parallel stream
Btw, here's how you can compress the code in your post:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.stream.Stream;
public class Main {
interface TestInterface extends Runnable{
default String getId() {
return "2";
}
}
static class TestClass implements TestInterface {
#Override
public void run() {
System.out.println("TEST");
}
}
public static void main(String[] args) {
ExecutorService exec = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors(), new ThreadFactory() {
#Override
public Thread newThread(final Runnable r) {
String id = ((TestInterface)r).getId();
Thread t = new Thread(r, id);
t.setDaemon(true);
return t;
}
});
Stream.of(new TestClass(),new TestClass(),new TestClass(),new TestClass()).forEach(exec::submit);
}
}

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 ..
}

Wrapping an asynchronous computation into a synchronous (blocking) computation

similar questions:
Pattern for wrapping an Asynchronous JavaScript function to make it synchronous
Wrapping an asynchronous method synchronously in C#
I have an object with a method I would like to expose to library clients (especially scripting clients) as something like:
interface MyNiceInterface
{
public Baz doSomethingAndBlock(Foo fooArg, Bar barArg);
public Future<Baz> doSomething(Foo fooArg, Bar barArg);
// doSomethingAndBlock is the straightforward way;
// doSomething has more control but deals with
// a Future and that might be too much hassle for
// scripting clients
}
but the primitive "stuff" I have available is a set of event-driven classes:
interface BazComputationSink
{
public void onBazResult(Baz result);
}
class ImplementingThing
{
public void doSomethingAsync(Foo fooArg, Bar barArg, BazComputationSink sink);
}
where ImplementingThing takes inputs, does some arcane stuff like enqueueing things on a task queue, and then later when a result occurs, sink.onBazResult() gets called on a thread that may or may not be the same thread as ImplementingThing.doSomethingAsync() was called.
Is there a way I can use the event-driven functions I have, along with concurrency primitives, to implement MyNiceInterface so scripting clients can happily wait on a blocking thread?
edit: can I use FutureTask for this?
Using your own Future implemenation:
public class BazComputationFuture implements Future<Baz>, BazComputationSink {
private volatile Baz result = null;
private volatile boolean cancelled = false;
private final CountDownLatch countDownLatch;
public BazComputationFuture() {
countDownLatch = new CountDownLatch(1);
}
#Override
public boolean cancel(final boolean mayInterruptIfRunning) {
if (isDone()) {
return false;
} else {
countDownLatch.countDown();
cancelled = true;
return !isDone();
}
}
#Override
public Baz get() throws InterruptedException, ExecutionException {
countDownLatch.await();
return result;
}
#Override
public Baz get(final long timeout, final TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
countDownLatch.await(timeout, unit);
return result;
}
#Override
public boolean isCancelled() {
return cancelled;
}
#Override
public boolean isDone() {
return countDownLatch.getCount() == 0;
}
public void onBazResult(final Baz result) {
this.result = result;
countDownLatch.countDown();
}
}
public Future<Baz> doSomething(Foo fooArg, Bar barArg) {
BazComputationFuture future = new BazComputationFuture();
doSomethingAsync(fooArg, barArg, future);
return future;
}
public Baz doSomethingAndBlock(Foo fooArg, Bar barArg) {
return doSomething(fooArg, barArg).get();
}
The solution creates a CountDownLatch internally which is cleared once the callback is received. If the user calls get, the CountDownLatch is used to block the calling thread until the computation completes and call the onBazResult callback. The CountDownLatch will assure that if the callback occurs before get() is called the get() method will return immediately with a result.
Well, there is the simple solution of doing something like:
public Baz doSomethingAndBlock(Foo fooArg, Bar barArg) {
final AtomicReference<Baz> notifier = new AtomicReference();
doSomethingAsync(fooArg, barArg, new BazComputationSink() {
public void onBazResult(Baz result) {
synchronized (notifier) {
notifier.set(result);
notifier.notify();
}
}
});
synchronized (notifier) {
while (notifier.get() == null)
notifier.wait();
}
return notifier.get();
}
Of course, this assumes that your Baz result will never be null…
The google guava library has an easy to use SettableFuture that makes this problem very simple (around 10 lines of code).
public class ImplementingThing {
public Baz doSomethingAndBlock(Foo fooArg, Bar barArg) {
try {
return doSomething(fooArg, barArg).get();
} catch (Exception e) {
throw new RuntimeException("Oh dear");
}
};
public Future<Baz> doSomething(Foo fooArg, Bar barArg) {
final SettableFuture<Baz> future = new SettableFuture<Baz>();
doSomethingAsync(fooArg, barArg, new BazComputationSink() {
#Override
public void onBazResult(Baz result) {
future.set(result);
}
});
return future;
};
// Everything below here is just mock stuff to make the example work,
// so you can copy it into your IDE and see it run.
public static class Baz {}
public static class Foo {}
public static class Bar {}
public static interface BazComputationSink {
public void onBazResult(Baz result);
}
public void doSomethingAsync(Foo fooArg, Bar barArg, final BazComputationSink sink) {
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Baz baz = new Baz();
sink.onBazResult(baz);
}
}).start();
};
public static void main(String[] args) {
System.err.println("Starting Main");
System.err.println((new ImplementingThing()).doSomethingAndBlock(null, null));
System.err.println("Ending Main");
}
This is dead simple with RxJava 2.x:
try {
Baz baz = Single.create((SingleEmitter<Baz> emitter) ->
doSomethingAsync(fooArg, barArg, result -> emitter.onSuccess(result)))
.toFuture().get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
Or without Lambda notation:
Baz baz = Single.create(new SingleOnSubscribe<Baz>() {
#Override
public void subscribe(SingleEmitter<Baz> emitter) {
doSomethingAsync(fooArg, barArg, new BazComputationSink() {
#Override
public void onBazResult(Baz result) {
emitter.onSuccess(result);
}
});
}
}).toFuture().get();
Even simpler:
Baz baz = Single.create((SingleEmitter<Baz> emitter) ->
doSomethingAsync(fooArg, barArg, result -> emitter.onSuccess(result)))
.blockingGet();
Kotlin Version:
val baz = Single.create<Baz> { emitter ->
doSomethingAsync(fooArg, barArg) { result -> emitter.onSuccess(result) }
}.blockingGet()
A very simple example, just to understand CountDownLatch without any
extra code.
A java.util.concurrent.CountDownLatch is a concurrency construct that allows one or more threads to wait for a given set of operations to complete.
A CountDownLatch is initialized with a given count. This count is decremented by calls to the countDown() method. Threads waiting for this count to reach zero can call one of the await() methods. Calling await() blocks the thread until the count reaches zero.
Below is a simple example. After the Decrementer has called countDown() 3 times on the CountDownLatch, the waiting Waiter is released from the await() call.
You can also mention some TimeOut to await.
CountDownLatch latch = new CountDownLatch(3);
Waiter waiter = new Waiter(latch);
Decrementer decrementer = new Decrementer(latch);
new Thread(waiter) .start();
new Thread(decrementer).start();
Thread.sleep(4000);
public class Waiter implements Runnable{
CountDownLatch latch = null;
public Waiter(CountDownLatch latch) {
this.latch = latch;
}
public void run() {
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Waiter Released");
}
}
//--------------
public class Decrementer implements Runnable {
CountDownLatch latch = null;
public Decrementer(CountDownLatch latch) {
this.latch = latch;
}
public void run() {
try {
Thread.sleep(1000);
this.latch.countDown();
Thread.sleep(1000);
this.latch.countDown();
Thread.sleep(1000);
this.latch.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Reference
If you don't want to use a CountDownLatch or your requirement is something same as Facebook like and unlike functionality. Means if one method is being called then don't call the other method.
In that case you can declare a
private volatile Boolean isInprocessOfLikeOrUnLike = false;
and then you can check in the beginning of your method call that if it is false then call method otherwise return.. depends upon your implementation.
Here's a more generic solution based on Paul Wagland's answer:
public abstract class AsyncRunnable<T> {
protected abstract void run(AtomicReference<T> notifier);
protected final void finish(AtomicReference<T> notifier, T result) {
synchronized (notifier) {
notifier.set(result);
notifier.notify();
}
}
public static <T> T wait(AsyncRunnable<T> runnable) {
final AtomicReference<T> notifier = new AtomicReference<>();
// run the asynchronous code
runnable.run(notifier);
// wait for the asynchronous code to finish
synchronized (notifier) {
while (notifier.get() == null) {
try {
notifier.wait();
} catch (InterruptedException ignore) {}
}
}
// return the result of the asynchronous code
return notifier.get();
}
}
Here's an example how to use it::
String result = AsyncRunnable.wait(new AsyncRunnable<String>() {
#Override
public void run(final AtomicReference<String> notifier) {
// here goes your async code, e.g.:
new Thread(new Runnable() {
#Override
public void run() {
finish(notifier, "This was a asynchronous call!");
}
}).start();
}
});
A more verbose version of the code can be found here: http://pastebin.com/hKHJUBqE
EDIT:
The example related to the question would be:
public Baz doSomethingAndBlock(final Foo fooArg, final Bar barArg) {
return AsyncRunnable.wait(new AsyncRunnable<Baz>() {
#Override
protected void run(final AtomicReference<Baz> notifier) {
doSomethingAsync(fooArg, barArg, new BazComputationSink() {
public void onBazResult(Baz result) {
synchronized (notifier) {
notifier.set(result);
notifier.notify();
}
}
});
}
});
}
The simplest way (which works for me) is to
Create a blocking queue
Call the asynchronous method - use a handler that offers the result to that blocking queue.
Poll the queue (that's where
you block) for the result.
public Baz doSomethingAndBlock(Foo fooArg, Bar barArg) throws InterruptedException {
final BlockingQueue<Baz> blocker = new LinkedBlockingQueue();
doSomethingAsync(fooArg, barArg, blocker::offer);
// Now block until response or timeout
return blocker.poll(30, TimeUnit.SECONDS);
}

Categories

Resources