blob: 39d24cf5175e12ec38c3ddfd61b648347fe6106d [file] [log] [blame]
Madan Jampani7e55c662016-02-15 21:13:53 -08001/*
2 * Copyright 2016 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 */
16package org.onosproject.store.primitives.impl;
17
18import java.util.Set;
19import java.util.concurrent.atomic.AtomicBoolean;
20
21import org.onosproject.store.primitives.DistributedPrimitiveCreator;
22import org.onosproject.store.primitives.TransactionId;
23import org.onosproject.store.service.Serializer;
24import org.onosproject.store.service.TransactionContext;
25import org.onosproject.store.service.TransactionalMap;
26
27import com.google.common.collect.Sets;
28
29/**
30 * Default implementation of transaction context.
31 */
32public class NewDefaultTransactionContext implements TransactionContext {
33
34 private final AtomicBoolean isOpen = new AtomicBoolean(false);
35 private final DistributedPrimitiveCreator creator;
36 private final TransactionId transactionId;
37 private final TransactionCoordinator transactionCoordinator;
38 private final Set<TransactionParticipant> txParticipants = Sets.newConcurrentHashSet();
39
40 public NewDefaultTransactionContext(TransactionId transactionId,
41 DistributedPrimitiveCreator creator,
42 TransactionCoordinator transactionCoordinator) {
43 this.transactionId = transactionId;
44 this.creator = creator;
45 this.transactionCoordinator = transactionCoordinator;
46 }
47
48 @Override
49 public String name() {
50 return transactionId.toString();
51 }
52
53 @Override
54 public TransactionId transactionId() {
55 return transactionId;
56 }
57
58 @Override
59 public boolean isOpen() {
60 return isOpen.get();
61 }
62
63 @Override
64 public void begin() {
65 if (!isOpen.compareAndSet(false, true)) {
66 throw new IllegalStateException("TransactionContext is already open");
67 }
68 }
69
70 @Override
71 public boolean commit() {
72 transactionCoordinator.commit(transactionId, txParticipants).getNow(null);
73 return true;
74 }
75
76 @Override
77 public void abort() {
78 isOpen.set(false);
79 }
80
81 @Override
82 public <K, V> TransactionalMap<K, V> getTransactionalMap(String mapName,
83 Serializer serializer) {
84 // FIXME: Do not create duplicates.
85 DefaultTransactionalMap<K, V> txMap = new DefaultTransactionalMap<K, V>(mapName,
86 creator.<K, V>newAsyncConsistentMap(mapName, serializer),
87 this,
88 serializer);
89 txParticipants.add(txMap);
90 return txMap;
91 }
92}