Wednesday, 25 November 2026

Parallel AI Agents with LangChain4j: Building a Code Review Workflow

   

In an AI agent workflow, not every task depends on the output of a previous task. When multiple agents can work independently on the same input, executing them sequentially can introduce unnecessary latency.

 

This is where the parallel workflow pattern becomes useful. A parallel workflow allows multiple specialized agents to execute at the same time. Once all the agents complete their work, their outputs can be collected and combined into a final result.

 

For example, imagine building an AI assistant that reviews a piece of Java code. Instead of asking one agent to check code quality, then security, then performance, and finally refactoring opportunities, we can have four specialized agents analyze the same code simultaneously.

 

The results can then be aggregated into a single code review report.

 

Conceptually:

 

Input → Multiple independent agents → Aggregate outputs → Final result

 


This pattern is particularly useful when the agents don't depend on one another's intermediate results.

 

Following table summarizes the sample usecases.

 

Use case

Parallel Agents

Code Review

Code Quality + Security + Performance + Refactoring

Travel Planning

Flights + Hotels + Restaurants + Activities

Content Creation

Research + SEO + Fact Checking + Writing

Document Analysis

Summary + Sentiment + Classification + Entity Extraction

Customer Support

Intent Detection + Sentiment + Knowledge Search + Policy Check

Product Recommendation

Price Analysis + Reviews + Feature Comparison + Alternatives

Financial Analysis

Revenue Analysis + Risk Analysis + Market Analysis + Competitor Analysis

Meeting Analysis

Summary + Action Items + Decisions + Sentiment

 

1. Sequential vs Parallel Workflow

The key question when designing an agent workflow is: Does Agent B need the output of Agent A?

 

·      If the answer is yes, the agents generally need to run sequentially.

 

·      If the answer is no, and the agents can independently process the same input, they are good candidates for parallel execution.

 

1.1        Sequential workflow

Consider a story-generation workflow:

 


Here, each step depends on the previous one.

 

·      The Story Reviewer needs the story produced by the Story Writer.

·      The Story Improver needs both the story and the review produced by the previous steps.

 

Therefore, executing these agents in parallel would not make sense.

 

The dependency looks like this:

Story Writer
     │
     ▼
Story Reviewer
     │
     ▼
Story Improver

   

So, the agents must wait for the required outputs before proceeding.

 

1.2 Parallel Workflow

Now consider a code review system. Suppose we have four specialized agents:

 


   

All four agents receive the same source code, but each performs a different analysis.

 

·      The Security Agent doesn't need the output of the Code Quality Agent.

·      The Performance Agent doesn't need the Security Agent's findings.

·      The Refactory Agent can independently analyze the source code and provide refactoring suggestions.

 

Therefore, these agents can execute concurrently. This is the fundamental difference between sequential and parallel workflows.

 

1.3 Why parallel execution matters?

Consider four agents, each taking approximately 10 seconds.

 

With a sequential workflow:

Agent A: 10s
Agent B: 10s
Agent C: 10s
Agent D: 10s
----------------
Total:   ~40s

   

If the four agents are independent and run concurrently:

 

Agent A: ───────── 10s
Agent B: ───────── 10s
Agent C: ───────── 10s
Agent D: ───────── 10s

The overall execution time can be closer to the slowest agent, rather than the sum of all agents' execution times.

 

Approximately:

Sequential ≈ A + B + C + D

Parallel   ≈ max(A, B, C, D)

 

There will of course be some overhead for scheduling, aggregation, model calls, and other infrastructure, so this isn't an exact formula. But it illustrates why parallel workflows can significantly reduce latency.

 

1.4 But parallel doesn't mean "always run everything in parallel"

This is an important design consideration. You should parallelize independent work, not simply split a workflow into multiple agents.

 

For example:


 

 

Here, the first analysis must happen before the parallel branches, because the downstream agents depend on the analyzed requirements. This gives us a hybrid workflow:

 

Sequential → Parallel → Aggregate

 

This is often more realistic than having an entirely parallel workflow.

 

1.5 A simple rule of thumb

Question

Workflow

Does Agent B depend on Agent A's output?                            

Sequential

Can A, B and C independently process the same input?                

Parallel

Do some steps depend on previous steps while others are independent?

Hybrid

 

Parallel workflow is not about having multiple agents. It is about identifying independent work that can be performed concurrently and then combining the results.

 

2. Example: Parallel Code Review Using Multiple Specialized Agents

A practical example of the parallel workflow pattern is an AI-powered Java code review system. Instead of asking a single agent to perform every type of code review, we divide the responsibility among multiple specialized agents.

 

