Teams keep deploying a graph database to solve a problem that fits in 40 MB of heap. Route planning over 30,000 junctions, dependency reachability across 5,000 Maven artifacts, permission inheritance in a document tree — none of that needs a server, a network hop, or a Cypher query. It needs a graph data structure and a shortest-path algorithm, in-process.

Three libraries cover that space on the JVM, and in 2026 they are not close: JGraphT is an algorithms library with real graph types, Guava Graph is a small, well-designed primitive set buried inside a 3 MB utility jar, and JUNG is a 2000s-era academic project whose last release predates Java 9. Choosing badly means either writing your own Dijkstra or fighting a library that was designed before generics were standard.

TL;DR

  • Use JGraphT 1.5.3 for anything that needs an algorithm: shortest paths, max flow, spanning trees, matching, cycle detection, topological order. It is the only one of the three with a maintained algorithm catalogue.
  • Use Guava Graph if you already ship Guava and you only need to model relationships, check connectivity, or traverse a hierarchy. It is a data structure, not an algorithm library.
  • Avoid JUNG for new code. Its last published release is 2.1.1 from September 2016. The repository receives occasional commits, but no release has shipped in nine years.
DimensionJGraphTGuava GraphJUNG
GitHub stars2,78651,922 (all of Guava)431
Latest release1.5.333.8.0-jre2.1.1
Release date2026Nov 2026Sep 2016
Last commitDec 2026Dec 2026Nov 2026
ScopeGraph types + 100+ algorithmsGraph types + traversal onlyGraph types + algorithms + visualization
Graph modelsSimple, multigraph, pseudograph, directed/undirected, weighteddirected/undirected, Network for edge valuesdirected/undirected, sparse/dense, hypergraph
Weighted edgesDefaultWeightedEdge + setEdgeWeightNo native weightsVia edge objects you define
VisualizationExport to DOT / GraphMLNoneSwing-based renderer
Dependency weight~2.4 MB (core + fastutil)Part of a 3 MB Guava jar~1 MB across 3 artifacts
VerdictDefault choiceFine for modelingLegacy only

Decision Matrix

Your taskPickReason
Shortest path with weights on 100k edgesJGraphTDijkstraShortestPath plus fastutil-backed graph types
“Can service A reach service B?” in a dependency graphGuava GraphGraphs.reachableNodes is two lines and already in your classpath
Maximum flow / min cut on a capacity networkJGraphTPushRelabelMFImpl, EdmondsKarpMFImpl ship in core
Topological ordering of a build graphJGraphTTopologicalOrderIterator handles cycles with a clear failure
Transitive closure of a permission treeGuava GraphGraphs.transitiveClosure is one call
Force-directed layout drawn into a Swing panelJUNGIt is the only one with a built-in renderer
Detecting communities / clusteringJGraphTClustering and VertexColoring algorithms included
You need persisted graphs across restartsNoneUse a graph database, then load a subgraph into JGraphT

JGraphT 1.5.3 — The Working Choice

JGraphT separates graph structure from graph algorithms, and it takes both seriously. Structure comes from a family of interfaces (Graph, Digraph, WeightedGraph, ListenableGraph) with concrete implementations for every combination of directedness, self-loops, and parallel edges. Algorithms live in org.jgrapht.alg.* and cover shortest paths, spanning trees, flows, matching, coloring, clustering, isomorphism, and traversals.

Under the hood, the default implementations are backed by fastutil-style specialized maps, which is why JGraphT handles hundreds of thousands of edges without the boxing overhead you get from a HashMap<String, List<String>> built by hand.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import org.jgrapht.Graph;
import org.jgrapht.GraphPath;
import org.jgrapht.alg.shortestpath.DijkstraShortestPath;
import org.jgrapht.graph.DefaultWeightedEdge;
import org.jgrapht.graph.SimpleDirectedWeightedGraph;

Graph<String, DefaultWeightedEdge> network =
        new SimpleDirectedWeightedGraph<>(DefaultWeightedEdge.class);

network.addVertex("ams");
network.addVertex("fra");
network.addVertex("sin");

DefaultWeightedEdge amsFra = network.addEdge("ams", "fra");
network.setEdgeWeight(amsFra, 420.0);   // milliseconds, kilometres, cost — your unit

DefaultWeightedEdge fraSin = network.addEdge("fra", "sin");
network.setEdgeWeight(fraSin, 6400.0);

DijkstraShortestPath<String, DefaultWeightedEdge> dijkstra =
        new DijkstraShortestPath<>(network);

GraphPath<String, DefaultWeightedEdge> path = dijkstra.getPath("ams", "sin");
System.out.println(path.getVertexList());  // [ams, fra, sin]
System.out.println(path.getWeight());      // 6820.0

Unweighted graphs need less ceremony — DijkstraShortestPath.findPathBetween(graph, "a", "z") is a static one-liner. Topological ordering and cycle detection are equally direct:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
import org.jgrapht.alg.cycle.CycleDetector;
import org.jgrapht.alg.shortestpath.TopologicalOrderIterator;
import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.graph.SimpleDirectedGraph;

