1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 *
9 * https://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18 package org.apache.commons.lang3.builder;
19
20 import static org.junit.jupiter.api.Assertions.assertEquals;
21 import static org.junit.jupiter.api.Assertions.assertNull;
22 import static org.junit.jupiter.api.Assertions.assertTrue;
23
24 import java.util.Map;
25 import java.util.concurrent.BrokenBarrierException;
26 import java.util.concurrent.CyclicBarrier;
27 import java.util.concurrent.ExecutorService;
28 import java.util.concurrent.Executors;
29 import java.util.concurrent.Future;
30 import java.util.concurrent.TimeUnit;
31 import java.util.concurrent.TimeoutException;
32
33 import org.apache.commons.lang3.AbstractLangTest;
34 import org.apache.commons.lang3.ObjectUtils;
35 import org.apache.commons.lang3.StringUtils;
36 import org.junit.jupiter.params.ParameterizedTest;
37 import org.junit.jupiter.params.provider.ValueSource;
38
39 /**
40 * Tests isolation of visited state between threads and between successive outputs on the same thread.
41 *
42 * <p>
43 * Two workers render the same object concurrently. Each output must detail its first occurrence and abbreviate its second occurrence, regardless of whether the
44 * other worker has already visited that object. A barrier inside the rendering callback forces the traversals to overlap instead of relying on thread
45 * scheduling to expose shared state.
46 * </p>
47 *
48 * <p>
49 * The workers repeat the operation with their own style instances to expose state left on reused threads. Only one worker keeps an unrelated root registered,
50 * so the assertions also check that root registration and traversal cleanup remain local to each thread.
51 * </p>
52 */
53 class ToStringBuilderTraversalConcurrencyTest extends AbstractLangTest {
54
55 /**
56 * Waits for both workers to reach the shared object's rendering callback.
57 *
58 * <p>
59 * A timeout turns a missing callback into a bounded test failure. For example, state shared across threads could make one worker abbreviate the object
60 * immediately and skip the callback, leaving the other worker waiting. Interruptions preserve the interrupt flag for executor shutdown.
61 * </p>
62 *
63 * @param barrier the barrier shared by the two workers.
64 * @throws IllegalStateException if synchronization is interrupted, times out, or the barrier is broken.
65 */
66 private static void awaitOtherTraversal(final CyclicBarrier barrier) {
67 try {
68 barrier.await(10, TimeUnit.SECONDS);
69 } catch (final InterruptedException ex) {
70 Thread.currentThread().interrupt();
71 throw new IllegalStateException(ex);
72 } catch (final BrokenBarrierException | TimeoutException ex) {
73 throw new IllegalStateException(ex);
74 }
75 }
76
77 /**
78 * Creates a worker's style with a synchronization point after the shared object is marked visited and before it is rendered reflectively.
79 *
80 * <p>
81 * Each worker needs its own style because multiline indentation is mutable. The barrier coordinates traversal state without introducing a separate race
82 * through shared formatting state.
83 * </p>
84 *
85 * @param multiline whether to use the multiline recursive style.
86 * @param shared the object whose rendering must overlap on both workers.
87 * @param barrier the barrier shared by the workers.
88 * @return a style that pauses when rendering the shared object in detail.
89 */
90 private static RecursiveToStringStyle createStyle(final boolean multiline, final Object shared, final CyclicBarrier barrier) {
91 if (multiline) {
92 return new MultilineRecursiveToStringStyle() {
93
94 private static final long serialVersionUID = 1L;
95
96 /**
97 * {@inheritDoc}
98 *
99 * <p>
100 * Waits for the other worker before rendering the shared object so both traversals are active at the same time.
101 * </p>
102 */
103 @Override
104 public void appendDetail(final StringBuffer buffer, final String fieldName, final Object value) {
105 if (value == shared) {
106 awaitOtherTraversal(barrier);
107 }
108 super.appendDetail(buffer, fieldName, value);
109 }
110 };
111 }
112 return new RecursiveToStringStyle() {
113
114 private static final long serialVersionUID = 1L;
115
116 /**
117 * {@inheritDoc}
118 *
119 * <p>
120 * Waits for the other worker before rendering the shared object so both traversals are active at the same time.
121 * </p>
122 */
123 @Override
124 public void appendDetail(final StringBuffer buffer, final String fieldName, final Object value) {
125 if (value == shared) {
126 awaitOtherTraversal(barrier);
127 }
128 super.appendDetail(buffer, fieldName, value);
129 }
130 };
131 }
132
133 /**
134 * Renders 100 outputs on one worker and checks their contents and thread-local cleanup.
135 *
136 * <p>
137 * Each output contains the shared object's identity twice, with a detailed first occurrence and an abbreviated second occurrence. Repeating the assertions
138 * on the same thread detects visited marks leaking from a previous output. The optional unrelated root must survive each completed output, then be removed
139 * when this worker finishes.
140 * </p>
141 *
142 * @param multiline whether to use the multiline recursive style.
143 * @param shared the object rendered twice in each output and shared with the other worker.
144 * @param barrier the synchronization point used for each output's first occurrence.
145 * @param abandoned whether to keep an unrelated abandoned builder's root registered on this worker.
146 */
147 private static void renderOnWorker(final boolean multiline, final Object shared, final CyclicBarrier barrier, final boolean abandoned) {
148 final Object orphan = new Object();
149 if (abandoned) {
150 new ReflectionToStringBuilder(orphan, new RecursiveToStringStyle());
151 }
152 try {
153 // Each worker reuses its own style; multiline indentation is mutable and must not be shared between threads.
154 final RecursiveToStringStyle style = createStyle(multiline, shared, barrier);
155 final String identity = ObjectUtils.identityToString(shared);
156 for (int i = 0; i < 100; i++) {
157 final String output = new ToStringBuilder(new Object[0], style).append("first", shared).append("second", shared).toString();
158 assertEquals(2, StringUtils.countMatches(output, identity));
159 assertEquals(1, StringUtils.countMatches(output, identity + "["));
160 assertTrue(output.contains("first=" + identity + "["));
161 assertNull(ToStringStyle.getActiveTraversal());
162 final Map<?, ?> direct = ToStringStyle.getDirectTraversals().get();
163 assertTrue(direct == null || direct.isEmpty());
164 assertEquals(abandoned ? 1 : 0, ToStringStyle.getRegistry().size());
165 if (abandoned) {
166 assertTrue(ToStringStyle.getRegistry().containsKey(orphan));
167 }
168 }
169 } finally {
170 ToStringStyle.unregister(orphan);
171 }
172 assertTrue(ToStringStyle.getRegistry().isEmpty(), "A reused worker must not retain completed roots");
173 }
174
175 /**
176 * Tests that two overlapping traversals can render the same object independently on reused worker threads.
177 *
178 * <p>
179 * One worker keeps an unrelated root registered and the other does not. Both must produce a fresh detailed first occurrence in every output. Bounded waits
180 * and executor shutdown ensure that a traversal regression cannot leave the test waiting indefinitely or retain worker threads.
181 * </p>
182 *
183 * @param multiline whether to exercise the multiline recursive style instead of the single-line recursive style.
184 * @throws Exception if a worker fails, a wait times out, or the test thread is interrupted.
185 */
186 @ParameterizedTest(name = "multiline={0}")
187 @ValueSource(booleans = { false, true })
188 void testOverlappingTraversalsOnReusedWorkers(final boolean multiline) throws Exception {
189 final Object shared = new Object();
190 final CyclicBarrier barrier = new CyclicBarrier(2);
191 final ExecutorService pool = Executors.newFixedThreadPool(2);
192 try {
193 // Both threads pause after marking the same object visited, before either completes its nested rendering.
194 final Future<?> withOrphan = pool.submit(() -> renderOnWorker(multiline, shared, barrier, true));
195 final Future<?> withoutOrphan = pool.submit(() -> renderOnWorker(multiline, shared, barrier, false));
196 withOrphan.get(30, TimeUnit.SECONDS);
197 withoutOrphan.get(30, TimeUnit.SECONDS);
198 } finally {
199 pool.shutdownNow();
200 assertTrue(pool.awaitTermination(10, TimeUnit.SECONDS), "Worker threads must terminate even if an assertion fails");
201 }
202 }
203 }