To review a given Java source file, four independent agents are invoked:

 

·      Code Quality Expert: Analyzes readability, naming, duplication, SOLID violations, and maintainability.

·      Security Expert: Looks for injection vulnerabilities, authentication/authorization problems, sensitive data exposure, and input-validation issues.

·      Performance Expert: Analyzes algorithms, loops, object creation, collection usage, database/network calls, and memory-related problems.

·      Refactoring Expert: Identifies practical refactoring opportunities and provides the original and improved code.

 

The important point is that none of these agents needs to wait for another agent. They all receive the same Java source code and perform their analysis independently.

 

Let’s define interfaces for these agents.

 

CodeQualityExpert.java

public interface CodeQualityExpert {

    @UserMessage("""
            You are an expert Java code reviewer.

            Review the following Java code specifically for code quality.

            Look for:
            - Clean code violations
            - Poor naming
            - Code duplication
            - Maintainability issues
            - SOLID principle violations
            - Unnecessary complexity

            Provide a concise list of findings.
            Do not review security or performance.

            Java code:
            {{code}}
            """)
    @Agent
    List<String> reviewCodeQuality(@V("code") String code);
}

PerformanceExpert.java

public interface PerformanceExpert {

    @UserMessage("""
            You are an expert Java performance reviewer.

            Review the following Java code specifically for performance issues.

            Look for:
            - Inefficient algorithms
            - Unnecessary loops
            - Excessive object creation
            - Inefficient collection usage
            - Unnecessary database or network calls
            - Potential memory issues
            - Other performance bottlenecks

            Provide a concise list of findings.
            Do not review security or general code quality.

            Java code:
            {{code}}
            """)
    @Agent
    List<String> reviewPerformance(@V("code") String code);
}

RefactoringExpert.java

public interface RefactoringExpert {

    @UserMessage("""
            You are an expert Java refactoring specialist.

            Analyze the following Java code and identify practical refactoring
            opportunities that improve readability, maintainability, design,
            and simplicity.

            Return a JSON object with one field:
            - suggestions: array of refactoring suggestion objects

            Each suggestion object must contain:
            - issue
            - explanation
            - originalSnippet
            - refactoredSnippet

            IMPORTANT RULES:

            1. originalSnippet must contain the exact relevant code from the
               provided source code.

            2. refactoredSnippet must ALWAYS contain the complete replacement
               Java code after applying the suggested refactoring.

            3. Never return an empty, null, or "No code provided"
               refactoredSnippet.

            4. If the recommended refactoring is to remove unused or dead code,
               refactoredSnippet must contain the complete surrounding code
               after removing that code, rather than being empty.

            5. The refactoredSnippet must be valid Java code.

            6. Preserve the original behavior unless the refactoring itself
               requires a behavior-preserving structural change.

            7. Do not provide only a description of the changes. Always provide
               the actual refactored Java code.

            8. Only identify meaningful refactoring opportunities.
               Do not focus on security or performance issues.

            Java code:
            {{code}}
            """)
    @Agent
    RefactoringSuggestions suggestRefactorings(
            @V("code") String code);

SecurityExpert.java

 

public interface SecurityExpert {