Graph<String, DefaultEdge> build = new SimpleDirectedGraph<>(DefaultEdge.class);
build.addVertex("core");
build.addVertex("api");
build.addVertex("web");
build.addEdge("core", "api");
build.addEdge("api", "web");

TopologicalOrderIterator<String, DefaultEdge> order = new TopologicalOrderIterator<>(build);
order.forEachRemaining(System.out::println);   // core, api, web

CycleDetector<String, DefaultEdge> cycles = new CycleDetector<>(build);
System.out.println(cycles.detectCycles());     // false

JGraphT graph model from the official user guide

Dependency:

1
2
3
4
5
<dependency>
  <groupId>org.jgrapht</groupId>
  <artifactId>jgrapht-core</artifactId>
  <version>1.5.3</version>
</dependency>

Two caveats. First, vertex and edge objects must have sane equals/hashCode — JGraphT uses them as map keys, so a mutable vertex whose hash changes after insertion will silently vanish from lookups. Second, SimpleGraph rejects parallel edges by design; if you model a road network where two roads connect the same cities, use Multigraph or Pseudograph and expect a different algorithm API surface.

Guava Graph 33.8.0 — A Data Structure, Not an Algorithm Library

Guava’s graph module was added in 2016 and has barely changed since, because it does one thing well: model relationships with a clean, type-safe API. You get Graph (edges have no value), ValueGraph (deprecated in favour of Network), and Network (edges carry an object).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
import com.google.common.graph.GraphBuilder;
import com.google.common.graph.Graphs;
import com.google.common.graph.MutableGraph;
import com.google.common.graph.Traverser;

MutableGraph<String> deps = GraphBuilder.directed().build();
deps.putEdge("web", "api");
deps.putEdge("api", "auth");
deps.putEdge("auth", "db");

// Everything reachable from "web", breadth-first, lazily
for (String node : Traverser.forGraph(deps).breadthFirst("web")) {
    System.out.println(node);            // web, api, auth, db
}

// Reachability as a set, and the full transitive closure
System.out.println(Graphs.reachableNodes(deps, "web"));   // [web, api, auth, db]
MutableGraph<String> closure = Graphs.transitiveClosure(deps);

That is genuinely useful and genuinely limited. There is no Dijkstra, no max flow, no coloring, no matching. Edge weights do not exist as a first-class concept — you either put a weighted object on a Network edge or maintain a side map. For a service dependency graph or an org chart, none of that matters. For a routing problem, it is disqualifying.

Dependency — note you are pulling the whole utility jar:

1
2
3
4
5
<dependency>
  <groupId>com.google.guava</groupId>
  <artifactId>guava</artifactId>
  <version>33.8.0-jre</version>
</dependency>

The trap most teams hit is mutability. MutableGraph is mutable, and there is no immutable counterpart that preserves the graph interface — ImmutableGraph exists, but converting back and forth for incremental updates is clumsy. Decide early whether the graph is a build-time artifact or a live structure, and do not pass MutableGraph across module boundaries.

JUNG 2.1.1 — Still Teaching, No Longer Shipping

JUNG (Java Universal Network/Graph Framework) was the standard answer in 2008. It remains the only one of the three with a built-in Swing visualization layer, which is why it still shows up in academic code and internal analysis tools.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
import edu.uci.ics.jung.algorithms.scoring.PageRank;
import edu.uci.ics.jung.graph.DirectedSparseMultigraph;
import edu.uci.ics.jung.graph.Graph;

Graph<String, String> g = new DirectedSparseMultigraph<>();
g.addVertex("a");
g.addVertex("b");
g.addVertex("c");
g.addEdge("e1", "a", "b");
g.addEdge("e2", "b", "c");
g.addEdge("e3", "c", "a");

PageRank<String, String> rank = new PageRank<>(g, 0.15);
rank.evaluate();
System.out.println(rank.getVertexScore("a"));

The code still compiles and runs on current JDKs. The problem is everything around it. The release is from 2016; the Maven coordinates (net.sf.jung:jung-graph-impl, jung-algorithms, jung-visualization) have not moved since. There is no JPMS module descriptor, so you will add --add-opens flags or live with classpath mode. The visualization module depends on Swing, which means it does not run headless without extra configuration.

Use it if you have an existing analysis tool built on it and the cost of rewriting exceeds the cost of pinning an old dependency. Do not adopt it for a new service — the algorithm coverage you would gain over JGraphT is roughly zero, and you inherit a nine-year-old dependency graph.

What Actually Matters at Scale

Published microbenchmarks for these libraries are mostly noise: they measure a 1,000-vertex graph built in a loop, then quote nanoseconds. The properties that decide real workloads are different.

Representation overhead. JGraphT’s default graphs store adjacency in specialized primitive-friendly maps, which keeps memory proportional to edges with modest per-entry overhead. Guava’s graphs are built on HashSet/HashMap of boxed references — fine up to a few hundred thousand edges, wasteful beyond. JUNG allocates an edge object per relationship plus separate incident-edge sets, which is the heaviest of the three.

