ad4215c965deaf483b47145a7d1667c6599460ad
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / main / java / org / opendaylight / controller / cluster / sharding / LookupTask.java
1 /*
2  * Copyright (c) 2017 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.controller.cluster.sharding;
9
10 import static akka.actor.ActorRef.noSender;
11
12 import akka.actor.ActorRef;
13 import akka.actor.Status;
14 import org.eclipse.jdt.annotation.Nullable;
15
16 /**
17  * Base class for lookup tasks. Lookup tasks are supposed to run repeatedly until successful lookup or maximum retries
18  * are hit. This class is NOT thread-safe.
19  */
20 abstract class LookupTask implements Runnable {
21     private final int maxRetries;
22     private final ActorRef replyTo;
23     private int retried = 0;
24
25     LookupTask(final ActorRef replyTo, final int maxRetries) {
26         this.replyTo = replyTo;
27         this.maxRetries = maxRetries;
28     }
29
30     abstract void reschedule(int retries);
31
32     void tryReschedule(final @Nullable Throwable throwable) {
33         if (retried <= maxRetries) {
34             retried++;
35             reschedule(retried);
36         } else {
37             fail(throwable);
38         }
39     }
40
41     void fail(final @Nullable Throwable throwable) {
42         if (throwable == null) {
43             replyTo.tell(new Status.Failure(
44                     new DOMDataTreeShardCreationFailedException("Unable to find the backend shard."
45                             + "Failing..")), noSender());
46         } else {
47             replyTo.tell(new Status.Failure(
48                     new DOMDataTreeShardCreationFailedException("Unable to find the backend shard."
49                             + "Failing..", throwable)), noSender());
50         }
51     }
52 }