    @UserMessage("""
            You are an expert application security reviewer.

            Review the following Java code specifically for security vulnerabilities.

            Look for:
            - Injection vulnerabilities
            - Improper input validation
            - Sensitive information exposure
            - Authentication or authorization issues
            - Insecure handling of data
            - Other common security problems

            Provide a concise list of findings.
            Do not review general code quality or performance.

            Java code:
            {{code}}
            """)
    @Agent
    List<String> reviewSecurity(@V("code") String code);
}

Agents for the above interfaces are defined like below.

CodeQualityExpert codeQualityExpert = AgenticServices
        .agentBuilder(CodeQualityExpert.class)
        .chatModel(chatModel)
        .outputKey("codeQualityComments")
        .build();

SecurityExpert securityExpert = AgenticServices
        .agentBuilder(SecurityExpert.class)
        .chatModel(chatModel)
        .outputKey("codeSecurityComments")
        .build();

PerformanceExpert performanceExpert = AgenticServices
        .agentBuilder(PerformanceExpert.class)
        .chatModel(chatModel)
        .outputKey("codePerformanceComments")
        .build();

RefactoringExpert refactoringExpert = AgenticServices
        .agentBuilder(RefactoringExpert.class)
        .chatModel(chatModel)
        .outputKey("refactoringSuggestions")
        .build();

   

The Orchestrator

The interesting part is the CodeReviewExpert. It acts as the orchestrator rather than performing the actual review itself.

 

The orchestrator coordinates the work, specialized agents perform the work.


CodeQualityExpert codeQualityExpert = AgenticServices
        .agentBuilder(CodeQualityExpert.class)
        .chatModel(chatModel)
        .outputKey("codeQualityComments")
        .build();

SecurityExpert securityExpert = AgenticServices
        .agentBuilder(SecurityExpert.class)
        .chatModel(chatModel)
        .outputKey("codeSecurityComments")
        .build();

PerformanceExpert performanceExpert = AgenticServices
        .agentBuilder(PerformanceExpert.class)
        .chatModel(chatModel)
        .outputKey("codePerformanceComments")
        .build();

RefactoringExpert refactoringExpert = AgenticServices
        .agentBuilder(RefactoringExpert.class)
        .chatModel(chatModel)
        .outputKey("refactoringSuggestions")
        .build();

Building the Parallel Workflow

The workflow is created using AgenticServices like below.

CodeReviewExpert codeReviewExpert = AgenticServices
        .parallelBuilder(CodeReviewExpert.class)
        .subAgents(
                codeQualityExpert,
                securityExpert,
                performanceExpert,
                refactoringExpert
        )
        .executor(Executors.newFixedThreadPool(4))
        .outputKey("plans")
        .output(agenticScope -> {

            List<String> codeQualityComments =
                    agenticScope.readState("codeQualityComments", List.of());

            List<String> codeSecurityComments =
                    agenticScope.readState("codeSecurityComments", List.of());

            List<String> codePerformanceComments =
                    agenticScope.readState("codePerformanceComments", List.of());

            RefactoringSuggestions refactoringState =
                    agenticScope.readState("refactoringSuggestions", null);

            List<RefactoringSuggestion> refactoringSuggestions =
                    refactoringState != null
                            && refactoringState.getSuggestions() != null
                            ? refactoringState.getSuggestions()
                            : List.of();

            CodeReviewComments codeReviewComments = new CodeReviewComments();

            codeReviewComments.setCodePerformanceComments(codePerformanceComments);
            codeReviewComments.setCodeQualityComments(codeQualityComments);
            codeReviewComments.setCodeSecurityComments(codeSecurityComments);
            codeReviewComments.setRefactoringSuggestions(refactoringSuggestions);

            return codeReviewComments;
        })
        .build();

  

The important part here is:

 

.subAgents(
    codeQualityExpert,
    securityExpert,
    performanceExpert,
    refactoringExpert
)

  

This tells the workflow that these four agents are the specialized workers.

 

.executor(Executors.newFixedThreadPool(4))

Above statement provides four execution threads so the four independent tasks can execute concurrently.

 

How do we combine the results?

Each specialist produces its own result.

 

For example:

  • codeQualityComments
  • codeSecurityComments
  • codePerformanceComments
  • refactoringSuggestions

 

The workflow then reads these results from the agenticScope:

List<String> codeQualityComments =
    agenticScope.readState(
        "codeQualityComments",
        List.of()
    );

List<String> codeSecurityComments =
    agenticScope.readState(
        "codeSecurityComments",
        List.of()
    );

List<String> codePerformanceComments =
    agenticScope.readState(
        "codePerformanceComments",
        List.of()
    );

RefactoringSuggestions refactoringState =
    agenticScope.readState(
        "refactoringSuggestions",
        null
    );

   

Finally, these individual outputs are combined into a single object:

 

CodeReviewComments codeReviewComments = new CodeReviewComments();
codeReviewComments.setCodePerformanceComments(codePerformanceComments);
codeReviewComments.setCodeQualityComments(codeQualityComments);
codeReviewComments.setCodeSecurityComments(codeSecurityComments);
codeReviewComments.setRefactoringSuggestions(refactoringSuggestions);

The final CodeReviewComments therefore represents the combined result of the entire parallel workflow.

 

Follow below step-by-step procedure to build the complete working Application.

 

Step 1: Create new maven project parallel-code-reviewer.

 

Update pom.xml with maven dependencies.

 

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <groupId>com.sample.app</groupId>
    <artifactId>parallel-code-reviewer</artifactId>
    <version>1.0.0</version>

    <name>Sequential Handoff Pattern Demo</name>
    <description>
        Simple Java console application demonstrating a deterministic
        sequential handoff workflow with LangChain4j and Ollama.
    </description>

    <properties>

