In the disruptor (version 3.3.2), each event is a Runnable (since EventProcessor extends runnable).
I am writing an application that whenever an EventHandler throws an exception, the class who calls disruptor.start() needs to catch the exception and then react.
Now, if an EventProcessor would have been a Callable, that would have been easy.
Is there another way in Disruptor to propagate the exception?
I solved the problem by passing an implementation interface to the EventHandler,
as suggested by the Doug Lea book. The exception is set in a LinkedList, and at the end of the method call I retrieve the last element in the list. Sample code:
final LinkedList<Throwable> listExceptions = new LinkedList<Throwable>();
MyClassWithDisruptor at = MyClassWithDisruptor.getInstance();
at.send(message, transport, conf, new AuditExceptionHandler() {
#Override
public void handleException(final Throwable e) {
e.printStackTrace();
}
#Override
public void setException(final Exception e) throws AuditTrailException {
listExceptions.add(e);
}
});
The disruptor provides an ExceptionHandler which intended for dealing with this sort of problem.
Related
So I'm using ListenableFuture as a return type for certain operations. I expect the users to add callback to the future and then handle the success and exception cases. Now if the user cannot handle the exception, I want to have the ability to throw that exception onto the main Thread. Here's some code example:
public class SomeProcessor {
ListeningExecutorService executor = MoreExecutors.listeningDecorator(Executors.newSingleThreadExecutor());
public ListenableFuture<String> doStringProcessing() {
return executor.submit(() -> doWork());
}
private String doWork() {
return "stuff";
}
}
Then in a client class:
public class SomeConsumer {
public SomeConsumer (SomeProcessor processor) {
Futures.addCallback(processor.doStringProcessing(), new FutureCallback<String>() {
#Override
public void onSuccess(String result) {
// do something with result
}
#Override
public void onFailure(Throwable t) {
if (t instanceof ExceptionICanHandle) {
// great, deal with it
} else {
// HERE I want to throw on the Main thread, not on the executor's thread
// Assume somehow I can get a hold of the main thread object
mainThread.getUncaughtExceptionHandler().uncaughtException(mainThread, t);
// This above code seems wrong???
throw new RuntimeException("Won't work as this is not on the mainthread");
}
}
}, MoreExecutors.directionExecutor());
}
}
There is no direct way to do this.1
Hence, this question boils down to a combination of 2 simple things:
How do I communicate some data from a submitted task back to the code that is managing the pool itself? Which boils down to: How do I send data from one thread to another, and...
How do I throw an exception - which is trivial - throw x;.
In other words, you make the exception in your task, and do not throw it, instead, you store the object in a place the main thread can see it, and notify the main thread they need to go fetch it and throw it. Your main thread waits for this notification and upon receiving it, fetches it, and throws it.
A submitted task cannot simply 'ask' for its pool or the thread that manages it. However, that is easy enough to solve: Simply pass either the 'main thread' itself, or more likely some third object that serves as common communication line between them, to the task itself, so that task knows where to go.
Here is one simplistic approach based on the raw synchronization primitives baked into java itself:
public static void main(String[] args) {
// I am the main thread
// Fire up the executorservice here and submit tasks to it.
// then ordinarily you would let this thread end or sleep.
// instead...
ExecutorService service = ...;
AtomicReference<Throwable> err = new AtomicReference<>();
Runnable task = () -> doWork(err);
service.submit(task);
while (true) {
synchronized (err) {
Throwable t = err.get();
if (t != null) throw t;
err.wait();
}
}
}
public void doWork(AtomicReference<Throwable> envelope) {
try {
doActualWork();
catch (Throwable t) {
synchronized (envelope) {
envelope.set(t);
envelope.notifyAll();
}
}
}
There are many, many ways to send messages from one thread to another and the above is a rather finicky, primitive form. It'll do fine if you don't currently have any comms channels already available to you. But, if you already have e.g. a message queue service or the like you should probably use that instead here.
[1] Thread.stop(someThrowable) literally does this as per its own documentation. However, it doesn't work - it's not just deprecated, it has been axed entirely; calling it throws an UnsupportedOperationException on modern VMs (I think at this point 10 years worth of releases at least), and is marked deprecated with the rather ominous warning of This method is inherently unsafe. and a lot more to boot, it's not the right answer.
I have a common project with some shared code that is being used in another project. I'm trying to convert/map the exception from the common project CommonException to a new type of Exception let's call it SuperAwesomeException.
The aim is to have a generic way of handling all custom exceptions in the project.
I've attempted to do this using an UncaughtExceptionHandler. This seems to work when running the project but not from within JUnit, since that wraps each test in a try/catch block as described here.
public final class ExceptionHandler implements Thread.UncaughtExceptionHandler {
#Override
public void uncaughtException(Thread thread, Throwable exception) {
if (exception instanceof CommonException) {
throw new SuperAwesomeException(exception.getMessage());
}
if (exception instanceof SuperAwesomeException) {
throw new CommonException(exception.getMessage());
}
else {
System.out.println("ERROR! caught some other exception I don't really care about");
System.out.println("Not doing anything");
}
}
}
Is there another way I can map from one Exception to another or can I somehow tell JUnit not to catch certain exceptions and check the Exception is mapped to the correct one?
UPDATE - How I initially tried to write the Test:
public class ClassThatThrowsException {
ClassThatThrowsException() {
Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler());
}
public void doSomething() {
throw new CommonException("Something boring blew up!");
}
}
public class ClassThatThrowsExceptionTest {
#Test(expected=SuperAwesomeException.class)
public void testAwesome() {
ClassThatThrowsException c = new ClassThatThrowsException();
c.doSomething();
}
}
which throws:
java.lang.Exception: Unexpected exception, expected<SuperAwesomeException> but was<CommonException>
The problem is: when you are using JUnit, the framework will catch your exception. Therefore the uncaught exception handler isn't called in the first place!
See here for more details.
Thus, you have to do two things:
A) write tests that make sure that your exception handler implementation works as desired
#Test(expected=SuperAwesomeException.class)
public void testAwesome() {
new ExceptionHandler().uncaughtException(null, new CommonException("whatever"));
}
B) thest the plumbing - you want to make sure that this specific uncaught handler gets actually set by your code:
#Test
public void testDefaultHandlerIsSet() {
// creating a new instance should update the handler!
new ClassThatThrowsException();
Thread.UncaughtExceptionHandler handler = Thread.getDefaultUncaughtExceptionHandler();
assertThat(handler, not(nullValue()));
assertThat(handler, instanceOf(ExceptionHandler.class));
}
Finally - please note: you should not just do new XException(oldException.getMessage). Rather go for new XException("some message, oldException).
In other words: you got a cause here; so you better use the incoming exception as cause within the new one you intend to throw. Otherwise you loose all stack trace information.
I'm trying to figure out a way to implement an asynchronous retry mechanism using Hazelcast IExecutorService without recursive calls:
The recursive solution looks like that:
Callable task = ...
private sendToExecutor(){
Future future = submitToExecutorService(task);
((ICompletableFuture<ActionReply>) future).andThen(callback);
}
The callback is an ExecutionCallback:
#Override
public void onResponse(ActionReply response) {
// normal stuff
}
#Override
public void onFailure(Throwable t) {
// re-send if possible
if(numRetries < max_retries){
sendToExecutor();
}
}
I'm struggling to find a nice solution that does not involve the recursion. Any help will be appreciated. Thanks!
Create a wrapper class that implements Future and implement the get method which should catch RetryableHazelcastException. Note that you need have a limit on number of retries. If it crosses that limit means, there some major problem with your cluster.
public class RetryableFuture implements Future {
//Implement other methods.
#Override
public Object get() throws InterruptedException, ExecutionException {
try{
//get operation on future object
}catch(ExecutionException e){
if(e.getCause() instanceof RetryableHazelcastException){
//Log some warnings and submit the task back to Executors
}
}catch(Exception e){
//Not all exceptions are retryable
}finally {
//Close any kind of resources.
}
}
}
I asked this question before but was unable to get it opened again as my update didn't kick of the reopen process. So resubmitting it
My question is how to get an ExecutorService to realize that the thread is not valid(null) straight away without having to wait for the get on the future.
I have a use case where when creating a thread in a ThreadFactory I want to return null if the Thread cannot be set up correctly(for example it cant connect to a server).
When the ExecutorService runs a submit on a callable and the ThreadFactory returns null as below the code will run but will wait at future.get(5, TimeUnit.SECONDS); and then throw a TimeoutException. The problem is that ThreadFactory.newThread() doesn't allow me to throw an exception here.
public class TestThreadFactory implements ThreadFactory {
#Override
public Thread newThread(Runnable r) {
// try to create a conneciton that fails
// I cannot throw an exception here, so if there is a problem I have to return null
return null;
}
}
public class ExecutorServicePool {
public static ExecutorService getService() {
return Executors.newFixedThreadPool(10, new TestThreadFactory());
}
}
public static void main(String[] args) {
ExecutorService executorService = ExecutorServicePool.getService();
Callable callable = new Callable<String>() {
#Override
public String call() throws Exception {
return "callable";
}
};
Future<String> future = executorService.submit(callable);
try {
future.get(5, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
}
executorService.shutdown();
}
You could throw a RuntimeException which feels like a sensible thing to do.
RuntimeExceptions are great for situations that are generally not recoverable. Not being able to connect to a database for example is a prime example of one of those situations. Basically in this scenario you want to say:
"Something is really wrong and at the minute I can't process your
request. Try again later"
RuntimeExceptions can be thrown in method implementations even if the Interface does not declare them. So you can update your ThreadFactory implementation to throw a RuntimeException rather than returning null. You could even create a specific RuntimeException sub-class to ensure that it is clear what the error is within your application e.g. FailedToInitialiseThreadException
You can create custom executor service by extending ThreadPoolExecutor and
override methods where threadfactory is called to get new thread, to your need.
What I want is a standard JDK class that look like this:
interface ExplodingRunnable {
void run() throws Exception;
}
Callable is no good, because its call() method is required to return a value, but I need a void.
Runnable is no good, because its run() method doesn't declare throws Exception.
I sort of need a combination of the two. Any ideas?
EDIT: I should have mentioned that I tried Callable<Void> but it requires you to define a method:
public Void call() {
// run your code;
return null; // ugly!
}
I'm looking for something a bit nicer.
Why do I want this?
I'm implementing a standard why of catching "will never happen" Exceptions (they will never happen, but various APIs define their methods throwing Exceptions) and throwing any Exceptions that might occur by wrapping them in an (unchecked) RuntimeException, so the caller can simply pass a "ExplodingRunnable" in and not have to code loads of perfunctory try/catch blocks that will never be exercised.
FINAL EDIT It looks like what I was looking for doesn't exist. The accepted answer is the closest to "correct", but it looks like there is no solution to answer the question as asked.
Could you just use Callable<Void>?
An interface with only one method, which returns void and throws Exception.
Among all java and javax classes, only one fits that description:
package java.lang;
public interface AutoCloseable
{
void close() throws Exception;
}
Well... the word "close" has many meanings...
You want to surround a bunch of statements with some extra handling, there is no sin to define your own interface here. You may find that your API requires users to learn 4 new phrases
Util.muckException( new ExplodingRunnable() { public void run() throws Exception
^1 ^2 ^3 ^4
You can actually cut down two, and user code would look like this
new MuckException(){ public void run() throws Exception
{
statement_1;
...
statement_n;
}};
public abstract class MuckException
{
public abstract run() throws Exception;
public MuckException()
{
try{ run(); }
catch(Exception e){ throw new Error(e); }
}
}
Just use Callable, ignore the return value and document things as ignoring the returned value and recommend returning null. Just because you can return something does not mean you have to.
I would just use Callable<Void> and learn to love it. ;)
You can have the checked exception not declared with the following.
Runnable runs = new Runnable() {
public void run() {
try {
// do something
} catch(Exception e) {
// rethrows anything without the compiler knowing.
// the method is deprecated but can be used on the current thread.
Thread.currentThread().stop(e);
}
}
});
Future future = executorService.submit(run);
try {
future.get();
} catch (ExecutionException ee) {
Throwable e = ee.getCause(); // can be the checked exception above.
}
and not have to code loads of perfunctory try/catch blocks that will never be exercised.
I had the same issue and fixed it a little differently
// Exceptions class
public RuntimeException wrap(Exception e) {
return e instanceof RuntimeException ? ((RuntimeException)e) : new RuntimeException(e);
}
// user code
try {
foo.bar();
} catch (Exception e) {
throw Exceptions.wrap(e);
}