Jordan Halterman | 5a1053e | 2017-05-19 18:03:47 -0700 | [diff] [blame] | 1 | /* |
| 2 | * Copyright 2017-present Open Networking Laboratory |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | package org.onosproject.store.primitives; |
| 17 | |
| 18 | import java.util.concurrent.CompletableFuture; |
| 19 | import java.util.concurrent.ExecutionException; |
| 20 | import java.util.concurrent.TimeUnit; |
| 21 | import java.util.concurrent.TimeoutException; |
| 22 | |
| 23 | import org.onosproject.store.service.AsyncAtomicIdGenerator; |
| 24 | import org.onosproject.store.service.AtomicIdGenerator; |
| 25 | import org.onosproject.store.service.StorageException; |
| 26 | import org.onosproject.store.service.Synchronous; |
| 27 | |
| 28 | /** |
| 29 | * Default implementation for a {@code AtomicIdGenerator} backed by a {@link AsyncAtomicIdGenerator}. |
| 30 | */ |
| 31 | public class DefaultAtomicIdGenerator extends Synchronous<AsyncAtomicIdGenerator> implements AtomicIdGenerator { |
| 32 | |
| 33 | private final AsyncAtomicIdGenerator asyncIdGenerator; |
| 34 | private final long operationTimeoutMillis; |
| 35 | |
| 36 | public DefaultAtomicIdGenerator(AsyncAtomicIdGenerator asyncIdGenerator, long operationTimeoutMillis) { |
| 37 | super(asyncIdGenerator); |
| 38 | this.asyncIdGenerator = asyncIdGenerator; |
| 39 | this.operationTimeoutMillis = operationTimeoutMillis; |
| 40 | } |
| 41 | |
| 42 | @Override |
| 43 | public long nextId() { |
| 44 | return complete(asyncIdGenerator.nextId()); |
| 45 | } |
| 46 | |
| 47 | private <T> T complete(CompletableFuture<T> future) { |
| 48 | try { |
| 49 | return future.get(operationTimeoutMillis, TimeUnit.MILLISECONDS); |
| 50 | } catch (InterruptedException e) { |
| 51 | Thread.currentThread().interrupt(); |
| 52 | throw new StorageException.Interrupted(); |
| 53 | } catch (TimeoutException e) { |
| 54 | throw new StorageException.Timeout(); |
| 55 | } catch (ExecutionException e) { |
| 56 | throw new StorageException(e.getCause()); |
| 57 | } |
| 58 | } |
| 59 | } |