Tracing programs
After your first trace and reading its output, choose the task you need below. Work in the directory containing your downloaded code-tracer.jar, with a full JDK 21 or later selected as described in installation. Save the example files as UTF-8. No source checkout is needed.
Commands work in Bash, PowerShell 7.4+, and Command Prompt unless a shell-specific alternative is shown. Tracing commands include the explicit trace subcommand. --input (-i) takes a source file, not a directory; when omitted, the tracer reads source from its standard input. That is separate from the input read by the traced program.
| Task | Recipe |
|---|---|
| Check whether a teaching program can be traced | Program requirements |
| Capture the final state or a sequence of states | Choose snapshots |
| Compare repeated hits at a loop line | Trace a loop |
| Give the program input | Supply program input |
| Submit a program with several source files | Submit multiple files |
| Show what several threads are doing | Trace a multithreaded program |
| Use precompiled classes or a dependency JAR | Add binary dependencies |
| Raise a budget for a complete trusted trace | Tune a tracing budget |
| Change output presentation or keep a partial result | Choose presentation and budgets |
Program requirements
For ordinary single-file input without delimiters, include exactly one public top-level type. The tracer derives the temporary source filename from that type; the original filename does not replace this requirement. To submit explicitly named files, use the delimited bundle. Compact source files such as a file containing only void main() { ... } are not supported.
The entry file is the first submitted file containing a recognized main-method candidate. That file must contain exactly one candidate, including candidates inside nested types; helper files do not need a main method. A candidate returns void, is named main, and accepts no parameters, one String[] parameter, or one String... parameter. Source selection does not check access or static modifiers, so recognition alone does not guarantee that the active JDK can launch it. Use public static void main(String[] args) for the CLI examples across the tested JDKs.
The traced String[] args is empty. There is no tracer option for passing program arguments, and arguments after -- are not forwarded to the guest. Adapt an argument-driven example to read guest standard input, or supply its demonstration values in the source.
Choose snapshots
Save this as SnapshotDemo.java:
public class SnapshotDemo {
public static void main(String[] args) {
int value = 7;
value++;
System.out.println(value);
}
}
For the state at main exit, run:
java -jar code-tracer.jar trace -i SnapshotDemo.java --format modern --pretty > final-trace.json
For a sequence that includes the change from 7 to 8, run:
java -jar code-tracer.jar trace -i SnapshotDemo.java --all-breakpoints --format modern --pretty > snapshots.json
Both runs capture final guest stdout 8 followed by a newline. Open snapshots.json and follow value through the main frame's locals; a line stop can precede the statement's effect. The final-state command omits breakpoint options, so it selects main exit. Envelope mode places that capture inside a sequence root.
This default capture expects a main-exit snapshot. There are current limitations when main ends through System.exit, including status zero, or an uncaught exception thrown inside JDK code: ordinary default capture can exit 1, report an internal missing-snapshot error, and leave the JSON file empty. Use chronological capture (--all-breakpoints) or selected executable locations to retain the states reached before termination. A directly thrown exception in submitted code can instead supply a terminal exception snapshot in place of normal main exit. See capture when main does not return and uncaught exceptions for the differences between trace generation and guest success.
To select particular stops, use list-breakpoints to discover executable lines; blank lines and declarations need not have a location. The loop tutorial compares the following choices:
| Selection | Retained snapshots |
|---|---|
--all-breakpoints |
Encountered stops in execution order. |
--breakpoints "12,Helper.java:5" |
Latest hit for each selected file/line; bare line-number result keys can group multiple files. |
--breakpoints=-1 |
Main exit. |
--breakpoints 4 --accumulate-breakpoints |
Repeated hits at the selected line. Accumulation alone does not select loop lines. |
--breakpoints 4 --all-breakpoints |
Source-line stops restricted to the selection, retained chronologically. |
Chronological capture already retains repeated hits. Selected-breakpoint and chronological output can have different roots; use the output reference when comparing their JSON.
Supply program input
Save this as Greeting.java:
import java.util.Scanner;
public class Greeting {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String name = input.nextLine();
System.out.println("Hello, " + name + "!");
}
}
Save input.txt with this line and a newline at the end:
Ada
java -jar code-tracer.jar trace -i Greeting.java --stdin-file input.txt --all-breakpoints --format modern --pretty > input-trace.json
The final captured stdout is Hello, Ada! followed by a newline. The source comes from Greeting.java; the guest's input comes from input.txt. For a short literal input, replace --stdin-file input.txt with --stdin "Ada"; do not supply both options. Omitted guest input is an empty stream, so reads reach end-of-input instead of prompting the tracer's terminal. Guest output is inside the JSON; tracer diagnostics for this ordinary command remain on terminal stderr. For example, running Greeting.java without guest input makes Scanner.nextLine() throw NoSuchElementException. Keep --all-breakpoints when inspecting that failure; the default main-exit limitation described above can otherwise prevent JSON output. With --result-envelope, read job diagnostics inside the JSON envelope instead.
Submit multiple files
Save this complete bundle as submission.txt; the delimiter lines name the two source files:
// --- demo/Helper.java ---
package demo;
public class Helper {
public static int answer() {
return 42;
}
}
// --- demo/Main.java ---
package demo;
public class Main {
public static void main(String[] args) {
System.out.println(Helper.answer());
}
}
In Bash or Command Prompt, pass the bundle through the tracer's standard input:
java -jar code-tracer.jar trace --all-breakpoints --format modern --pretty < submission.txt > multi-trace.json
PowerShell does not support < input redirection. Use its UTF-8 text pipeline:
Get-Content -Raw -Encoding utf8 submission.txt | java -jar code-tracer.jar trace --all-breakpoints --format modern --pretty > multi-trace.json
The final captured stdout is 42 followed by a newline. sources contains demo/Helper.java and demo/Main.java; entryFile is demo/Main.java. The tracer selects the first file with a recognized main-method candidate. File-qualified breakpoint line numbers start at each file's first content line, excluding the delimiter.
Under the default TRUSTED inspection policy, CLI compilation can discover neighboring sources when the entry file declares a package. With --input, its parent directories must match the package path; the directory above that path becomes the source root. For source read from stdin, the tracer looks for the package directory beneath its working directory, then src/main/java, then src. Default-package programs have no neighboring-source discovery: a helper beside Main.java is not automatically compiled, so include it in the bundle.
Discovered dependencies can affect compilation and tracing without appearing in the submitted sources map. To avoid unintentionally compiling matching files from the working directory, submit all required source and use --result-envelope --inspection FIELDS, or run trusted stdin examples from a directory without matching package folders. FIELDS means field-only inspection; it also disables neighboring discovery. Multithread capture selects that same source-discovery policy. See CLI source discovery and inspection policies for the exact boundaries; none of these choices provides host isolation. The delimited source bundle reference defines the delimiter grammar and path rules. For Java code that assembles bundles programmatically, use the SourceBundle reference, including its ordering, validation, file-capture, and link-following rules.
Trace a multithreaded program
Save this as Workers.java:
public class Workers {
public static void main(String[] args) throws InterruptedException {
int[] counts = new int[2];
Thread worker = new Thread(() -> {
counts[0] = 21;
}, "worker");
worker.start();
counts[1] = 21;
worker.join();
System.out.println(counts[0] + counts[1]);
}
}
Thread capture requires modern JSON and always records a chronological sequence:
java -jar code-tracer.jar trace -i Workers.java --multithread --format modern --pretty > threads.json
The trace captures final guest stdout 42 followed by a newline in the last step's stdout. Every step in threads.json has a threads array, with each thread's id, name, state, and callStack, and a triggeringThreadId naming the thread that stopped. The top-level callStack is that triggering thread's stack. When worker stops at line 5, the main entry in threads still shows main's frame and locals. Steps whose event is thread_start or thread_death mark thread lifecycle changes and can have no source location.
Without --multithread, this command captures only the final main-exit state. With --all-breakpoints or --breakpoints instead, a stop reached in worker code records only the stopping thread's stack and no thread identity, so main's frame seems to disappear during those steps. For a program that might never finish, add --result-envelope and explicit limits such as --timeout-ms 5000 to keep a partial trace. See opt-in thread capture for every field, event, and limitation.
Add binary dependencies
Use this recipe when the submitted program needs a compiled library. First save Helper.java beside the tracer JAR:
package teaching;
public class Helper {
public static int answer() {
return 42;
}
}
Save the program to trace as UseHelper.java:
import teaching.Helper;
public class UseHelper {
public static void main(String[] args) {
System.out.println(Helper.answer());
}
}
Use a new classes directory. These JDK tools compile the helper and package its classes; they do not run it:
mkdir classes
javac -d classes Helper.java
jar --create --file helper.jar -C classes .
java -jar code-tracer.jar trace -i UseHelper.java --class-path helper.jar --all-breakpoints --format modern --pretty > dependency-trace.json
The final captured stdout is 42 followed by a newline. The tracer compiles and traces UseHelper; the compiled helper supplies its return value but receives no source-line breakpoints. To use the compiled directory instead, replace --class-path helper.jar with --class-path classes.
--class-path, -classpath, and -cp are repeatable tracer options after the trace or list-breakpoints subcommand. The same entries serve compilation and execution. Directory entries contain package-relative class files and resources; adding a directory does not compile its Java sources or add JARs inside it. Explicit binary dependencies also work with FIELDS inspection and multithread tracing.
Each option accepts a platform-separated list (: on Linux/macOS, ; on Windows); repeated options append. Quote patterns so the tracer expands them. lib/* selects immediate .jar/.JAR files, while lib/**/*.jar matches immediate and nested lowercase .jar filenames. Pattern groups are sorted in place, and missing explicit paths or patterns with no matches fail preparation. Relative paths use the tracer's working directory. Local manifest dependencies are followed automatically; manifest directory URLs must end with /, such as classes/.
Keep borrowed dependencies available and unchanged until tracing finishes, or use --copy-class-path to capture them and available transitive manifest dependencies before compilation. Glob discovery skips symbolic links by default, while directory copying rejects links inside the tree. --follow-class-path-links enables following for both operations, including targets outside the selected root, and rejects broken links or cycles. Source limits do not bound binary dependency sizes. See the CLI reference and Java dependency API for complete rules.
Guest compilation disables annotation processing. Supply any required generated source files explicitly; annotations can still be used as ordinary dependency types.
Choose presentation and budgets
Use SnapshotDemo.java from Choose snapshots for this recipe:
java -jar code-tracer.jar trace -i SnapshotDemo.java --all-breakpoints --format modern --pretty --type-style simple --remove-main-args --include-primitive-bits > presentation-trace.json
The output still captures value changing from 7 to 8 and stdout 8 followed by a newline. It omits the main frame's args local, uses simple type labels, and includes binary metadata beside the primitive value. Compare it with snapshots.json: presentation options change the representation, not the program's source.
--format modern produces typed JSON objects; --format pytutor is the default. Ordinary modern JSON is always indented. --pretty indents Python Tutor output and result envelopes without changing capture selection. --remove-main-args, --remove-method-this, and --type-style simple adjust the presentation. --inline-strings applies only to Python Tutor output: it places string contents inline instead of using the default string-object representation. It has no effect on modern output, whose strings remain references to heap string objects. All three boolean options default to false; the default type style is fqn. The executable help currently omits the format qualification for --inline-strings; this paragraph describes its implemented behavior.
Trusted inspection evaluates lazy enum hash codes by default. Use --no-eval-enum-hash to suppress that evaluation, or --eval-enum-hash to enable it explicitly. If both appear, the last setting wins. Field-only and multithread inspection do not invoke guest methods regardless of this setting.
Add the optional --include-primitive-bits flag (no value required) to include binary encodings alongside primitive literals. It defaults to false, supports both formats and every capture mode, and does not require --result-envelope. Use --include-primitive-bits=true or --include-primitive-bits=false to set it explicitly; other explicit values are usage errors (exit 2).
The option does not change inspection policy, capture selection, or exit statuses. --multithread still requires --format modern; invalid arguments still produce CLI usage errors (exit 2). See the output reference for array/field placement and payload-size implications, and encoding definitions and references for normative specifications and informative explanations of the encoding formats.
Tune a tracing budget
Use SnapshotDemo.java from Choose snapshots, in the same directory as code-tracer.jar. An ordinary chronological trace permits 10,000 captured snapshots by default. To allow up to 20,000 while keeping the other ordinary budgets, run:
java -jar code-tracer.jar trace -i SnapshotDemo.java --all-breakpoints --format modern --max-snapshots 20000 > raised-limit.json
This small example should complete with exit status 0 and a nonempty raised-limit.json; its final captured stdout is 8 followed by a newline. For a longer trusted program that stopped with snapshot_limit, substitute that program's input file and choose a cap appropriate to its expected execution. Check the command's exit status and result before treating the trace as complete. Raising one cap can reveal another limit or a guest failure; it does not guarantee exit 0. Use the stop-code table to match the reported reason to its option, and the limits reference for accounting and budget rules.
For a trusted local example whose resource use you understand, --unlimited disables the ordinary default budgets:
java -jar code-tracer.jar trace -i SnapshotDemo.java --all-breakpoints --format modern --unlimited > unlimited-trace.json
The same small example should finish with exit 0 and final guest stdout 8\n. Prefer raising an individual cap when that is sufficient. Any explicit budget still applies alongside --unlimited, regardless of option order; for example, adding --max-snapshots 20000 retains that cap while other omitted budgets are unlimited. Fixed representation and thread restrictions also remain active, and the command can still fail. Neither approach supplies whole-job isolation or a whole-job deadline. Use finite explicit budgets and the runner contract for hosted submissions.
Keep partial results when a budget stops tracing
Ordinary tracing uses finite default budgets. If a budget stops it, the command exits with code 3 and writes no trace JSON. Use --result-envelope when you want an explicit status and the completed snapshots captured before the stop. Envelope mode leaves omitted limits unlimited, so choose every intended budget explicitly instead of assuming the ordinary defaults carry over.
This demonstration uses SnapshotDemo.java from Choose snapshots. It deliberately allows only one captured snapshot:
java -jar code-tracer.jar trace -i SnapshotDemo.java --all-breakpoints --format modern --pretty --result-envelope --inspection FIELDS --timeout-ms 5000 --max-snapshots 1 --max-output-bytes 65536 --max-heap-objects 1000 --max-elements 10000 --max-trace-bytes 33554432 --max-source-bytes 262144 --max-source-files 32 --max-threads 64 --max-frames 4096 --max-snapshot-bytes 8388608 > partial-result.json
Expect exit code 3. Open partial-result.json: status is stopped, complete is false, and stopReason is snapshot_limit. The completed snapshot is inside trace.steps; it is useful partial evidence, not proof that the program finished. For other failures, trace can be null when no usable payload is available.
These are illustrative budgets for a trusted example, not universal settings. FIELDS avoids inspection-time guest method calls and requires an envelope when selected explicitly. Neither inspection policy nor tracing budgets isolate guest code, and a tracing timeout does not cover the whole job. See the trace model, bounded result contract, and runner contract for those boundaries. The CLI reference defines the flags; the bounded tracing reference gives budget rules and the ordinary defaults listed above its limits table.
Sets and unmodifiable views
Trace the runnable set example after packaging:
java -jar target/code-tracer.jar trace -i examples/sets/Main.java --all-breakpoints --format modern
Use --format pytutor for Python Tutor output. The example keeps a mutable LinkedHashSet and an unmodifiable view. Adding through the backing reference changes the view's later captured elements; earlier snapshots remain unchanged. The view and its alias refer to one wrapper, separate from the backing set. Trusted inspection preserves the order returned by toArray(), including nulls. For raw storage, add --result-envelope --inspection FIELDS. See the set output contract for ordering, identity, and failure behavior.
Date and time values
After packaging the checkout, trace the date/time example from the repository root:
java -jar target/code-tracer.jar trace -i examples/java-time/Main.java --all-breakpoints --format modern
Use --format pytutor for Python Tutor output. The example source constructs a leap-day date, a time with nanosecond precision, their combined LocalDateTime, and a Duration of negative one nanosecond. It adds two seconds to the duration while retaining a reference to the original object.
Before the addition, elapsed and original refer to the same duration, whose fields are seconds = -1 and nanos = 999999999. After the addition, elapsed refers to a different duration with seconds = 1 and nanos = 999999999; original still refers to the unchanged object. The combined date-time's date and time fields retain their references to the component objects.
Trusted inspection reads these stored components without calling guest methods. For raw field traversal, add --result-envelope --inspection FIELDS. See date/time objects for supported types, component types, unknown-layout fallback, and budget accounting.