LOW-LEVEL DESIGN · MODELING AND UML · UML · 20 OF 48

UML Activity Diagrams: Decisions, Fork, Join and Swimlanes

How to read and draw UML activity diagrams: start and end nodes, actions, decisions and merges with guards, fork and join for parallel work, swimlanes and a little object flow, shown on a job application workflow, with Java that codes the decisions as ifs and the fork and join with CompletableFuture, plus when to pick it over a sequence or state diagram.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
1 / 18

Press play to hear the narration, or step through at your own pace. The Java example is below.

Java example

One file, Java 17, 136 lines, with a small main() demo. Save it as HiringActivityDemo.java, then run javac HiringActivityDemo.java && java HiringActivityDemo.

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * The job application activity diagram as a small workflow.
 * Actions are methods, decisions are ifs, the fork and join use CompletableFuture.
 */
public class HiringActivityDemo {

    record Application(String id, int yearsExperience, boolean cleanRecord, int interviewScore) { }

    /** Object flow: each parallel branch produces one of these. */
    record CheckResult(String lane, String name, boolean passed, int days) { }

    // ---- The problem: the checks run one after another. ----
    static final class SequentialHiring {
        int daysToDecide() {
            int backgroundDays = 3;
            int interviewDays = 2;
            return backgroundDays + interviewDays;          // waits for the sum
        }
    }

    // ---- The clean version: the activity diagram, step by step. ----
    static final class HiringWorkflow {
        private final ExecutorService pool;
        private final List<String> log = new ArrayList<>();

        HiringWorkflow(ExecutorService pool) {
            this.pool = pool;
        }

        String run(Application app) {
            log.clear();
            submit(app);                                    // action (Candidate lane)
            if (!screen(app)) {                             // decision: [meets basics] / [else]
                return finish(reject(app, "does not meet the basics"));
            }
            List<CheckResult> results = forkAndJoin(app);   // fork ... join
            int days = 0;
            for (CheckResult r : results) {
                lane(r.lane(), r.name() + (r.passed() ? " passed" : " failed") + " in " + r.days() + " days");
                days = Math.max(days, r.days());            // parallel: the longest branch
            }
            lane("System", "both checks done after " + days + " days");
            boolean allPassed = results.stream().allMatch(CheckResult::passed);
            String outcome = allPassed                      // decision: [all passed] / [else]
                    ? offer(app)
                    : reject(app, "a check failed");
            return finish(outcome);                         // merge, then the final node
        }

        private List<CheckResult> forkAndJoin(Application app) {
            // fork: both flows start now, on the pool
            CompletableFuture<CheckResult> bg =
                    CompletableFuture.supplyAsync(() -> backgroundCheck(app), pool);
            CompletableFuture<CheckResult> iv =
                    CompletableFuture.supplyAsync(() -> techInterview(app), pool);
            // join bar: wait until every flow has arrived
            CompletableFuture.allOf(bg, iv).join();
            // read results in a fixed order so the output never depends on timing
            return List.of(bg.join(), iv.join());
        }

        private void submit(Application app) {
            lane("Candidate", "submit application " + app.id());
        }

        private boolean screen(Application app) {
            boolean ok = app.yearsExperience() >= 2;
            String verdict = ok ? "meets basics" : "too junior";
            lane("Recruiter", "screen CV: " + app.yearsExperience() + " years, " + verdict);
            return ok;
        }

        /** Runs on a pool thread, so it does not print; it returns its result instead. */
        private CheckResult backgroundCheck(Application app) {
            pause();
            return new CheckResult("Vendor", "background check", app.cleanRecord(), 3);
        }

        private CheckResult techInterview(Application app) {
            pause();
            return new CheckResult("Hiring team", "tech interview (score " + app.interviewScore() + ")",
                    app.interviewScore() >= 6, 2);
        }

        private String offer(Application app) {
            lane("Recruiter", "send offer letter to " + app.id());
            return "OFFER";
        }

        private String reject(Application app, String reason) {
            lane("Recruiter", "send rejection to " + app.id() + ": " + reason);
            return "REJECTED";
        }

        private String finish(String outcome) {
            lane("System", "close application, outcome " + outcome);
            log.forEach(System.out::println);
            return outcome;
        }

        private void lane(String who, String what) {
            log.add(String.format("  %-12s| %s", who, what));
        }