        <!-- Java -->
        <java.version>21</java.version>
        <maven.compiler.release>${java.version}</maven.compiler.release>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

        <!-- LangChain4j -->
        <langchain4j.version>1.18.1</langchain4j.version>
        <langchain4j.agentic.version>1.18.1-beta28</langchain4j.agentic.version>

        <!-- Logging -->
        <slf4j.version>2.0.17</slf4j.version>

        <!-- Console -->
        <jline.version>3.30.6</jline.version>

        <!-- Application -->
        <main.class>com.sample.app.App</main.class>

        <!-- Maven Plugins -->
        <maven.compiler.plugin.version>3.14.1</maven.compiler.plugin.version>
        <maven.surefire.plugin.version>3.5.4</maven.surefire.plugin.version>
        <maven.shade.plugin.version>3.6.1</maven.shade.plugin.version>
        <spotless.maven.plugin.version>3.4.0</spotless.maven.plugin.version>

    </properties>

    <dependencies>

        <!-- LangChain4j Core -->
        <dependency>
            <groupId>dev.langchain4j</groupId>
            <artifactId>langchain4j-core</artifactId>
            <version>${langchain4j.version}</version>
        </dependency>

        <!-- LangChain4j Ollama Integration -->
        <dependency>
            <groupId>dev.langchain4j</groupId>
            <artifactId>langchain4j-ollama</artifactId>
            <version>${langchain4j.version}</version>
        </dependency>

        <!-- LangChain4j Agentic -->
        <dependency>
            <groupId>dev.langchain4j</groupId>
            <artifactId>langchain4j-agentic</artifactId>
            <version>${langchain4j.agentic.version}</version>
        </dependency>

        <!-- SLF4J -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-nop</artifactId>
            <version>${slf4j.version}</version>
        </dependency>

        <!-- JLine -->
        <dependency>
            <groupId>org.jline</groupId>
            <artifactId>jline</artifactId>
            <version>${jline.version}</version>
        </dependency>

    </dependencies>

    <build>

        <plugins>

            <!-- Java Compiler -->

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>${maven.compiler.plugin.version}</version>
                <configuration>
                    <release>${maven.compiler.release}</release>
                </configuration>
            </plugin>

            <!-- Unit Tests -->

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>${maven.surefire.plugin.version}</version>
            </plugin>

            <!-- Build Executable JAR -->

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>${maven.shade.plugin.version}</version>

                <executions>
                    <execution>
                        <phase>package</phase>

                        <goals>
                            <goal>shade</goal>
                        </goals>

                        <configuration>
                            <createDependencyReducedPom>false</createDependencyReducedPom>

                            <transformers>
                                <transformer
                                    implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                    <mainClass>${main.class}</mainClass>
                                </transformer>
                            </transformers>
                        </configuration>

                    </execution>
                </executions>

            </plugin>

            <!-- Code Formatting -->

            <plugin>
                <groupId>com.diffplug.spotless</groupId>
                <artifactId>spotless-maven-plugin</artifactId>
                <version>${spotless.maven.plugin.version}</version>

                <configuration>
                    <java>

                        <!-- Apply Google Java Format -->
                        <googleJavaFormat />

                        <!-- General formatting and cleanup -->
                        <trimTrailingWhitespace />
                        <endWithNewline />
                        <removeUnusedImports />

                    </java>
                </configuration>

                <executions>
                    <execution>
                        <id>spotless-check</id>
                        <goals>
                            <goal>check</goal>
                        </goals>
                        <phase>verify</phase>
                    </execution>
                </executions>

            </plugin>

        </plugins>

    </build>

</project>

   

Step 2: Define chat model configuration class.

To demo the application, I am using codellama:7b model.

 

OllamaConfig.java

 

package com.sample.app.config;

import dev.langchain4j.model.chat.ChatModel;
import dev.langchain4j.model.chat.request.ResponseFormat;
import dev.langchain4j.model.ollama.OllamaChatModel;

public final class OllamaConfig {

  public static final String DEFAULT_BASE_URL = "http://localhost:11434";
  public static final String DEFAULT_MODEL_NAME = "codellama:7b";

  private OllamaConfig() {}

  public static ChatModel createChatModel() {
    String baseUrl = resolveBaseUrl();
    String modelName = resolveModelName();

    return OllamaChatModel.builder().baseUrl(baseUrl).modelName(modelName).temperature(0.2).build();
  }

  public static ChatModel createStructuredChatModel() {
    String baseUrl = resolveBaseUrl();
    String modelName = resolveModelName();

    return OllamaChatModel.builder()
        .baseUrl(baseUrl)
        .modelName(modelName)
        .temperature(0.2)
        .responseFormat(ResponseFormat.JSON)
        .build();
  }