Algorithm availability as a cost multiplier. If the algorithm you need is missing, you write it, test it, and own it. A hand-rolled Dijkstra that ignores negative weights, or a topological sort that loops forever on a cycle, is a production incident waiting to happen. JGraphT’s catalogue is worth a dependency on its own.

Graph rebuild cost. All three are in-memory structures. If your source of truth is a relational table, you rebuild the graph on startup and after every relevant write. For a 200,000-edge graph that is a second or two — acceptable at boot, painful per request. Cache the built graph and invalidate on change, or move to a graph database.

Serialization. JGraphT can export to DOT and GraphML, which is how you inspect a production graph offline. Guava and JUNG have no built-in export format; you write the serializer.

Pitfalls That Bite in Production

  • Mutable vertex keys. A vertex object whose hashCode depends on a mutable field will disappear from JGraphT’s internal maps after the field changes. Use immutable identifiers — a record, a String, a long.
  • Undirected vs directed mistakes. Guava’s GraphBuilder.undirected() treats putEdge(a, b) and putEdge(b, a) as the same edge. Building a directed graph by accident produces plausible-but-wrong reachability results that tests rarely catch.
  • Parallel edges in SimpleGraph. JGraphT throws IllegalArgumentException on a duplicate edge in a simple graph. Road networks and message flows usually need Multigraph.
  • Self-loops. All three allow them, and most algorithms silently mishandle them. Filter self-loops at ingest unless your domain genuinely has them.
  • Cycle detection is not free. JGraphT’s CycleDetector is a full traversal. Calling it inside a per-request code path on a large graph will dominate your latency profile.
  • Heap sizing. A graph of 1 million edges with boxed String vertices comfortably exceeds 300 MB. If your container limit is 512 MB, model vertices as int indices and keep a separate lookup table.
  • Thread safety. None of the three is thread-safe for concurrent mutation. Build once, publish as an immutable reference, and read concurrently — that pattern is safe; concurrent writes are not.

When You Should Reach for a Graph Database Instead

In-process libraries stop being the right answer when any of these is true: the graph does not fit in heap, you need multi-hop queries with predicates that change per request, several services must read the same graph, or you need durability and time-travel over graph state. At that point the comparison shifts to graph databases like Dgraph, JanusGraph and OrientDB, and the library becomes a client-side cache of a subgraph.

The same split shows up in routing: at city scale you can run Dijkstra in-process, but continental road networks need a dedicated engine, as covered in self-hosted routing engines — GraphHopper vs OSRM vs Valhalla. And if you are optimizing memory for large primitive-heavy structures, the techniques in Java collections libraries — Eclipse Collections, Fastutil and HPPC apply directly to graph adjacency storage.

FAQ

Is JGraphT fast enough for production use?

Yes. JGraphT is used in compiler tooling, network analysis, and scheduling systems where graphs reach hundreds of thousands of edges. Its default graph implementations are memory-efficient, and the algorithms are textbook implementations with test coverage. The limiting factor is usually heap size and rebuild frequency, not algorithmic speed.

Can Guava Graph compute a shortest path?

No. Guava’s graph module offers traversal (Traverser), reachability, transitive closure, and connectivity checks. It has no weighted shortest-path implementation. If you need distances, use JGraphT and pass Guava’s graph in as a view or convert it once.

Is JUNG still maintained in 2026?

Barely. The last published release is 2.1.1 from September 2016, although the repository still receives occasional commits. It compiles on modern JDKs but has no module descriptor and depends on Swing for visualization. Treat it as a legacy dependency, not a candidate for new work.

Do I need a graph database if I use JGraphT?

Only if the graph is too large for heap, needs to be shared across services, or requires durable multi-hop queries. For a single service answering path or reachability questions over a graph that fits in memory, JGraphT plus a rebuild-on-change strategy is simpler and faster than operating a database.

Which library handles multigraphs and parallel edges best?

JGraphT. It offers Multigraph, Pseudograph, and directed variants, each with a distinct contract, and its algorithms declare which graph features they support. Guava’s Graph disallows parallel edges entirely, and JUNG’s SparseMultigraph allows them but with heavier per-edge allocation.

How do I visualize a graph built with JGraphT?

Export to DOT and render with Graphviz: new DOTExporter<String, DefaultEdge>().exportGraph(graph, writer). That keeps visualization out of your runtime dependencies and works in CI. JUNG’s built-in renderer is an option only if you are already on JUNG and running a desktop UI.


💰 想测试你的市场判断力?我用 Polymarket 做预测市场交易——这是全球最大的预测市场平台,从大选结果到技术监管时间线,什么都可以押注。和赌博不同,这是真正的信息市场:你懂的信息越多,胜率越高。我靠预测技术相关事件的走向已经赚了不少。用我的邀请链接注册:Polymarket.com