        private static void pause() {
            try {
                Thread.sleep(50);                            // stands in for days of real work
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    }

    public static void main(String[] args) {
        System.out.println("Sequential version needs " + new SequentialHiring().daysToDecide() + " days");

        ExecutorService pool = Executors.newFixedThreadPool(2);
        try {
            HiringWorkflow workflow = new HiringWorkflow(pool);

            System.out.println("Path 1: strong candidate");
            System.out.println("=> " + workflow.run(new Application("J-41", 5, true, 8)));

            System.out.println("Path 2: weak interview");
            System.out.println("=> " + workflow.run(new Application("J-42", 3, true, 4)));
        } finally {
            pool.shutdown();
        }
    }
}

Notes

The problem

Here is the problem. The hiring process is described in one sentence: screen the CV, then run a background check, then the tech interview, then send the offer. So the first version of the code does exactly that, one after another. The background check takes three days and the interview two, so every decision takes five days. Worse, nobody wrote down what happens when the CV fails, or when only one of the checks fails.

The hiring process, in words
  • "we screen the CV, then do a
  • background check, then the
  • tech interview, then offer"
  • questions left open:
  • must the interview wait for
  • the background check?
  • what if the CV fails?
  • what if one check fails?
  • who does each step?

The idea

The idea in one sentence: an activity diagram shows the steps of a process, the choices in it, and which steps can run at the same time. It looks like a flowchart with extra powers. A filled circle is the start, and a circle with a ring around it is the end. Rounded boxes are actions. Arrows show the flow from one action to the next. Diamonds are choices, thick bars split and join parallel work, and swimlanes show who does each step.

The pieces
  • start: filled circle
  • end: circle with a ring
  • action: rounded box
  • arrow: control flow
  • decision / merge: diamond
  • fork / join: thick bar
  • swimlane: a column per actor
  • object node: a plain box
  • one diagram = one process

Start and actions

Every activity has one start node, a small filled circle. From it, an arrow leads to the first action. An action is one step of work, drawn as a box with rounded corners, and named with a verb, like submit application or screen CV. The arrows between actions are called control flow: when one action finishes, the next one can begin. Keep each action at the same level of detail, not one huge step next to a tiny one.

Decisions and guards

A decision is a diamond with one arrow in and two or more arrows out. Each outgoing arrow carries a guard, a condition in square brackets. After screening, if the candidate meets the basics, we go on. Else, we send a rejection. Guards must cover every case, and two guards should never be true at the same time. Writing else as the last guard is a simple way to make sure nothing falls through.

Guards
  • [meets basics] go on
  • [else] reject
  • rules:
  • every case is covered
  • no two guards true at once
  • [else] is a safe last guard
  • a decision is a diamond,
  • not an action

Merge and end

Paths that split at a decision often meet again later. A merge is the same diamond shape, but with several arrows in and one arrow out. Whether we sent an offer or a rejection, the flow continues to the same end. A merge does not wait for anything, because only one of its incoming paths is ever taken. After it comes the final node, a filled circle inside a ring. When the flow reaches it, the whole activity is finished.

Fork

Now the fix for our five day problem. The background check does not need the interview, and the interview does not need the background check. So we put a fork after the first decision. A fork is a thick black bar with one arrow in and several arrows out. Unlike a decision, every outgoing flow starts, all at the same time. The vendor begins the background check while the hiring team runs the interview.

Join

A join is the matching thick bar with several arrows in and one arrow out. It waits until every incoming flow has arrived, and only then lets the flow continue. If the interview is done on day two, it waits for the background check to finish on day three. Now the decision takes three days, the longest branch, instead of five, the sum of both. After the join, a second decision asks: did everything pass?

Merge vs join

These two pairs look similar, so compare them. A decision and a merge use diamonds. Only one path runs, and the merge does not wait. A fork and a join use thick bars. All paths run, and the join waits for every one. Mixing them is a real bug. If you put a join after a decision, it waits forever for the path that was never taken. In code, that is a thread waiting for a result that will never come.

Do not mix them up
  • decision then merge (diamond)
  • only ONE path runs
  • merge does not wait
  • fork then join (thick bar)
  • ALL paths run
  • join waits for every one
  • join after a decision:
  • waits forever for a path
  • that never ran

The whole diagram

Here is the whole workflow. Start, submit the application, screen the CV. If the basics are missing, reject. Otherwise fork into the background check and the tech interview, and join when both are done. If both passed, send the offer, else send a rejection. Both paths merge and reach the end. Every case now has an ending, including the two we forgot in the first version, and the slow part runs in parallel.

Swimlanes

Swimlanes split the diagram into columns, one per actor or department. Every action sits in the lane of whoever does it. The candidate submits. The recruiter screens, and later sends the offer or the rejection. An outside vendor runs the background check, and the hiring team runs the interview. Each arrow that crosses a lane is a hand-off between people or systems, and hand-offs are where delays and lost messages usually hide.

Four lanes
  • | Candidate | Recruiter |
  • | submit | screen |
  • | | offer or |
  • | | reject |
  • | Vendor | Hiring team |
  • | bg check | interview |
  • an arrow crossing a lane
  • is a hand-off

Object flow

Sometimes it helps to show the data that moves between actions. This is called object flow. Submit application produces an application object, drawn as a plain rectangle on the arrow, and screen CV consumes it. Each check produces a check result, and send offer produces an offer letter. You can write a state in brackets, like application, screened. Use object flow lightly, only where the data is important, or the diagram gets crowded.

Objects between actions
  • [Submit] --> Application
  • --> [Screen CV]
  • [Background check]
  • --> Check result
  • [Send offer]
  • --> Offer letter
  • an object box can show its
  • state: Application [screened]

Diagram to code

The diagram turns into code almost line by line. Each action is a method call: submit, screen, offer, reject. Each decision is an if, and its guards are the condition and the else. The fork and join live in one helper that returns both check results. Both paths go through the same finish method, which is the merge, and then the method returns, which is the final node. The shape of the code matches the shape of the diagram.

Actions and decisions
String run(Application app) {
    submit(app);              // action
    if (!screen(app)) {       // decision
        return finish(reject(app));
    }
    List<CheckResult> r = forkAndJoin(app);
    boolean ok = r.stream()
        .allMatch(CheckResult::passed);
    return finish(ok ? offer(app)
                     : reject(app));
}

Fork and join in Java

Here is the fork and join in Java. Each branch starts with CompletableFuture supply async on a thread pool, so both checks run at the same time. That is the fork. Then allOf followed by join blocks until every branch has finished. That is the join bar. Finally we read the two results in a fixed order, background check first, so the output is the same on every run, no matter which branch finished first.

Fork and join
// fork: both flows start now
var bg = CompletableFuture.supplyAsync(
        () -> backgroundCheck(app), pool);
var iv = CompletableFuture.supplyAsync(
        () -> techInterview(app), pool);
// join bar: wait for every flow
CompletableFuture.allOf(bg, iv).join();
// read results in a fixed order
return List.of(bg.join(), iv.join());

Run it

The demo runs two paths. Application J forty one has five years of experience, so it passes screening and forks. The background check comes back clear after three days, and the interview scores eight out of ten after two. The join waits for both, everything passed, and an offer goes out after three days, not five. Application J forty two also passes screening, but scores four in the interview, so after the join it gets a rejection.

Which diagram when

When should you pick an activity diagram? Use it for a process with several steps, choices and parallel work, often across several people or systems, like hiring, order fulfilment or a loan approval. Use a sequence diagram when the question is which object calls which, in what order. Use a state diagram when one object moves through states, like an application going from submitted to screened to hired. They answer different questions.

Pick the right picture
  • activity diagram:
  • steps of a whole process,
  • choices, parallel work
  • sequence diagram:
  • messages between objects
  • in one scenario
  • state diagram:
  • the states of ONE object
  • and what moves it
  • one fact, one diagram

Interviews and mistakes

In interviews, an activity diagram helps most in workflow heavy problems: an order checkout, an approval chain, a vending machine purchase, or an ATM withdrawal. Watch for the classic mistakes. A join after a decision waits forever. Guards that overlap or miss a case. A process with no path for failure. Actions named after classes instead of verbs. And branches drawn in parallel that really depend on each other's results.

Watch out for
  • a join after a decision
  • (waits forever)
  • guards that overlap or miss
  • a case
  • a decision with no way out
  • for failure
  • class names as actions
  • every tiny step drawn
  • parallel branches that
  • secretly depend on each other

Interview questions

What is an activity diagram used for?

It models the flow of a process or workflow: its actions, the decisions between them, and which steps can run in parallel. It is useful for business workflows and complex methods, and swimlanes can show which actor or system does each step.

What is the difference between a decision node and a fork?

A decision is a diamond where exactly one outgoing path is taken, chosen by guard conditions. A fork is a thick bar where every outgoing path starts at the same time, which models parallel work.

What is the difference between a merge and a join?

A merge is a diamond that brings alternative paths together and continues as soon as any one arrives. A join is a thick bar that waits until all incoming parallel flows have arrived. Using a join where a merge belongs makes the flow wait forever.

What are guards in an activity diagram?

Guards are conditions written in square brackets on the arrows leaving a decision node, such as [meets basics] and [else]. They should cover every possible case and never be true at the same time.

What are swimlanes?

Swimlanes, also called partitions, divide the diagram into columns or rows, one per actor, role or system. Each action is placed in the lane of whoever performs it, so hand-offs between people or systems become visible.

When would you use an activity diagram instead of a sequence diagram?

Use an activity diagram to show the overall steps, branches and parallel parts of a process, often across several actors. Use a sequence diagram to show the exact messages between objects in one scenario, in time order.

How is an activity diagram different from a state diagram?

An activity diagram follows a process from step to step, and its nodes are actions. A state diagram follows one object, and its nodes are the states that object can be in, with events that move it between them.

How do you implement a fork and join in Java?

Start each branch asynchronously, for example with CompletableFuture.supplyAsync on an executor, then wait for all of them with CompletableFuture.allOf(...).join() before continuing. Reading each future result after that in a fixed order keeps the output deterministic.