1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.giraph.graph;
19
20 import org.apache.giraph.edge.Edge;
21 import org.apache.giraph.utils.UnsafeByteArrayInputStream;
22 import org.apache.giraph.utils.UnsafeByteArrayOutputStream;
23 import org.apache.hadoop.io.Writable;
24 import org.apache.hadoop.io.WritableComparable;
25
26 import java.io.DataInput;
27 import java.io.IOException;
28
29
30
31
32
33
34
35
36
37
38 public class ByteValueVertex<I extends WritableComparable,
39 V extends Writable, E extends Writable>
40 extends DefaultVertex<I, V, E> {
41
42
43 private byte[] valueBytes;
44
45 private V cachedValue = null;
46
47 @Override
48 public V getValue() {
49 if (cachedValue != null) {
50 return cachedValue;
51 }
52 DataInput dis = new UnsafeByteArrayInputStream(valueBytes);
53 cachedValue = getConf().createVertexValue();
54 try {
55 cachedValue.readFields(dis);
56 } catch (IOException ioe) {
57 throw new RuntimeException("Could not deserialize vertex value", ioe);
58 }
59
60 valueBytes = null;
61 return cachedValue;
62 }
63
64
65
66
67
68 private void setSerializedValue(V value) {
69 UnsafeByteArrayOutputStream bos = new UnsafeByteArrayOutputStream();
70 try {
71 value.write(bos);
72 bos.close();
73 } catch (IOException ioe) {
74 throw new RuntimeException("Could not serialize vertex value", ioe);
75 }
76 this.valueBytes = bos.toByteArray();
77 cachedValue = null;
78 }
79
80 @Override
81 public void setValue(V value) {
82 if (cachedValue != null) {
83 cachedValue = value;
84 } else {
85 setSerializedValue(value);
86 }
87 }
88
89 @Override
90 public void initialize(I id, V value, Iterable<Edge<I, E>> edges) {
91
92 super.initialize(id, null, edges);
93 setValue(value);
94 }
95
96 @Override
97 public void initialize(I id, V value) {
98 super.initialize(id, null);
99 setValue(value);
100 }
101
102 @Override
103 public void unwrapMutableEdges() {
104
105
106 if (cachedValue != null) {
107
108
109 setSerializedValue(cachedValue);
110 cachedValue = null;
111 }
112 super.unwrapMutableEdges();
113 }
114 }