  public static String resolveBaseUrl() {
    return readSetting("OLLAMA_BASE_URL", DEFAULT_BASE_URL);
  }

  public static String resolveModelName() {
    return readSetting("OLLAMA_MODEL", DEFAULT_MODEL_NAME);
  }

  private static String readSetting(String key, String defaultValue) {
    String systemValue = System.getProperty(key);
    if (systemValue != null && !systemValue.trim().isEmpty()) {
      return systemValue.trim();
    }

    String environmentValue = System.getenv(key);
    if (environmentValue != null && !environmentValue.trim().isEmpty()) {
      return environmentValue.trim();
    }

    return defaultValue;
  }
}

Step 3: Define model classes.

 

RefactoringSuggestion.java

 

package com.sample.app.model;

import dev.langchain4j.model.output.structured.Description;

public class RefactoringSuggestion {

  @Description(
      """
      A short, specific description of the code issue that should be
      addressed through refactoring. For example: "Method has too many
      responsibilities" or "Duplicate validation logic".
      """)
  private String issue;

  @Description(
      """
      A clear explanation of why the code should be refactored and what
      design, readability, maintainability, or simplicity problem it
      causes. Do not describe security or performance issues.
      """)
  private String explanation;

  @Description(
      """
      The exact relevant portion of the original Java source code that
      contains the identified refactoring opportunity. Preserve the
      original code without modifications.
      """)
  private String originalSnippet;

  @Description(
      """
      The improved version of the originalSnippet after applying the
      proposed refactoring. The code must be valid Java and should
      address the issue identified above while preserving the original
      behavior as much as possible.
      """)
  private String refactoredSnippet;

  public String getIssue() {
    return issue;
  }

  public void setIssue(String issue) {
    this.issue = issue;
  }

  public String getExplanation() {
    return explanation;
  }

  public void setExplanation(String explanation) {
    this.explanation = explanation;
  }

  public String getOriginalSnippet() {
    return originalSnippet;
  }

  public void setOriginalSnippet(String originalSnippet) {
    this.originalSnippet = originalSnippet;
  }

  public String getRefactoredSnippet() {
    return refactoredSnippet;
  }

  public void setRefactoredSnippet(String refactoredSnippet) {
    this.refactoredSnippet = refactoredSnippet;
  }
}

   

RefactoringSuggestions.java

 

package com.sample.app.model;

import java.util.List;

public class RefactoringSuggestions {
  private List<RefactoringSuggestion> suggestions;

  public List<RefactoringSuggestion> getSuggestions() {
    return suggestions;
  }

  public void setSuggestions(List<RefactoringSuggestion> suggestions) {
    this.suggestions = suggestions;
  }
}

CodeReviewComments.java

package com.sample.app.model;

import java.util.List;

public class CodeReviewComments {
  private List<String> codeQualityComments;
  private List<String> codeSecurityComments;
  private List<String> codePerformanceComments;
  private List<RefactoringSuggestion> refactoringSuggestions;

  public List<String> getCodeQualityComments() {
    return codeQualityComments;
  }

  public void setCodeQualityComments(List<String> codeQualityComments) {
    this.codeQualityComments = codeQualityComments;
  }

  public List<String> getCodeSecurityComments() {
    return codeSecurityComments;
  }

  public void setCodeSecurityComments(List<String> codeSecurityComments) {
    this.codeSecurityComments = codeSecurityComments;
  }

  public List<String> getCodePerformanceComments() {
    return codePerformanceComments;
  }

  public void setCodePerformanceComments(List<String> codePerformanceComments) {
    this.codePerformanceComments = codePerformanceComments;
  }

  public List<RefactoringSuggestion> getRefactoringSuggestions() {
    return refactoringSuggestions;
  }

  public void setRefactoringSuggestions(List<RefactoringSuggestion> refactoringSuggestions) {
    this.refactoringSuggestions = refactoringSuggestions;
  }

  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder();

    sb.append("Code Review Comments\n");
    sb.append("====================\n");

    appendComments(sb, "Code Quality", codeQualityComments);
    appendComments(sb, "Code Security", codeSecurityComments);
    appendComments(sb, "Code Performance", codePerformanceComments);

    sb.append("\nRefactoring Suggestions:\n");
    sb.append("------------------------\n");

