2020import org .apache .beam .sdk .coders .Coder ;
2121import org .apache .beam .sdk .coders .CoderException ;
2222import org .apache .beam .sdk .util .CoderUtils ;
23+ import org .checkerframework .checker .nullness .qual .MonotonicNonNull ;
2324import org .checkerframework .checker .nullness .qual .Nullable ;
2425
2526/**
@@ -57,19 +58,34 @@ public static <K> StructuralKey<K> of(K key, Coder<K> coder) {
5758
5859 private static class CoderStructuralKey <K > extends StructuralKey <K > {
5960 private final Coder <K > coder ;
60- private final Object structuralValue ;
61- private final byte [] encoded ;
61+ private final K key ;
6262
63- private CoderStructuralKey (Coder <K > coder , K key ) throws Exception {
63+ private byte @ MonotonicNonNull [] encoded ;
64+ private @ MonotonicNonNull Object structuralValue ;
65+
66+ private CoderStructuralKey (Coder <K > coder , K key ) {
6467 this .coder = coder ;
65- this .structuralValue = coder .structuralValue (key );
66- this .encoded = CoderUtils .encodeToByteArray (coder , key );
68+ this .key = key ;
69+ }
70+
71+ private byte [] getEncoded () throws CoderException {
72+ if (encoded == null ) {
73+ this .encoded = CoderUtils .encodeToByteArray (coder , this .key );
74+ }
75+ return encoded ;
76+ }
77+
78+ private Object getStructuralValue () {
79+ if (structuralValue == null ) {
80+ this .structuralValue = coder .structuralValue (this .key );
81+ }
82+ return structuralValue ;
6783 }
6884
6985 @ Override
7086 public K getKey () {
7187 try {
72- return CoderUtils .decodeFromByteArray (coder , encoded );
88+ return CoderUtils .decodeFromByteArray (coder , getEncoded () );
7389 } catch (CoderException e ) {
7490 throw new IllegalArgumentException (
7591 "Could not decode Key with coder of type " + coder .getClass ().getSimpleName (), e );
@@ -83,14 +99,14 @@ public boolean equals(@Nullable Object other) {
8399 }
84100 if (other instanceof CoderStructuralKey ) {
85101 CoderStructuralKey <?> that = (CoderStructuralKey <?>) other ;
86- return structuralValue .equals (that .structuralValue );
102+ return getStructuralValue () .equals (that .getStructuralValue () );
87103 }
88104 return false ;
89105 }
90106
91107 @ Override
92108 public int hashCode () {
93- return structuralValue .hashCode ();
109+ return getStructuralValue () .hashCode ();
94110 }
95111 }
96112}
0 commit comments