How to notify mainthread when completing WorkEvent with exception?

132 views Asked by At

I'm working with the IBM WorkManager (v8.0.0) to do some work asynchronous to the main thread.

For this I use the following code:

// wm = via resource injected WorkManager

WorkItem item = wm.startWork(work, WorkManager.INDEFINITE, new WorkListener() {

  @Override
  public void workStarted(WorkEvent arg0) {
  }

  @Override
  public void workRejected(WorkEvent arg0) {
  }

  @Override
  public void workCompleted(WorkEvent arg0) {
    WorkException exception = arg0.getException();
    if (null != exception) {
      throw new RuntimeException("WorkCompleted with Exception");
    }
  }

  @Override
  public void workAccepted(WorkEvent arg0) {
  }
});

This works quite fine as long the WorkEvent was completed without an exception. But when it was completed with an exception, I want to notify the mainthread to stop it submitting more WorkItems to the WorkManager.

I thought I could raise an RunetimeException to notify the mainthread, but analysing the logs I found out that the exception is thrown in that moment the mainthreads finished submitting all WorkItems to the WorkManager and calling the join-method of the WorkManager - which is far too late (in most cases 50.000 items have to be done by the WorkManager).

So how can I interrupt my mainthread to stop it submitting more items to the WorkManager in this moment when an exception is recognized in workCompleted?

1

There are 1 answers

1
GhostCat On BEST ANSWER

You need a "more direct" interface then.

Meaning; you are showing code that calls:

WorkItem item = wm.startWork(work, WorkManager.INDEFINITE, new WorkListener()

The class that contains that instructions need some "input" channel; for example there could be a "simple" field in that class List<Exception> that your work items add their exceptions to.

And your "main" class that creates those work items should check that list regularly; and simply stop adding new work items when an exception is found.

Of course, you have to make that thread safe, and provide a reasonable architecture.