Skip to content

Salmaazoz22/parallel-processing-java-fcai

Repository files navigation

Monte Carlo Estimation of π - Project 3

Course: Parallel proceesing and high computing Institution: Faculty of Computers and Artificial Intelligence, Helwan University
Academic Year: 2025-2026

Team Members

  • Salma Mohammed Abd-ElAziz
  • Ahmed Alaa Abd-ElReheem
  • Rawan Essam-ElDin Fahmy
  • Mahmoud Hossam-ElDin Mahmoud
  • Mohammed Saied Ahmed
  • Nour Hatem Mohammed
  • Yassin Yasser Zakaria

Table of Contents

  1. Project Overview
  2. Features
  3. Technical Implementation
  4. System Architecture
  5. Installation & Setup
  6. Usage Guide
  7. Experimental Results
  8. Bonus Features
  9. File Structure
  10. Technologies Used

Project Overview

This project implements a Monte Carlo simulation to estimate the value of π (pi) using both sequential and parallel approaches. The Monte Carlo method generates random points within a unit square and determines what fraction falls within an inscribed quarter circle. The ratio of points inside the circle to total points, multiplied by 4, approximates π.

Mathematical Background

The Monte Carlo method for π estimation:

  • Generate random points (x, y) where 0 ≤ x, y ≤ 1
  • Check if point lies inside quarter circle: x² + y² ≤ 1
  • Estimate: π ≈ 4 × (points inside circle) / (total points)

Features

Core Functionality

Sequential π Estimator - Single-threaded baseline implementation
Parallel π Estimator - Multi-threaded using ExecutorService and Futures
Configurable Simulations - Adjustable points, threads, and tasks
Performance Benchmarking - Compare sequential vs parallel execution
Thread Scalability Analysis - Test performance across different thread counts

Bonus Features (Implemented)

🎨 Interactive GUI Dashboard with:

  • Real-time visualization of random point generation
  • Live convergence graph showing π estimate approaching true value
  • Thread workload distribution pie chart
  • Multiple simulation modes (Visual, Batch, Comparison, Benchmark)

📊 Advanced Analysis Tools:

  • Batch experiments with averaged results
  • Sequential vs Parallel comparison with speedup calculation
  • Thread scalability benchmarking (1, 2, 4, 8, 16 threads)

Technical Implementation

Object-Oriented Design

The project follows clean OOP principles with clear separation of concerns:

Core Classes

SimulationConfig

  • Encapsulates simulation parameters
  • Stores: totalPoints, numTasks, numThreads
  • Provides getters for configuration access

PiEstimator (Interface)

  • Defines contract: double estimatePi(SimulationConfig config)
  • Enables polymorphic behavior for different estimation strategies

SequentialPiEstimator

  • Implements single-threaded Monte Carlo simulation
  • Uses java.util.Random for point generation
  • Serves as baseline for performance comparison

ParallelPiEstimator

  • Implements multi-threaded estimation using:
    • ExecutorService with fixed thread pool
    • Callable<Long> tasks for parallel computation
    • Future<Long> for result aggregation
  • Uses ThreadLocalRandom for thread-safe randomness
  • Divides workload into configurable number of tasks

PiExperimentRunner

  • Orchestrates experiments across different configurations
  • Measures execution time and estimation accuracy
  • Supports batch experiments with averaged results
  • Outputs formatted performance reports

PiDashboard (GUI)

  • Swing-based interactive dashboard
  • Real-time visualization and monitoring
  • Multiple operation modes
  • Custom panels for different visualizations

System Architecture

┌─────────────────────────────────────────────────────────┐
│                     User Interface Layer                 │
│  ┌──────────────────┐    ┌──────────────────────────┐  │
│  │  PiDashboard     │    │  PiExperimentRunner      │  │
│  │  (GUI)           │    │  (Console)               │  │
│  └──────────────────┘    └──────────────────────────┘  │
└─────────────────────────────────────────────────────────┘
                              │
