{"id":26865703,"url":"https://github.com/tobiadeniji94/token_ring_algorithm","last_synced_at":"2025-03-31T04:22:54.407Z","repository":{"id":285306523,"uuid":"957674703","full_name":"TobiAdeniji94/token_ring_algorithm","owner":"TobiAdeniji94","description":"The Token Ring System simulates a distributed environment where multiple processes coordinate access to a critical section using a token.","archived":false,"fork":false,"pushed_at":"2025-03-30T23:54:06.000Z","size":20,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-03-31T00:21:24.650Z","etag":null,"topics":["algorithm","java","ring","token"],"latest_commit_sha":null,"homepage":"","language":"Java","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/TobiAdeniji94.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2025-03-30T23:16:09.000Z","updated_at":"2025-03-30T23:54:09.000Z","dependencies_parsed_at":"2025-03-31T00:21:29.072Z","dependency_job_id":"05a14c8b-7d6c-435a-baa7-744006e60207","html_url":"https://github.com/TobiAdeniji94/token_ring_algorithm","commit_stats":null,"previous_names":["tobiadeniji94/token_ring_algorithm"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/TobiAdeniji94%2Ftoken_ring_algorithm","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/TobiAdeniji94%2Ftoken_ring_algorithm/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/TobiAdeniji94%2Ftoken_ring_algorithm/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/TobiAdeniji94%2Ftoken_ring_algorithm/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/TobiAdeniji94","download_url":"https://codeload.github.com/TobiAdeniji94/token_ring_algorithm/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":246414147,"owners_count":20773222,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["algorithm","java","ring","token"],"created_at":"2025-03-31T04:22:53.715Z","updated_at":"2025-03-31T04:22:54.384Z","avatar_url":"https://github.com/TobiAdeniji94.png","language":"Java","readme":"# Token Ring System Documentation\n\n## Overview\n\nThe Token Ring System simulates a distributed environment where multiple processes coordinate access to a critical section using a token. It uses a Lamport clock for timestamping and handles message communication using polymorphism rather than a switch-case statement. The system also demonstrates features such as mutual exclusion, coordinator election and failure detection, fairness in request handling, and process recovery.\n\n**Note:** This implementation is based on the algorithm described in the paper *\"Token Ring Algorithm To Achieve Mutual Exclusion In Distributed System – A Centralized Approach\"* by Sandipan Basu, published in the *IJCSI International Journal of Computer Science Issues, Vol. 8, Issue 1, January 2011*\n\n## Components\n\n### 1. Message and Message Types\n\n- **`enum MessageType`**  \n  Defines the types of messages exchanged between processes:\n  - **`REQUEST`**: A process requests access to the critical section.\n  - **`GRANT`**: The coordinator grants the token to a requesting process.\n  - **`RELEASE`**: A process releases the token after exiting the critical section.\n  - **`WAIT`**: (Reserved for potential waiting functionality.)\n  - **`EXISTS`**: Used by processes to check if the coordinator is alive.\n  - **`OK`**: Acknowledgement message.\n  - **`COORDINATOR`**: Announces the new coordinator.\n  - **`UPDATE`**: (Reserved for updating ring configuration.)\n  - **`NEW`**: Used to add a new process to the ring configuration.\n\n- **`class Message`**  \n  Represents a communication message between processes. Key fields include:\n  - **`senderPid`**: The process identifier (PID) of the sender.\n  - **`type`**: The type of the message (from `MessageType`).\n  - **`timestamp`**: The Lamport clock timestamp when the message was created.\n  - **`coordinatorPid`**: For `COORDINATOR` messages, the PID of the elected coordinator.\n  - **`ringConfig`**: For `UPDATE` messages, holds the ring configuration (list of process IDs).\n\n### 2. Lamport Clock\n\n- **`class LamportClock`**  \n  Implements a logical clock using Lamport’s algorithm:\n  - **`incrementAndGet()`**: Increments the clock and returns the new time.\n  - **`get()`**: Returns the current time.\n  - **`update(int receivedTime)`**: Updates the clock based on the received timestamp, ensuring the clock always advances.\n\n### 3. Message Handlers\n\nTo avoid a central switch-case statement, the system uses polymorphism by defining a common interface and multiple concrete handler classes for different message types.\n\n- **`interface MessageHandler`**  \n  Declares a single method:\n  - **`void handle(Process process, Message msg)`**: Processes the given message using the context of the process.\n\n- **Handler Implementations:**\n  - **`RequestHandler`**:  \n    - Handles `REQUEST` messages by invoking `process.handleRequest(msg)`.\n    \n  - **`GrantHandler`**:  \n    - Handles `GRANT` messages by setting the token flag (`hasToken`) and initiating the critical section via `process.startCriticalSection()`.\n    \n  - **`ExistsHandler`**:  \n    - Handles `EXISTS` messages by calling `process.handleExists(msg)`.\n    \n  - **`ReleaseHandler`**:  \n    - Handles `RELEASE` messages by calling `process.handleRelease(msg)`.\n    \n  - **`NewHandler`**:  \n    - Handles `NEW` messages by adding a new process to the ring configuration if the process is the coordinator.\n    \n  - **`NoOpHandler`**:  \n    - A no-operation handler (used for `OK` messages).\n    \n  - **`CoordinatorHandler`**:  \n    - Handles `COORDINATOR` messages by updating the process’s coordinator information.\n\n### 4. Process Class\n\n- **`class Process implements Runnable`**  \n  Represents a node in the distributed system. Key responsibilities include:\n  - **State Variables:**\n    - `pid`: Unique identifier for the process.\n    - `coordinatorPid`: PID of the current coordinator.\n    - `clock`: Instance of `LamportClock` for managing timestamps.\n    - `requestQueue`: A priority queue that orders `REQUEST` messages by timestamp and sender PID.\n    - `ringConfig`: A list of process IDs representing the token ring.\n    - `inbox`: A blocking queue to store incoming messages.\n    - `scheduler`: Schedules tasks such as sending periodic EXISTS messages or checking coordinator status.\n    - Flags like `hasToken`, `isCoordinator`, and `inCriticalSection` manage process state.\n  - **Message Handling:**  \n    A map (`messageHandlers`) associates each `MessageType` with its corresponding `MessageHandler`. In the main `run()` loop, each incoming message is delegated to the appropriate handler.\n  - **Key Methods:**\n    - **`send(Message msg)`**: Adds a message to the process's inbox.\n    - **`sendToCoordinator(Message msg)`**: Sends a message directly to the coordinator.\n    - **`broadcast(Message msg)`**: Sends a message to all processes in the system.\n    - **`handleRequest(Message msg)`**: Adds a request to the queue and may trigger token granting.\n    - **`grantToken()`**: Grants the token to the next process in the request queue.\n    - **`handleExists(Message msg)`**: Handles EXISTS messages to confirm the coordinator is alive.\n    - **`handleRelease(Message msg)`**: Processes RELEASE messages by freeing up the token.\n    - **`becomeCoordinator()`**: Transitions the process to a coordinator role if a failure is detected.\n    - **`checkCoordinatorAlive()`**: Periodically checks the health of the current coordinator.\n    - **`startCriticalSection()`**: Simulates the execution of the critical section.\n    - **`requestCriticalSection()`**: Sends a REQUEST message to the coordinator to enter the critical section.\n\n### 5. TokenRingSystem\n\n- **`class TokenRingSystem`**  \n  Manages the overall simulation:\n  - **Static List:**\n    - `List\u003cProcess\u003e processes`: Holds all process instances.\n  - **`main(String[] args)`**:  \n    - Creates a predefined number of processes.\n    - Starts each process using an executor service.\n    - Initiates a test sequence that simulates:\n      - **Test 1: Mutual Exclusion** – Random processes request access to the critical section.\n      - **Test 2: Coordinator Failure** – The coordinator is deliberately failed to test recovery.\n      - **Test 3: Fairness** – Specific processes are forced to request the critical section.\n      - **Test 4: Process Recovery** – A previously failed process is revived and reintegrated into the ring.\n\n## How It Works\n\n1. **Initialization:**  \n   The `TokenRingSystem` initializes multiple `Process` objects, assigns one as the coordinator, and sets up the ring configuration.\n\n2. **Message Delegation:**  \n   Each process’s `run()` method continuously polls its inbox for messages. Using a handler map, the system delegates the processing of each message to its corresponding handler, which executes the relevant logic (e.g., handling requests, granting tokens, or processing coordinator updates).\n\n3. **Critical Section Access:**  \n   When a process requests access via `requestCriticalSection()`, it sends a `REQUEST` message. The coordinator, maintaining a request queue, eventually sends a `GRANT` message (if it has the token), allowing the process to enter its critical section.\n\n4. **Coordinator Failure and Recovery:**  \n   The system periodically checks if the coordinator is still alive. If the coordinator fails, another process can become the new coordinator by calling `becomeCoordinator()`. Additionally, the `NEW` message type supports the addition or recovery of processes into the ring configuration.\n\n## Usage\n\n- **Running the System:**  \n  Execute the `main()` method in the `TokenRingSystem` class. The system will start all processes and run through a sequence of tests simulating:\n  - Mutual exclusion by randomly requesting the critical section.\n  - Coordinator failure and subsequent recovery.\n  - Fairness in servicing requests.\n  - Process recovery and reintegration.\n\n- **Console Output:**  \n  The system prints detailed status messages to the console. These messages trace:\n  - Requests for critical section entry.\n  - Token grants by the coordinator.\n  - Processes entering and leaving the critical section.\n  - Coordinator failure detection and election.\n  - Process recovery events.\n\n## Acknowledgments and References\n\nThis implementation is based on the algorithm presented in:\n\n\u003e **Sandipan Basu, \"Token Ring Algorithm To Achieve Mutual Exclusion In Distributed System – A Centralized Approach.\"**  \n\u003e *IJCSI International Journal of Computer Science Issues, Vol. 8, Issue 1, January 2011.*  \n\u003e ISSN (Online): 1694-0814  \n\u003e [www.IJCSI.org](http://www.IJCSI.org)  \n\u003e  \n\u003e The paper addresses challenges in ensuring mutual exclusion in distributed systems. It proposes enhancements to the traditional token ring algorithm—special thanks to Sandipan Basu for his contributions to the field.\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftobiadeniji94%2Ftoken_ring_algorithm","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ftobiadeniji94%2Ftoken_ring_algorithm","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftobiadeniji94%2Ftoken_ring_algorithm/lists"}