Hi guys revising for an exam and im fine with the theory stuff but heres one question:

A large ornamental garden is open to the members of the public who can enter through two gates: east gate or the west gate. The management wants to determine how many people there are in the garden at any time. Write a program to implement the population count that contains two concurrent threads (each controlling a single gate). The gardens is open 1 hour a day. You can assume during this time no one was allowed to leave. 18marks

This is a closed book exam! So for this I would write two threads east and west. Start them in the main method. Incrementing a counter instance variable, within the run methods of the thread class.

Please correct anything you guys think above. How would you guys prevent the threads interfereing with each other? and how does the 1 hour get into it?

Thanks guys

Dani AI

Generated

Good direction, — modelling each gate as its own thread is the right approach. was also pointing at the key issue: protect the shared count so two threads cannot lose updates or read a stale value.

A simple, robust solution uses an atomic counter and a shared stop flag. The counter keeps increments atomic and visible; the flag lets both gate threads terminate cleanly after the one-hour window. Example (trimmed) simulation:

import java.util.concurrent.*;
import java.util.concurrent.atomic.*;

class Gate implements Runnable {
  private final AtomicInteger count;
  private final AtomicBoolean open;
  Gate(AtomicInteger count, AtomicBoolean open){ this.count = count; this.open = open; }
  public void run(){
    while (open.get()){
      count.incrementAndGet();
      try { Thread.sleep(ThreadLocalRandom.current().nextInt(5,20)); } 
      catch (InterruptedException e){ Thread.currentThread().interrupt(); break; }
    }
  }
}

public class Garden {
  public static void main(String[] args) throws Exception {
    AtomicInteger total = new AtomicInteger();
    AtomicBoolean open = new AtomicBoolean(true);
    Thread east = new Thread(new Gate(total, open), "East");
    Thread west = new Thread(new Gate(total, open), "West");
    east.start(); west.start();

    ScheduledExecutorService s = Executors.newSingleThreadScheduledExecutor();
    s.schedule(() -> open.set(false), 1, TimeUnit.HOURS);
    s.shutdown();

    east.join(); west.join();
    System.out.println("People inside: " + total.get());
  }
}

Notes and alternatives:

  • Use AtomicInteger (or LongAdder for very high update rates) so you avoid explicit locking overhead. See AtomicInteger and LongAdder.
  • Use a scheduler or record start time and stop after one hour; for testing use a shorter interval.
  • Never use Thread.stop() — use a volatile/atomic flag or interrupts and join() to wait for termination.
  • If inputs come from hardware/sensors, queue events and have a single consumer update the counter to avoid missed events.

For exam answers, state the concurrency hazard (lost update/visibility), show a thread-safe implementation, and explain how you enforce the one-hour window and graceful shutdown.

Recommended Answers

All 3 Replies

synchronise on the counter

Yeah i guess i was thinking it would be something more complex than that but you're right. What about the 1 hour stipulation?

doesn't matter. Just introduce a switch somewhere that opens or closes a gate :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.