┌─────────────────────────────────────────────────────────┐
│                   Business Logic Layer                   │
│  ┌──────────────────────────────────────────────────┐  │
│  │           PiEstimator (Interface)                │  │
│  │  ┌──────────────────┐  ┌────────────────────┐  │  │
│  │  │ Sequential       │  │ Parallel           │  │  │
│  │  │ PiEstimator      │  │ PiEstimator        │  │  │
│  │  └──────────────────┘  └────────────────────┘  │  │
│  └──────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────┘
                              │
┌─────────────────────────────────────────────────────────┐
│                   Configuration Layer                    │
│  ┌──────────────────────────────────────────────────┐  │
│  │           SimulationConfig                       │  │
│  │  (totalPoints, numTasks, numThreads)            │  │
│  └──────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────┘

Parallel Execution Flow

ExecutorService
     │
     ├──> Task 1 (Callable) ──> Future<Long> ──┐
     ├──> Task 2 (Callable) ──> Future<Long> ──┤
     ├──> Task 3 (Callable) ──> Future<Long> ──┤──> Aggregate
     ├──> Task 4 (Callable) ──> Future<Long> ──┤    Results
     └──> Task N (Callable) ──> Future<Long> ──┘
                                                 │
                                                 ▼
                                         Calculate π

Installation & Setup

Prerequisites

  • Java Development Kit (JDK): Version 11 or higher
  • IDE (Optional): IntelliJ IDEA, Eclipse, or VS Code with Java extensions

Compilation

# Navigate to project directory
cd monte-carlo-pi-estimation

# Compile all Java files
javac *.java

# Or compile individually
javac SimulationConfig.java
javac PiEstimator.java
javac SequentialPiEstimator.java
javac ParallelPiEstimator.java
javac PiExperimentRunner.java
javac PiDashboard.java

Usage Guide

1. Console-Based Experiments

Run comprehensive benchmarking experiments:

java PiExperimentRunner

Output Example:

Type            Threads    Points       Time(ms)     Estimate        Error          
-------------------------------------------------------------------------------------
Sequential      1          100000       45           3.14280000      0.00120734     
Sequential      1          1000000      420          3.14172800      0.00013474     
Sequential      1          10000000     4150         3.14158540      0.00000725     
-------------------------------------------------------------------------------------
Parallel        2          100000       28           3.14276000      0.00116734     
Parallel        4          100000       18           3.14164000      0.00004734     
Parallel        8          100000       15           3.14152000      0.00007265     

2. Interactive GUI Dashboard

Launch the graphical interface:

java PiDashboard

GUI Features:

Configuration Panel:

  • Total Points: Number of random points to generate
  • Threads: Number of parallel threads (1-32)
  • Batch Trials: Number of trials for batch mode

Operation Modes:

  1. Run Visual (Single)

    • Real-time visualization of point generation
    • Live convergence graph
    • Thread workload distribution
  2. Run Batch (Fast)

    • Multiple trials with averaged results
    • No visualization for faster execution
    • Statistical analysis
  3. Compare (Seq vs Par)

    • Side-by-side comparison
    • Speedup calculation
    • Detailed performance metrics
  4. Benchmark Threads

    • Test scalability across thread counts
    • Performance profile generation
    • Speedup analysis
  5. Reset Board

    • Clear all visualizations
    • Reset statistics

Visualization Panels:

  • Dots Canvas: 600×600 pixel display showing:

    • Green dots: Points inside circle
    • Red dots: Points outside circle
    • White circle: Unit circle boundary
  • Convergence Graph:

    • Blue line: Current π estimate
    • Red line: True π value (3.14159...)
    • Auto-scaling Y-axis
  • Thread Load Pie Chart:

    • Visual distribution of work across threads
    • Color-coded thread identification
    • Real-time updates

Experimental Results

Sample Performance Data

Configuration Points Threads Time (ms) π Estimate Error Speedup
Sequential 10⁶ 1 420 3.141728 0.000135 1.00x
Parallel 10⁶ 2 245 3.141652 0.000059 1.71x
Parallel 10⁶ 4 138 3.141584 0.000009 3.04x
Parallel 10⁶ 8 95 3.141598 0.000005 4.42x
Parallel 10⁶ 16 78 3.141590 0.000003 5.38x