    if (refactoringSuggestions == null || refactoringSuggestions.isEmpty()) {
      sb.append("  No refactoring suggestions\n");
    } else {
      for (int i = 0; i < refactoringSuggestions.size(); i++) {
        RefactoringSuggestion suggestion = refactoringSuggestions.get(i);

        sb.append("\n  Suggestion ").append(i + 1).append(":\n");
        sb.append("    Issue:\n");
        sb.append("      ").append(suggestion.getIssue()).append("\n");

        sb.append("    Explanation:\n");
        sb.append("      ").append(suggestion.getExplanation()).append("\n");

        sb.append("    Original Code:\n");
        appendCode(sb, suggestion.getOriginalSnippet());

        sb.append("    Refactored Code:\n");
        appendCode(sb, suggestion.getRefactoredSnippet());
      }
    }

    return sb.toString();
  }

  private void appendComments(StringBuilder sb, String section, List<String> comments) {

    sb.append("\n").append(section).append(":\n");
    sb.append("-".repeat(section.length() + 1)).append("\n");

    if (comments == null || comments.isEmpty()) {
      sb.append("  No comments\n");
      return;
    }

    for (int i = 0; i < comments.size(); i++) {
      sb.append("  ").append(i + 1).append(". ").append(comments.get(i)).append("\n");
    }
  }

  private void appendCode(StringBuilder sb, String code) {
    if (code == null || code.isBlank()) {
      sb.append("      No code provided\n");
      return;
    }

    String[] lines = code.split("\\R");

    for (String line : lines) {
      sb.append("      ").append(line).append("\n");
    }
  }
}

   

Step 4: Define Agent interfaces.

 

CodeQualityExpert.java

 

package com.sample.app.agents;

import dev.langchain4j.agentic.Agent;
import dev.langchain4j.service.UserMessage;
import dev.langchain4j.service.V;
import java.util.List;

public interface CodeQualityExpert {

  @UserMessage(
      """
            You are an expert Java code reviewer.

            Review the following Java code specifically for code quality.

            Look for:
            - Clean code violations
            - Poor naming
            - Code duplication
            - Maintainability issues
            - SOLID principle violations
            - Unnecessary complexity

            Provide a concise list of findings.
            Do not review security or performance.

            Java code:
            {{code}}
            """)
  @Agent
  List<String> reviewCodeQuality(@V("code") String code);
}

   

PerformanceExpert.java

 

package com.sample.app.agents;

import dev.langchain4j.agentic.Agent;
import dev.langchain4j.service.UserMessage;
import dev.langchain4j.service.V;
import java.util.List;

public interface PerformanceExpert {

  @UserMessage(
      """
      You are an expert Java performance reviewer.

      Review the following Java code specifically for performance issues.

      Look for:
      - Inefficient algorithms
      - Unnecessary loops
      - Excessive object creation
      - Inefficient collection usage
      - Unnecessary database or network calls
      - Potential memory issues
      - Other performance bottlenecks

      Provide a concise list of findings.
      Do not review security or general code quality.

      Java code:
      {{code}}
      """)
  @Agent
  List<String> reviewPerformance(@V("code") String code);
}

   

RefactoringExpert.java

 

package com.sample.app.agents;

import com.sample.app.model.RefactoringSuggestions;
import dev.langchain4j.agentic.Agent;
import dev.langchain4j.service.UserMessage;
import dev.langchain4j.service.V;

public interface RefactoringExpert {

  @UserMessage(
      """
            You are an expert Java refactoring specialist.

            Analyze the following Java code and identify practical refactoring
            opportunities that improve readability, maintainability, design,
            and simplicity.

            Return a JSON object with one field:
            - suggestions: array of refactoring suggestion objects

            Each suggestion object must contain:
            - issue
            - explanation
            - originalSnippet
            - refactoredSnippet

            IMPORTANT RULES:

            1. originalSnippet must contain the exact relevant code from the
               provided source code.

            2. refactoredSnippet must ALWAYS contain the complete replacement
               Java code after applying the suggested refactoring.

            3. Never return an empty, null, or "No code provided"
               refactoredSnippet.

            4. If the recommended refactoring is to remove unused or dead code,
               refactoredSnippet must contain the complete surrounding code
               after removing that code, rather than being empty.

            5. The refactoredSnippet must be valid Java code.

            6. Preserve the original behavior unless the refactoring itself
               requires a behavior-preserving structural change.

            7. Do not provide only a description of the changes. Always provide
               the actual refactored Java code.

            8. Only identify meaningful refactoring opportunities.
               Do not focus on security or performance issues.

            Java code:
            {{code}}
            """)
  @Agent
  RefactoringSuggestions suggestRefactorings(@V("code") String code);
}

