Quantcast
Channel: Spring Community Forums - Data
Viewing all articles
Browse latest Browse all 297

transaction in a scheduled Runnable?

$
0
0
Hello,

I have a worker class TestWorker that implements Runnable.

Code:

@Service
public class TestWorker implements Runnable {

  @Autowired
  private ProvisioningService provisioningService;
 
  @Override
  public void run() {
   
    //START TRANSACTION
    try {
    Customer c = new Customer();
    c.setName("Test customer");
   
    this.provisioningService.createCustomer(c);
   
    String t = null;
    t.charAt(1);
    //generate RuntimeException NPE
   
    //COMMIT TRANSACTION
    } catch (Exception e) {
      //ROLLBACK TRANSACTION
    }
  }

}

The method createCustomer is @Transactional

I want to rollback if an RuntimeException occured in the run() method.
@Transactional is not possible on the run method.

I use the worker in a @Service like this:

Code:


@Service("pollDiagnosticsTraces")
@Transactional
public class PolDiagnosticsTracesImpl implements PollDiagnosticsTraces {

  private boolean running = false;

  @Autowired

  private ScheduledFuture<?> scheduledFutureTestWorkder;

  private TestWorker testWorker;

  @Override
  @Transactional
  public void startPolling() {
    if (!running) {
      if (this.scheduledFutureTestWorkder == null || this.scheduledFutureTestWorkder.isDone()) {
            this.scheduledFutureTestWorkder = taskScheduler.schedule(this.testWorker, new PollTrigger(
                getLongProperty("pollingrepair")));
      }
      running = true;
    }
  }

  @Override
  public void stopPolling() {
    if (running) {
      this.scheduledFutureTestWorkder.cancel(false);
      running = false;
    }
  }

}

When I run this, I get the Nullpointerexception, but the customer is committed. I want rollback the transaction.

If I create a NPE in createCustomer itself, it works (rollback)
How can I do it?

Viewing all articles
Browse latest Browse all 297

Trending Articles