47
48 /**
49 * Thread dump support.
50 *
51 * This class defines static methods to support the Thread.dump_to_file diagnostic command
52 * and the HotSpotDiagnosticMXBean.dumpThreads API. It defines methods to generate a
53 * thread dump to a file or byte array in plain text or JSON format.
54 */
55 public class ThreadDumper {
56 private ThreadDumper() { }
57
58 // the maximum byte array to return when generating the thread dump to a byte array
59 private static final int MAX_BYTE_ARRAY_SIZE = 16_000;
60
61 /**
62 * Generate a thread dump in plain text format to a file or byte array, UTF-8 encoded.
63 * This method is invoked by the VM for the Thread.dump_to_file diagnostic command.
64 *
65 * @param file the file path to the file, null or "-" to return a byte array
66 * @param okayToOverwrite true to overwrite an existing file
67 * @return the UTF-8 encoded thread dump or message to return to the tool user
68 */
69 public static byte[] dumpThreads(String file, boolean okayToOverwrite) {
70 if (file == null || file.equals("-")) {
71 return dumpThreadsToByteArray(false, MAX_BYTE_ARRAY_SIZE);
72 } else {
73 return dumpThreadsToFile(file, okayToOverwrite, false);
74 }
75 }
76
77 /**
78 * Generate a thread dump in JSON format to a file or byte array, UTF-8 encoded.
79 * This method is invoked by the VM for the Thread.dump_to_file diagnostic command.
80 *
81 * @param file the file path to the file, null or "-" to return a byte array
82 * @param okayToOverwrite true to overwrite an existing file
83 * @return the UTF-8 encoded thread dump or message to return to the tool user
84 */
85 public static byte[] dumpThreadsToJson(String file, boolean okayToOverwrite) {
86 if (file == null || file.equals("-")) {
87 return dumpThreadsToByteArray(true, MAX_BYTE_ARRAY_SIZE);
88 } else {
89 return dumpThreadsToFile(file, okayToOverwrite, true);
90 }
91 }
92
93 /**
94 * Generate a thread dump in plain text or JSON format to a byte array, UTF-8 encoded.
95 * This method is the implementation of the Thread.dump_to_file diagnostic command
96 * when a file path is not specified. It returns the thread dump and/or message to
97 * send to the tool user.
98 */
99 private static byte[] dumpThreadsToByteArray(boolean json, int maxSize) {
100 var out = new BoundedByteArrayOutputStream(maxSize);
101 try (out; var writer = new TextWriter(out)) {
102 if (json) {
103 dumpThreadsToJson(writer);
104 } else {
105 dumpThreads(writer);
106 }
107 } catch (Exception ex) {
108 if (ex instanceof UncheckedIOException ioe) {
109 ex = ioe.getCause();
110 }
111 String reply = String.format("Failed: %s%n", ex);
112 return reply.getBytes(StandardCharsets.UTF_8);
113 }
114 return out.toByteArray();
115 }
116
117 /**
118 * Generate a thread dump in plain text or JSON format to the given file, UTF-8 encoded.
119 * This method is the implementation of the Thread.dump_to_file diagnostic command.
120 * It returns the thread dump and/or message to send to the tool user.
121 */
122 private static byte[] dumpThreadsToFile(String file, boolean okayToOverwrite, boolean json) {
123 Path path = Path.of(file).toAbsolutePath();
124 OpenOption[] options = (okayToOverwrite)
125 ? new OpenOption[0]
126 : new OpenOption[] { StandardOpenOption.CREATE_NEW };
127 String reply;
128 try (OutputStream out = Files.newOutputStream(path, options)) {
129 try (var writer = new TextWriter(out)) {
130 if (json) {
131 dumpThreadsToJson(writer);
132 } else {
133 dumpThreads(writer);
134 }
135 reply = String.format("Created %s%n", path);
136 } catch (UncheckedIOException e) {
137 reply = String.format("Failed: %s%n", e.getCause());
138 }
139 } catch (FileAlreadyExistsException _) {
140 reply = String.format("%s exists, use -overwrite to overwrite%n", path);
141 } catch (Exception ex) {
142 reply = String.format("Failed: %s%n", ex);
143 }
144 return reply.getBytes(StandardCharsets.UTF_8);
145 }
146
147 /**
148 * Generate a thread dump in plain text format to the given output stream, UTF-8
149 * encoded. This method is invoked by HotSpotDiagnosticMXBean.dumpThreads.
150 * @throws IOException if an I/O error occurs
151 */
163 /**
164 * Generate a thread dump in plain text format to the given text stream.
165 * @throws UncheckedIOException if an I/O error occurs
166 */
167 private static void dumpThreads(TextWriter writer) {
168 writer.println(processId());
169 writer.println(Instant.now());
170 writer.println(Runtime.version());
171 writer.println();
172 dumpThreads(ThreadContainers.root(), writer);
173 }
174
175 private static void dumpThreads(ThreadContainer container, TextWriter writer) {
176 container.threads().forEach(t -> dumpThread(t, writer));
177 container.children().forEach(c -> dumpThreads(c, writer));
178 }
179
180 private static boolean dumpThread(Thread thread, TextWriter writer) {
181 ThreadSnapshot snapshot = ThreadSnapshot.of(thread);
182 if (snapshot == null) {
183 return false; // thread terminated
184 }
185 Instant now = Instant.now();
186 Thread.State state = snapshot.threadState();
187 writer.println("#" + thread.threadId() + " \"" + escape(snapshot.threadName())
188 + "\" " + (thread.isVirtual() ? "virtual " : "")
189 + decorateObject(thread)
190 + " " + state
191 + " cpuTime=" + snapshot.cpuTime()
192 + " " + now);
193 StackTraceElement[] stackTrace = snapshot.stackTrace();
194 int depth = 0;
195 while (depth < stackTrace.length) {
196 writer.print(" at ");
197 writer.println(stackTrace[depth]);
198 snapshot.ownedMonitorsAt(depth).forEach(o -> {
199 if (o != null) {
200 writer.println(" - locked " + decorateObject(o));
201 } else {
202 writer.println(" - lock is eliminated");
203 }
228 writer.println();
229 return true;
230 }
231
232 /**
233 * Returns the identity string for the given object in a form suitable for the plain
234 * text format thread dump.
235 */
236 private static String decorateObject(Object obj) {
237 return "<" + Objects.toIdentityString(obj) + ">";
238 }
239
240 /**
241 * Generate a thread dump in JSON format to the given output stream, UTF-8 encoded.
242 * This method is invoked by HotSpotDiagnosticMXBean.dumpThreads.
243 * @throws IOException if an I/O error occurs
244 */
245 public static void dumpThreadsToJson(OutputStream out) throws IOException {
246 var writer = new TextWriter(out);
247 try {
248 dumpThreadsToJson(writer);
249 writer.flush();
250 } catch (UncheckedIOException e) {
251 IOException ioe = e.getCause();
252 throw ioe;
253 }
254 }
255
256 /**
257 * JSON is schema-less and the thread dump format will evolve over time.
258 * {@code HotSpotDiagnosticMXBean.dumpThreads} links to a JSON file that documents
259 * the latest/current format. A system property can be used to generate the thread
260 * dump in older formats if necessary.
261 */
262 private static class JsonFormat {
263 private static final String JSON_FORMAT_VERSION_PROP =
264 "com.sun.management.HotSpotDiagnosticMXBean.dumpThreads.format";
265 static final int JSON_FORMAT_V1 = 1;
266 static final int JSON_FORMAT_V2 = 2;
267 private static final int JSON_FORMAT_LATEST = JSON_FORMAT_V2;
268 private static final int JSON_FORMAT;
269 static {
270 int ver = Integer.getInteger(JSON_FORMAT_VERSION_PROP, JSON_FORMAT_LATEST);
271 JSON_FORMAT = Math.clamp(ver, JSON_FORMAT_V1, JSON_FORMAT_LATEST);
272 }
273
274 static int formatVersion() {
275 return JSON_FORMAT;
276 }
277 }
278
279 /**
280 * Generate a thread dump to the given text stream in JSON format.
281 * @throws UncheckedIOException if an I/O error occurs
282 */
283 private static void dumpThreadsToJson(TextWriter textWriter) {
284 int format = JsonFormat.formatVersion();
285 var jsonWriter = new JsonWriter(textWriter, (format == JsonFormat.JSON_FORMAT_V1));
286 jsonWriter.startObject(); // top-level object
287 jsonWriter.startObject("threadDump");
288 if (format > JsonFormat.JSON_FORMAT_V1) {
289 jsonWriter.writeProperty("formatVersion", format);
290 }
291
292 jsonWriter.writeLongProperty("processId", processId());
293 jsonWriter.writeProperty("time", Instant.now());
294 jsonWriter.writeProperty("runtimeVersion", Runtime.version());
295
296 jsonWriter.startArray("threadContainers");
297 dumpThreads(ThreadContainers.root(), jsonWriter);
298 jsonWriter.endArray();
299
300 jsonWriter.endObject(); // threadDump
301
302 jsonWriter.endObject(); // end of top-level object
303 }
304
305 /**
333 if (!ThreadContainers.trackAllThreads()) {
334 threadCount = Long.max(threadCount, container.threadCount());
335 }
336 jsonWriter.writeLongProperty("threadCount", threadCount);
337
338 jsonWriter.endObject();
339
340 // the children of the thread container follow
341 container.children().forEach(c -> dumpThreads(c, jsonWriter));
342 }
343
344 /**
345 * Write a thread to the given JSON writer.
346 * @return true if the thread dump was written, false otherwise
347 * @throws UncheckedIOException if an I/O error occurs
348 */
349 private static boolean dumpThread(Thread thread, JsonWriter jsonWriter) {
350 Instant now = Instant.now();
351 ThreadSnapshot snapshot = ThreadSnapshot.of(thread);
352 if (snapshot == null) {
353 return false; // thread terminated
354 }
355 Thread.State state = snapshot.threadState();
356 StackTraceElement[] stackTrace = snapshot.stackTrace();
357
358 jsonWriter.startObject();
359 jsonWriter.writeLongProperty("tid", thread.threadId());
360 jsonWriter.writeProperty("time", now);
361 if (thread.isVirtual()) {
362 jsonWriter.writeProperty("virtual", Boolean.TRUE);
363 }
364 jsonWriter.writeProperty("name", snapshot.threadName());
365 jsonWriter.writeProperty("threadObj", Objects.toIdentityString(thread));
366 jsonWriter.writeProperty("state", state);
367 if (snapshot.cpuTime() != -1L) {
368 jsonWriter.writeLongProperty("cpuTime", snapshot.cpuTime());
369 }
370
371 // park blocker
372 Object parkBlocker = snapshot.parkBlocker();
373 if (parkBlocker != null) {
430 private static class JsonWriter {
431 private static class Node {
432 final boolean isArray;
433 int propertyCount;
434 Node(boolean isArray) {
435 this.isArray = isArray;
436 }
437 boolean isArray() {
438 return isArray;
439 }
440 int propertyCount() {
441 return propertyCount;
442 }
443 int getAndIncrementPropertyCount() {
444 int old = propertyCount;
445 propertyCount++;
446 return old;
447 }
448 }
449 private final Deque<Node> stack = new ArrayDeque<>();
450 private final boolean generateLongsAsString;
451 private final TextWriter writer;
452
453 JsonWriter(TextWriter writer, boolean generateLongsAsString) {
454 this.writer = writer;
455 this.generateLongsAsString = generateLongsAsString;
456 }
457
458 private void indent() {
459 int indent = stack.size() * 2;
460 writer.print(" ".repeat(indent));
461 }
462
463 /**
464 * Start of object or array.
465 */
466 private void startObject(String name, boolean isArray) {
467 if (!stack.isEmpty()) {
468 Node node = stack.peek();
469 if (node.getAndIncrementPropertyCount() > 0) {
470 writer.println(",");
471 }
472 }
473 indent();
474 if (name != null) {
475 writer.print("\"" + name + "\": ");
476 }
477 writer.println(isArray ? "[" : "{");
478 stack.push(new Node(isArray));
479 }
480
481 /**
482 * End of object or array.
483 */
484 private void endObject(boolean isArray) {
485 Node node = stack.pop();
486 if (node.isArray() != isArray)
487 throw new IllegalStateException();
488 if (node.propertyCount() > 0) {
489 writer.println();
490 }
491 indent();
492 writer.print(isArray ? "]" : "}");
493 }
494
495 /**
496 * Write a property.
497 * @param name the property name, null for an unnamed property
498 * @param obj the value or null
499 */
500 void writeProperty(String name, Object obj) {
501 Node node = stack.peek();
502 assert node != null;
503 if (node.getAndIncrementPropertyCount() > 0) {
504 writer.println(",");
505 }
506 indent();
507 if (name != null) {
508 writer.print("\"" + name + "\": ");
509 }
510 switch (obj) {
511 case Number _ -> writer.print(obj);
512 case Boolean _ -> writer.print(obj);
513 case null -> writer.print("null");
514 default -> writer.print("\"" + escape(obj.toString()) + "\"");
515 }
516 }
517
518 /**
519 * Write a property with a long value. If the value is outside the "interop"
520 * range of IEEE-754 double-precision floating point (64-bit) then it is
521 * written as a string.
522 */
523 void writeLongProperty(String name, long value) {
524 if (generateLongsAsString || value < -0x1FFFFFFFFFFFFFL || value > 0x1FFFFFFFFFFFFFL) {
525 writeProperty(name, Long.toString(value));
526 } else {
527 writeProperty(name, value);
528 }
529 }
530
531 /**
532 * Write an unnamed property.
533 */
534 void writeProperty(Object obj) {
|
47
48 /**
49 * Thread dump support.
50 *
51 * This class defines static methods to support the Thread.dump_to_file diagnostic command
52 * and the HotSpotDiagnosticMXBean.dumpThreads API. It defines methods to generate a
53 * thread dump to a file or byte array in plain text or JSON format.
54 */
55 public class ThreadDumper {
56 private ThreadDumper() { }
57
58 // the maximum byte array to return when generating the thread dump to a byte array
59 private static final int MAX_BYTE_ARRAY_SIZE = 16_000;
60
61 /**
62 * Generate a thread dump in plain text format to a file or byte array, UTF-8 encoded.
63 * This method is invoked by the VM for the Thread.dump_to_file diagnostic command.
64 *
65 * @param file the file path to the file, null or "-" to return a byte array
66 * @param okayToOverwrite true to overwrite an existing file
67 * @param ignore not used
68 * @return the UTF-8 encoded thread dump or message to return to the tool user
69 */
70 public static byte[] dumpThreads(String file, boolean okayToOverwrite, boolean ignore) {
71 if (file == null || file.equals("-")) {
72 return dumpThreadsToByteArray(false, false, MAX_BYTE_ARRAY_SIZE);
73 } else {
74 return dumpThreadsToFile(file, okayToOverwrite, false, false);
75 }
76 }
77
78 /**
79 * Generate a thread dump in JSON format to a file or byte array, UTF-8 encoded.
80 * This method is invoked by the VM for the Thread.dump_to_file diagnostic command.
81 *
82 * @param file the file path to the file, null or "-" to return a byte array
83 * @param okayToOverwrite true to overwrite an existing file
84 * @return the UTF-8 encoded thread dump or message to return to the tool user
85 */
86 public static byte[] dumpThreadsToJson(String file, boolean okayToOverwrite, boolean prettyPrint) {
87 if (file == null || file.equals("-")) {
88 return dumpThreadsToByteArray(true, prettyPrint, MAX_BYTE_ARRAY_SIZE);
89 } else {
90 return dumpThreadsToFile(file, okayToOverwrite, true, prettyPrint);
91 }
92 }
93
94 /**
95 * Generate a thread dump in plain text or JSON format to a byte array, UTF-8 encoded.
96 * This method is the implementation of the Thread.dump_to_file diagnostic command
97 * when a file path is not specified. It returns the thread dump and/or message to
98 * send to the tool user.
99 */
100 private static byte[] dumpThreadsToByteArray(boolean json, boolean prettyPrint, int maxSize) {
101 var out = new BoundedByteArrayOutputStream(maxSize);
102 try (out; var writer = new TextWriter(out)) {
103 if (json) {
104 dumpThreadsToJson(writer, prettyPrint);
105 } else {
106 dumpThreads(writer);
107 }
108 } catch (Exception ex) {
109 if (ex instanceof UncheckedIOException ioe) {
110 ex = ioe.getCause();
111 }
112 String reply = String.format("Failed: %s%n", ex);
113 return reply.getBytes(StandardCharsets.UTF_8);
114 }
115 return out.toByteArray();
116 }
117
118 /**
119 * Generate a thread dump in plain text or JSON format to the given file, UTF-8 encoded.
120 * This method is the implementation of the Thread.dump_to_file diagnostic command.
121 * It returns the thread dump and/or message to send to the tool user.
122 */
123 private static byte[] dumpThreadsToFile(String file,
124 boolean okayToOverwrite,
125 boolean json,
126 boolean prettyPrint) {
127 Path path = Path.of(file).toAbsolutePath();
128 OpenOption[] options = (okayToOverwrite)
129 ? new OpenOption[0]
130 : new OpenOption[] { StandardOpenOption.CREATE_NEW };
131 String reply;
132 try (OutputStream out = Files.newOutputStream(path, options)) {
133 try (var writer = new TextWriter(out)) {
134 if (json) {
135 dumpThreadsToJson(writer, prettyPrint);
136 } else {
137 dumpThreads(writer);
138 }
139 reply = String.format("Created %s%n", path);
140 } catch (UncheckedIOException e) {
141 reply = String.format("Failed: %s%n", e.getCause());
142 }
143 } catch (FileAlreadyExistsException _) {
144 reply = String.format("%s exists, use -overwrite to overwrite%n", path);
145 } catch (Exception ex) {
146 reply = String.format("Failed: %s%n", ex);
147 }
148 return reply.getBytes(StandardCharsets.UTF_8);
149 }
150
151 /**
152 * Generate a thread dump in plain text format to the given output stream, UTF-8
153 * encoded. This method is invoked by HotSpotDiagnosticMXBean.dumpThreads.
154 * @throws IOException if an I/O error occurs
155 */
167 /**
168 * Generate a thread dump in plain text format to the given text stream.
169 * @throws UncheckedIOException if an I/O error occurs
170 */
171 private static void dumpThreads(TextWriter writer) {
172 writer.println(processId());
173 writer.println(Instant.now());
174 writer.println(Runtime.version());
175 writer.println();
176 dumpThreads(ThreadContainers.root(), writer);
177 }
178
179 private static void dumpThreads(ThreadContainer container, TextWriter writer) {
180 container.threads().forEach(t -> dumpThread(t, writer));
181 container.children().forEach(c -> dumpThreads(c, writer));
182 }
183
184 private static boolean dumpThread(Thread thread, TextWriter writer) {
185 ThreadSnapshot snapshot = ThreadSnapshot.of(thread);
186 if (snapshot == null) {
187 return false; // thread not alive
188 }
189 Instant now = Instant.now();
190 Thread.State state = snapshot.threadState();
191 writer.println("#" + thread.threadId() + " \"" + escape(snapshot.threadName())
192 + "\" " + (thread.isVirtual() ? "virtual " : "")
193 + decorateObject(thread)
194 + " " + state
195 + " cpuTime=" + snapshot.cpuTime()
196 + " " + now);
197 StackTraceElement[] stackTrace = snapshot.stackTrace();
198 int depth = 0;
199 while (depth < stackTrace.length) {
200 writer.print(" at ");
201 writer.println(stackTrace[depth]);
202 snapshot.ownedMonitorsAt(depth).forEach(o -> {
203 if (o != null) {
204 writer.println(" - locked " + decorateObject(o));
205 } else {
206 writer.println(" - lock is eliminated");
207 }
232 writer.println();
233 return true;
234 }
235
236 /**
237 * Returns the identity string for the given object in a form suitable for the plain
238 * text format thread dump.
239 */
240 private static String decorateObject(Object obj) {
241 return "<" + Objects.toIdentityString(obj) + ">";
242 }
243
244 /**
245 * Generate a thread dump in JSON format to the given output stream, UTF-8 encoded.
246 * This method is invoked by HotSpotDiagnosticMXBean.dumpThreads.
247 * @throws IOException if an I/O error occurs
248 */
249 public static void dumpThreadsToJson(OutputStream out) throws IOException {
250 var writer = new TextWriter(out);
251 try {
252 dumpThreadsToJson(writer, /*prettyPrint*/true);
253 writer.flush();
254 } catch (UncheckedIOException e) {
255 IOException ioe = e.getCause();
256 throw ioe;
257 }
258 }
259
260 /**
261 * JSON is schema-less and the thread dump format will evolve over time.
262 * {@code HotSpotDiagnosticMXBean.dumpThreads} links to a JSON file that documents
263 * the latest/current format. A system property can be used to generate the thread
264 * dump in older formats if necessary.
265 */
266 private static class JsonFormat {
267 private static final String JSON_FORMAT_VERSION_PROP =
268 "com.sun.management.HotSpotDiagnosticMXBean.dumpThreads.format";
269 static final int JSON_FORMAT_V1 = 1;
270 static final int JSON_FORMAT_V2 = 2;
271 private static final int JSON_FORMAT_LATEST = JSON_FORMAT_V2;
272 private static final int JSON_FORMAT;
273 static {
274 int ver = Integer.getInteger(JSON_FORMAT_VERSION_PROP, JSON_FORMAT_LATEST);
275 JSON_FORMAT = Math.clamp(ver, JSON_FORMAT_V1, JSON_FORMAT_LATEST);
276 }
277
278 static int formatVersion() {
279 return JSON_FORMAT;
280 }
281 }
282
283 /**
284 * Generate a thread dump to the given text stream in JSON format.
285 * @throws UncheckedIOException if an I/O error occurs
286 */
287 private static void dumpThreadsToJson(TextWriter textWriter, boolean prettyPrint) {
288 int format = JsonFormat.formatVersion();
289 boolean generateLongsAsString = (format == JsonFormat.JSON_FORMAT_V1);
290 var jsonWriter = new JsonWriter(textWriter, prettyPrint, generateLongsAsString);
291 jsonWriter.startObject(); // top-level object
292 jsonWriter.startObject("threadDump");
293 if (format > JsonFormat.JSON_FORMAT_V1) {
294 jsonWriter.writeProperty("formatVersion", format);
295 }
296
297 jsonWriter.writeLongProperty("processId", processId());
298 jsonWriter.writeProperty("time", Instant.now());
299 jsonWriter.writeProperty("runtimeVersion", Runtime.version());
300
301 jsonWriter.startArray("threadContainers");
302 dumpThreads(ThreadContainers.root(), jsonWriter);
303 jsonWriter.endArray();
304
305 jsonWriter.endObject(); // threadDump
306
307 jsonWriter.endObject(); // end of top-level object
308 }
309
310 /**
338 if (!ThreadContainers.trackAllThreads()) {
339 threadCount = Long.max(threadCount, container.threadCount());
340 }
341 jsonWriter.writeLongProperty("threadCount", threadCount);
342
343 jsonWriter.endObject();
344
345 // the children of the thread container follow
346 container.children().forEach(c -> dumpThreads(c, jsonWriter));
347 }
348
349 /**
350 * Write a thread to the given JSON writer.
351 * @return true if the thread dump was written, false otherwise
352 * @throws UncheckedIOException if an I/O error occurs
353 */
354 private static boolean dumpThread(Thread thread, JsonWriter jsonWriter) {
355 Instant now = Instant.now();
356 ThreadSnapshot snapshot = ThreadSnapshot.of(thread);
357 if (snapshot == null) {
358 return false; // thread not alive
359 }
360 Thread.State state = snapshot.threadState();
361 StackTraceElement[] stackTrace = snapshot.stackTrace();
362
363 jsonWriter.startObject();
364 jsonWriter.writeLongProperty("tid", thread.threadId());
365 jsonWriter.writeProperty("time", now);
366 if (thread.isVirtual()) {
367 jsonWriter.writeProperty("virtual", Boolean.TRUE);
368 }
369 jsonWriter.writeProperty("name", snapshot.threadName());
370 jsonWriter.writeProperty("threadObj", Objects.toIdentityString(thread));
371 jsonWriter.writeProperty("state", state);
372 if (snapshot.cpuTime() != -1L) {
373 jsonWriter.writeLongProperty("cpuTime", snapshot.cpuTime());
374 }
375
376 // park blocker
377 Object parkBlocker = snapshot.parkBlocker();
378 if (parkBlocker != null) {
435 private static class JsonWriter {
436 private static class Node {
437 final boolean isArray;
438 int propertyCount;
439 Node(boolean isArray) {
440 this.isArray = isArray;
441 }
442 boolean isArray() {
443 return isArray;
444 }
445 int propertyCount() {
446 return propertyCount;
447 }
448 int getAndIncrementPropertyCount() {
449 int old = propertyCount;
450 propertyCount++;
451 return old;
452 }
453 }
454 private final Deque<Node> stack = new ArrayDeque<>();
455 private final TextWriter writer;
456 private final boolean prettyPrint; // pretty print or minify
457 private final boolean generateLongsAsString;
458
459 JsonWriter(TextWriter writer, boolean prettyPrint, boolean generateLongsAsString) {
460 this.writer = writer;
461 this.prettyPrint = prettyPrint;
462 this.generateLongsAsString = generateLongsAsString;
463 }
464
465 private void print(Object obj) {
466 writer.print(obj);
467 }
468
469 private void println(Object obj) {
470 if (prettyPrint) {
471 writer.println(obj);
472 } else {
473 writer.print(obj);
474 }
475 }
476
477 private void println() {
478 if (prettyPrint) {
479 writer.println();
480 }
481 }
482
483 private void indent() {
484 if (prettyPrint) {
485 int indent = stack.size() * 2;
486 writer.print(" ".repeat(indent));
487 }
488 }
489
490 /**
491 * Start of object or array.
492 */
493 private void startObject(String name, boolean isArray) {
494 if (!stack.isEmpty()) {
495 Node node = stack.peek();
496 if (node.getAndIncrementPropertyCount() > 0) {
497 println(",");
498 }
499 }
500 indent();
501 if (name != null) {
502 String gap = prettyPrint ? " " : "";
503 print("\"" + name + "\":" + gap);
504 }
505 println(isArray ? "[" : "{");
506 stack.push(new Node(isArray));
507 }
508
509 /**
510 * End of object or array.
511 */
512 private void endObject(boolean isArray) {
513 Node node = stack.pop();
514 if (node.isArray() != isArray)
515 throw new IllegalStateException();
516 if (node.propertyCount() > 0) {
517 println();
518 }
519 indent();
520 print(isArray ? "]" : "}");
521 }
522
523 /**
524 * Write a property.
525 * @param name the property name, null for an unnamed property
526 * @param obj the value or null
527 */
528 void writeProperty(String name, Object obj) {
529 Node node = stack.peek();
530 assert node != null;
531 if (node.getAndIncrementPropertyCount() > 0) {
532 println(",");
533 }
534 indent();
535 if (name != null) {
536 print("\"" + name + "\": ");
537 }
538 switch (obj) {
539 case Number _ -> print(obj);
540 case Boolean _ -> print(obj);
541 case null -> print("null");
542 default -> print("\"" + escape(obj.toString()) + "\"");
543 }
544 }
545
546 /**
547 * Write a property with a long value. If the value is outside the "interop"
548 * range of IEEE-754 double-precision floating point (64-bit) then it is
549 * written as a string.
550 */
551 void writeLongProperty(String name, long value) {
552 if (generateLongsAsString || value < -0x1FFFFFFFFFFFFFL || value > 0x1FFFFFFFFFFFFFL) {
553 writeProperty(name, Long.toString(value));
554 } else {
555 writeProperty(name, value);
556 }
557 }
558
559 /**
560 * Write an unnamed property.
561 */
562 void writeProperty(Object obj) {
|