SecurityExpert.java

package com.sample.app.agents;

import dev.langchain4j.agentic.Agent;
import dev.langchain4j.service.UserMessage;
import dev.langchain4j.service.V;
import java.util.List;

public interface SecurityExpert {

  @UserMessage(
      """
            You are an expert application security reviewer.

            Review the following Java code specifically for security vulnerabilities.

            Look for:
            - Injection vulnerabilities
            - Improper input validation
            - Sensitive information exposure
            - Authentication or authorization issues
            - Insecure handling of data
            - Other common security problems

            Provide a concise list of findings.
            Do not review general code quality or performance.

            Java code:
            {{code}}
            """)
  @Agent
  List<String> reviewSecurity(@V("code") String code);
}

   

CodeReviewExpert.java

 

package com.sample.app.agents;

import com.sample.app.model.CodeReviewComments;
import dev.langchain4j.agentic.Agent;
import dev.langchain4j.service.UserMessage;
import dev.langchain4j.service.V;

public interface CodeReviewExpert {

  @UserMessage(
      """
            You are an expert code review orchestrator.

            Your task is to perform a comprehensive review of the provided
            Java source code.

            The review is performed by multiple specialized agents working
            independently in parallel:

            1. Code Quality Expert
               Reviews clean code, naming, duplication, maintainability,
               SOLID principles, and unnecessary complexity.

            2. Security Expert
               Reviews security vulnerabilities, input validation,
               injection risks, sensitive information exposure,
               authentication, authorization, and insecure data handling.

            3. Performance Expert
               Reviews inefficient algorithms, unnecessary loops,
               excessive object creation, inefficient collection usage,
               unnecessary database or network calls, and memory issues.

            4. Refactoring Expert
               Identifies meaningful refactoring opportunities and provides
               the original code snippet along with the complete refactored
               code.

            Each specialist independently analyzes the same Java source code.
            Their results are combined into a single CodeReviewComments result.

            Do not perform the detailed review yourself.
            Delegate the review responsibilities to the appropriate
            specialized agents.

            Java code to review:
            {{code}}
            """)
  @Agent
  CodeReviewComments reviewCode(@V("code") String code);
}

   

Step 5: Define Workflow listener.

 

AgentWorkflowListener.java

 

package com.sample.app.agents;

import dev.langchain4j.agentic.observability.AgentListener;
import dev.langchain4j.agentic.observability.AgentRequest;
import dev.langchain4j.agentic.observability.AgentResponse;
import dev.langchain4j.agentic.scope.AgenticScope;
import java.util.Map;

public class AgentWorkflowListener implements AgentListener {

  @Override
  public void beforeAgentInvocation(AgentRequest request) {
    if (!request.agent().leaf()) {
      return;
    }

    printInitialStateIfNeeded(request);

    System.out.println(request.agent().outputKey());
  }

  @Override
  public void afterAgentInvocation(AgentResponse response) {
    if (!response.agent().leaf()) {
      return;
    }

    String outputKey = response.agent().outputKey();
    AgenticScope scope = response.agenticScope();

    // Store the agent output in the shared workflow state.
    scope.writeState(outputKey, response.output());

    // Render the agent output.
    System.out.println(outputKey + "\n\n" + response.output());

    // Show the state update.
    System.out.println("State updated: " + outputKey);

    System.out.println("  " + outputKey + " = " + scope.readState(outputKey, null));
    System.out.println();
    printState(scope);
  }

  @Override
  public boolean inheritedBySubagents() {
    return true;
  }

  private void printInitialStateIfNeeded(AgentRequest request) {
    AgenticScope scope = request.agenticScope();

    if (scope.executionContext("initialStatePrinted") != null) {
      return;
    }

    /*
     * The workflow starts with storyIdea as the initial state. Store it in the
     * shared AgenticScope so that subsequent agents can build on the state produced
     * by previous agents.
     */
    if (!scope.hasState("storyIdea") && request.inputs().containsKey("storyIdea")) {

      scope.writeState("storyIdea", request.inputs().get("storyIdea"));
    }

    scope.writeExecutionContext("initialStatePrinted", Boolean.TRUE);

    printState(scope);

    System.out.println();
  }