Key Findings

  1. Accuracy: Error decreases as sample size increases (approximately proportional to 1/√N)
  2. Speedup: Near-linear speedup up to 4-8 threads, then diminishing returns due to overhead
  3. Optimal Configuration: 4-8 threads provide best balance of performance and efficiency
  4. Statistical Stability: Batch averaging significantly reduces variance in estimates

Bonus Features

1. Interactive GUI (+3 points)

  • ✅ Real-time scatter plot visualization
  • ✅ Live convergence graph
  • ✅ Thread workload distribution
  • ✅ Interactive controls and configuration
  • ✅ Multiple visualization modes

2. Extended Features (+2 points)

  • ✅ Batch experiments with averaged error
  • ✅ Sequential vs Parallel comparison tool
  • ✅ Thread scalability benchmarking
  • ✅ Comprehensive performance profiling
  • ✅ Statistical analysis tools

Total Bonus Points Earned: +5


File Structure

monte-carlo-pi-estimation/
├── README.md                      # This file
├── .gitignore                     # Git ignore patterns
├── SimulationConfig.java          # Configuration holder
├── PiEstimator.java              # Estimator interface
├── SequentialPiEstimator.java    # Sequential implementation
├── ParallelPiEstimator.java      # Parallel implementation
├── PiExperimentRunner.java       # Console experiment runner
└── PiDashboard.java              # GUI application

Technologies Used

Core Java APIs

  • java.util.concurrent: ExecutorService, Callable, Future, ThreadLocalRandom
  • java.util: Random, ArrayList, List, Collections

GUI Framework

  • javax.swing: JFrame, JPanel, JButton, JSpinner, etc.
  • java.awt: Graphics2D, BufferedImage, Color, Font
  • java.awt.geom: Arc2D for pie chart rendering

Design Patterns

  • Strategy Pattern: PiEstimator interface with multiple implementations
  • Factory Pattern: ExecutorService creation
  • Observer Pattern: GUI updates and real-time visualization
  • Singleton Pattern: Dashboard instance management

Performance Considerations

Parallel Optimization Techniques

  1. ThreadLocalRandom: Eliminates contention on shared Random instance
  2. Task Granularity: Configurable task count for load balancing
  3. Fixed Thread Pool: Avoids overhead of thread creation/destruction
  4. Atomic Operations: AtomicLong for thread-safe counters in GUI

Memory Management

  • Efficient point generation without storage
  • Bounded history in convergence graph (max 500 points)
  • Proper executor shutdown to prevent memory leaks

Lessons Learned

  1. Parallel Programming: Effective use of Java concurrency utilities
  2. Performance Analysis: Understanding speedup, efficiency, and Amdahl's Law
  3. GUI Development: Building responsive, multi-threaded user interfaces
  4. Statistical Methods: Monte Carlo simulation and error analysis
  5. Software Design: Clean architecture and separation of concerns

Future Enhancements

  • GPU acceleration using CUDA or OpenCL
  • Distributed computing across multiple machines
  • Adaptive thread pool sizing based on workload
  • Export results to CSV/JSON for external analysis
  • Web-based interface using WebSockets for real-time updates

References

  1. Monte Carlo Methods in Statistical Physics - M.E.J. Newman and G.T. Barkema
  2. Java Concurrency in Practice - Brian Goetz
  3. Introduction to Parallel Computing - Ananth Grama et al.

License

This project is submitted as part of academic coursework at FCAI Helwan University.
© 2024-2025 Team Members. All rights reserved.


Acknowledgments

Special thanks to:

  • Course Instructors: For guidance on concurrent programming concepts
  • FCAI Helwan University: For providing the learning environment
  • Java Documentation: For comprehensive API references

Contact

For questions or issues related to this project, please contact any team member through the university portal.

Project Completion Date: December 2024
Version: 1.0.0

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages