summaryrefslogtreecommitdiff
path: root/src/main/java/com/amazon/carbonado/RepositoryException.java
blob: 224e878ff61495b157858c1aa41215405b5d4782 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
/*
 * Copyright 2006-2012 Amazon Technologies, Inc. or its affiliates.
 * Amazon, Amazon.com and Carbonado are trademarks or registered trademarks
 * of Amazon Technologies, Inc. or its affiliates.  All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.amazon.carbonado;

import java.util.Random;

/**
 * General checked exception thrown when accessing a {@link Repository}.
 *
 * <p>Some repository exceptions are the result of an optimistic lock failure
 * or deadlock. One resolution strategy is to exit all transactions and try the
 * operation again, after waiting some bounded random amount of time. As a
 * convenience, this class provides a mechanism to support such a backoff
 * strategy. For example:
 *
 * <pre>
 * // Retry at most three more times
 * for (int retryCount = 3;;) {
 *     try {
 *         ...
 *         myObject.load();
 *         ...
 *         myObject.update();
 *         break;
 *     } catch (OptimisticLockException e) {
 *         // Wait up to one second before retrying
 *         retryCount = e.backoff(e, retryCount, 1000);
 *     }
 * }
 * </pre>
 *
 * If the retry count is zero (or less) when backoff is called, then the
 * original exception is rethrown, indicating retry failure.
 *
 * @author Brian S O'Neill
 */
public class RepositoryException extends Exception {

    private static final long serialVersionUID = 7261406895435249366L;

    /**
     * One strategy for resolving an optimistic lock failure is to try the
     * operation again, after waiting some bounded random amount of time. This
     * method is provided as a convenience, to support such a random wait.
     * <p>
     * A retry count is required as well, which is decremented and returned by
     * this method. If the retry count is zero (or less) when this method is
     * called, then this exception is thrown again, indicating retry failure.
     *
     * @param retryCount current retry count, if zero, throw this exception again
     * @param milliseconds upper bound on the random amount of time to wait
     * @return retryCount minus one
     * @throws E if retry count is zero
     */
    public static <E extends Throwable> int backoff(E e, int retryCount, int milliseconds)
        throws E
    {
        if (retryCount <= 0) {
            // Workaround apparent compiler bug.
            org.cojen.util.ThrowUnchecked.fire(e);
        }
        if (milliseconds > 0) {
            Random rnd = cRandom;
            if (rnd == null) {
                cRandom = rnd = new Random();
            }
            if ((milliseconds = rnd.nextInt(milliseconds)) > 0) {
                try {
                    Thread.sleep(milliseconds);
                } catch (InterruptedException e2) {
                }
                return retryCount - 1;
            }
        }
        Thread.yield();
        return retryCount - 1;
    }

    private static Random cRandom;

    public RepositoryException() {
        super();
    }

    public RepositoryException(String message) {
        super(message);
    }

    public RepositoryException(String message, Throwable cause) {
        super(message, cause);
    }

    public RepositoryException(Throwable cause) {
        super(cause);
    }

    /**
     * Recursively calls getCause, until the root cause is found. Returns this
     * if no root cause.
     */
    public Throwable getRootCause() {
        Throwable cause = this;
        while (cause.getCause() != null) {
            cause = cause.getCause();
        }
        return cause;
    }

    /**
     * Converts RepositoryException into an appropriate PersistException.
     */
    public final PersistException toPersistException() {
        return toPersistException(null);
    }

    /**
     * Converts RepositoryException into an appropriate PersistException, prepending
     * the specified message. If message is null, original exception message is
     * preserved.
     *
     * @param message message to prepend, which may be null
     */
    public final PersistException toPersistException(final String message) {
        Throwable cause;
        if (this instanceof PersistException) {
            cause = this;
        } else {
            cause = getCause();
        }

        if (cause == null) {
            cause = this;
        } else if (cause instanceof PersistException && message == null) {
            return (PersistException) cause;
        }

        String causeMessage = cause.getMessage();
        if (causeMessage == null) {
            causeMessage = message;
        } else if (message != null) {
            causeMessage = message + " : " + causeMessage;
        }

        return makePersistException(causeMessage, cause);
    }

    /**
     * Converts RepositoryException into an appropriate FetchException.
     */
    public final FetchException toFetchException() {
        return toFetchException(null);
    }

    /**
     * Converts RepositoryException into an appropriate FetchException, prepending
     * the specified message. If message is null, original exception message is
     * preserved.
     *
     * @param message message to prepend, which may be null
     */
    public final FetchException toFetchException(final String message) {
        Throwable cause;
        if (this instanceof FetchException) {
            cause = this;
        } else {
            cause = getCause();
        }

        if (cause == null) {
            cause = this;
        } else if (cause instanceof FetchException && message == null) {
            return (FetchException) cause;
        }

        String causeMessage = cause.getMessage();
        if (causeMessage == null) {
            causeMessage = message;
        } else if (message != null) {
            causeMessage = message + " : " + causeMessage;
        }

        return makeFetchException(causeMessage, cause);
    }

    /**
     * Subclasses can override this to provide a more specialized exception.
     *
     * @param message exception message, which may be null
     * @param cause non-null cause
     */
    protected PersistException makePersistException(String message, Throwable cause) {
        return new PersistException(message, cause);
    }

    /**
     * Subclasses can override this to provide a more specialized exception.
     *
     * @param message exception message, which may be null
     * @param cause non-null cause
     */
    protected FetchException makeFetchException(String message, Throwable cause) {
        return new FetchException(message, cause);
    }
}