  private void printState(AgenticScope scope) {
    System.out.println("workflow state");
    System.out.println("-".repeat(100));

    Map<String, Object> stateObj = scope.state();

    for (String key : stateObj.keySet()) {
      Object value = stateObj.get(key);

      if (value != null) {
        String valueStr = value.toString();
        if (valueStr.length() > 100) {
          valueStr = valueStr.substring(0, 100) + "...";
        }
        System.out.println(key + " -> " + valueStr);
      } else {
        System.out.println(key + " -> null");
      }
    }

    System.out.println("-".repeat(100));
  }
}

   

Step 6: Define main application class.

 

App.java

 

package com.sample.app;

import com.sample.app.agents.AgentWorkflowListener;
import com.sample.app.agents.CodeQualityExpert;
import com.sample.app.agents.CodeReviewExpert;
import com.sample.app.agents.PerformanceExpert;
import com.sample.app.agents.RefactoringExpert;
import com.sample.app.agents.SecurityExpert;
import com.sample.app.config.OllamaConfig;
import com.sample.app.model.CodeReviewComments;
import com.sample.app.model.RefactoringSuggestion;
import com.sample.app.model.RefactoringSuggestions;
import dev.langchain4j.agentic.AgenticServices;
import dev.langchain4j.model.chat.ChatModel;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.Executors;

public class App {

  public static String readFileToString(String codeFilePath) throws IOException {
    if (codeFilePath == null || codeFilePath.isEmpty()) {
      System.out.println("Code File path should not be empty");
      System.exit(1);
    }

    return Files.readString(Path.of(codeFilePath));
  }

  public static void main(String[] args) throws IOException {
    System.out.println("Enter the code file path to review the code");

    String codeToReview = null;

    try (Scanner scanner = new Scanner(System.in)) {
      String codeFilePath = scanner.nextLine().trim();
      codeToReview = readFileToString(codeFilePath);
    }

    ChatModel chatModel = OllamaConfig.createChatModel();

    // Define Agents
    CodeQualityExpert codeQualityExpert =
        AgenticServices.agentBuilder(CodeQualityExpert.class)
            .chatModel(chatModel)
            .outputKey("codeQualityComments")
            .build();

    SecurityExpert securityExpert =
        AgenticServices.agentBuilder(SecurityExpert.class)
            .chatModel(chatModel)
            .outputKey("codeSecurityComments")
            .build();

    PerformanceExpert performanceExpert =
        AgenticServices.agentBuilder(PerformanceExpert.class)
            .chatModel(chatModel)
            .outputKey("codePerformanceComments")
            .build();

    RefactoringExpert refactoringExpert =
        AgenticServices.agentBuilder(RefactoringExpert.class)
            .chatModel(chatModel)
            .outputKey("refactoringSuggestions")
            .build();

    CodeReviewExpert codeReviewExpert =
        AgenticServices.parallelBuilder(CodeReviewExpert.class)
            .subAgents(codeQualityExpert, securityExpert, performanceExpert, refactoringExpert)
            .listener(new AgentWorkflowListener())
            .executor(Executors.newFixedThreadPool(4))
            .outputKey("plans")
            .output(
                agenticScope -> {
                  List<String> codeQualityComments =
                      agenticScope.readState("codeQualityComments", List.of());
                  List<String> codeSecurityComments =
                      agenticScope.readState("codeSecurityComments", List.of());
                  List<String> codePerformanceComments =
                      agenticScope.readState("codePerformanceComments", List.of());
                  RefactoringSuggestions refactoringState =
                      agenticScope.readState("refactoringSuggestions", null);
                  List<RefactoringSuggestion> refactoringSuggestions =
                      refactoringState != null && refactoringState.getSuggestions() != null
                          ? refactoringState.getSuggestions()
                          : List.of();

                  CodeReviewComments codeReviewComments = new CodeReviewComments();
                  codeReviewComments.setCodePerformanceComments(codePerformanceComments);
                  codeReviewComments.setCodeQualityComments(codeQualityComments);
                  codeReviewComments.setCodeSecurityComments(codeSecurityComments);
                  codeReviewComments.setRefactoringSuggestions(refactoringSuggestions);

                  return codeReviewComments;
                })
            .build();

    CodeReviewComments codeReviewComments = codeReviewExpert.reviewCode(codeToReview);

    System.out.println(codeReviewComments);
    System.exit(0);
  }
}

   

Build the application using Maven:

mvn clean package

 

Run the Application

Execute following command to run the application.

 

java -jar ./target/parallel-code-reviewer-1.0.0.jar

 

$java -jar ./target/parallel-code-reviewer-1.0.0.jar 
Enter the code file path to review the code

 

Enter the full absolute path of the file to get review comments.

 

You can download the Application from this link.

 

 

 

Previous                                                    Next                                                    Home