Skip to content

Commit 90ea450

Browse files
Azureyjtiluwatar
authored andcommitted
Leader Election Pattern (iluwatar#923)
* Fix issue iluwatar#761: ThreadSafeDoubleCheckLocking.java: Instantiating by Reflection call will be successful if you do that firstly * Create leader election module * Create Interface of Instance and MessageManager * Create implementations with token ring algorithm * Change package structure. Create basic message system. * Implement heartbeat and heartbeat invoking message system * Implement election message handler * Add leader message handler * Add main entry point * Add comments * Update README.md * Fix checkstyle issue * Add Unit Tests * Add Unit Tests * Add bully leader selection * Change System.out to log print. Add MIT license in each file. * Add More java doc comments * Add unit test * Add unit tests
1 parent 41b8d80 commit 90ea450

22 files changed

Lines changed: 1719 additions & 0 deletions

‎leader-election/README.md‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
---
2+
layout: pattern
3+
title: Leader Election
4+
folder: leader-election
5+
permalink: /patterns/leader-election/
6+
categories: Other
7+
tags:
8+
- Java
9+
- Difficulty-Beginner
10+
---
11+
12+
## Intent
13+
Leader Election pattern is commonly used in cloud system design. It can help to ensure that task instances selec the leader instance correctly and do not conflict with each other, cause contention for shared resources, or inadvertently interfere with the work that other task instances are performing.
14+
15+
## Applicability
16+
Use this pattern when
17+
18+
* the tasks in a distributed application, such as a cloud-hosted solution, require careful coordination and there is no natural leader.
19+
20+
Do not use this pattern when
21+
22+
* there is a natural leader or dedicated process that can always act as the leader. For example, it may be possible to implement a singleton process that coordinates the task instances. If this process fails or becomes unhealthy, the system can shut it down and restart it.
23+
* the coordination between tasks can be easily achieved by using a more lightweight mechanism. For example, if several task instances simply require coordinated access to a shared resource, a preferable solution might be to use optimistic or pessimistic locking to control access to that resource.
24+
25+
## Real world examples
26+
27+
* [Raft Leader Election](https://github.com/ronenhamias/raft-leader-election)
28+
29+
## Credits
30+
31+
* [ Cloud Design Patterns: Prescriptive Architecture Guidance for Cloud Applications](https://docs.microsoft.com/en-us/previous-versions/msp-n-p/dn568104(v=pandp.10))

‎leader-election/pom.xml‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<!--
3+
4+
The MIT License
5+
Copyright (c) 2014-2016 Ilkka Seppälä
6+
7+
Permission is hereby granted, free of charge, to any person obtaining a copy
8+
of this software and associated documentation files (the "Software"), to deal
9+
in the Software without restriction, including without limitation the rights
10+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11+
copies of the Software, and to permit persons to whom the Software is
12+
furnished to do so, subject to the following conditions:
13+
14+
The above copyright notice and this permission notice shall be included in
15+
all copies or substantial portions of the Software.
16+
17+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18+
IMPLIED, INCLUDING BUT NOT LIMITED TO THFE WARRANTIES OF MERCHANTABILITY,
19+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23+
THE SOFTWARE.
24+
25+
-->
26+
<project xmlns="http://maven.apache.org/POM/4.0.0"
27+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
28+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
29+
<modelVersion>4.0.0</modelVersion>
30+
<parent>
31+
<artifactId>java-design-patterns</artifactId>
32+
<groupId>com.iluwatar</groupId>
33+
<version>1.22.0-SNAPSHOT</version>
34+
</parent>
35+
<artifactId>leader-election</artifactId>
36+
<dependencies>
37+
<dependency>
38+
<groupId>org.junit.jupiter</groupId>
39+
<artifactId>junit-jupiter-engine</artifactId>
40+
<scope>test</scope>
41+
</dependency>
42+
</dependencies>
43+
</project>
Lines changed: 148 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,148 @@
1+
/**
2+
* The MIT License
3+
* Copyright (c) 2014-2016 Ilkka Seppälä
4+
* <p>
5+
* Permission is hereby granted, free of charge, to any person obtaining a copy
6+
* of this software and associated documentation files (the "Software"), to deal
7+
* in the Software without restriction, including without limitation the rights
8+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
* copies of the Software, and to permit persons to whom the Software is
10+
* furnished to do so, subject to the following conditions:
11+
* <p>
12+
* The above copyright notice and this permission notice shall be included in
13+
* all copies or substantial portions of the Software.
14+
* <p>
15+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21+
* THE SOFTWARE.
22+
*/
23+
24+
package com.iluwatar.leaderelection;
25+
26+
import org.slf4j.Logger;
27+
import org.slf4j.LoggerFactory;
28+
29+
import java.util.Queue;
30+
import java.util.concurrent.ConcurrentLinkedQueue;
31+
32+
/**
33+
* Abstract class of all the instance implementation classes.
34+
*/
35+
public abstract class AbstractInstance implements Instance, Runnable {
36+
37+
private static final Logger LOGGER = LoggerFactory.getLogger(AbstractInstance.class);
38+
39+
protected static final int HEARTBEAT_INTERVAL = 5000;
40+
41+
protected MessageManager messageManager;
42+
protected Queue<Message> messageQueue;
43+
protected final int localId;
44+
protected int leaderId;
45+
protected boolean alive;
46+
47+
/**
48+
* Constructor of BullyInstance.
49+
*/
50+
public AbstractInstance(MessageManager messageManager, int localId, int leaderId) {
51+
this.messageManager = messageManager;
52+
this.messageQueue = new ConcurrentLinkedQueue<>();
53+
this.localId = localId;
54+
this.leaderId = leaderId;
55+
this.alive = true;
56+
}
57+
58+
/**
59+
* The instance will execute the message in its message queue periodically once it is alive.
60+
*/
61+
@Override
62+
public void run() {
63+
while (true) {
64+
if (!this.messageQueue.isEmpty()) {
65+
this.processMessage(this.messageQueue.remove());
66+
}
67+
}
68+
}
69+
70+
/**
71+
* Once messages are sent to the certain instance, it will firstly be added to the queue and wait to be executed.
72+
* @param message Message sent by other instances
73+
*/
74+
@Override
75+
public void onMessage(Message message) {
76+
messageQueue.offer(message);
77+
}
78+
79+
/**
80+
* Check if the instance is alive or not.
81+
* @return {@code true} if the instance is alive.
82+
*/
83+
@Override
84+
public boolean isAlive() {
85+
return alive;
86+
}
87+
88+
/**
89+
* Set the health status of the certain instance.
90+
* @param alive {@code true} for alive.
91+
*/
92+
@Override
93+
public void setAlive(boolean alive) {
94+
this.alive = alive;
95+
}
96+
97+
/**
98+
* Process the message according to its type.
99+
* @param message Message polled from queue.
100+
*/
101+
private void processMessage(Message message) {
102+
switch (message.getType()) {
103+
case ELECTION:
104+
LOGGER.info("Instance " + localId + " - Election Message handling...");
105+
handleElectionMessage(message);
106+
break;
107+
case LEADER:
108+
LOGGER.info("Instance " + localId + " - Leader Message handling...");
109+
handleLeaderMessage(message);
110+
break;
111+
case HEARTBEAT:
112+
LOGGER.info("Instance " + localId + " - Heartbeat Message handling...");
113+
handleHeartbeatMessage(message);
114+
break;
115+
case ELECTION_INVOKE:
116+
LOGGER.info("Instance " + localId + " - Election Invoke Message handling...");
117+
handleElectionInvokeMessage();
118+
break;
119+
case LEADER_INVOKE:
120+
LOGGER.info("Instance " + localId + " - Leader Invoke Message handling...");
121+
handleLeaderInvokeMessage();
122+
break;
123+
case HEARTBEAT_INVOKE:
124+
LOGGER.info("Instance " + localId + " - Heartbeat Invoke Message handling...");
125+
handleHeartbeatInvokeMessage();
126+
break;
127+
default:
128+
break;
129+
}
130+
}
131+
132+
/**
133+
* Abstract methods to handle different types of message. These methods need to be implemented in concrete instance
134+
* class to implement corresponding leader-selection pattern.
135+
*/
136+
protected abstract void handleElectionMessage(Message message);
137+
138+
protected abstract void handleElectionInvokeMessage();
139+
140+
protected abstract void handleLeaderMessage(Message message);
141+
142+
protected abstract void handleLeaderInvokeMessage();
143+
144+
protected abstract void handleHeartbeatMessage(Message message);
145+
146+
protected abstract void handleHeartbeatInvokeMessage();
147+
148+
}
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
/**
2+
* The MIT License
3+
* Copyright (c) 2014-2016 Ilkka Seppälä
4+
* <p>
5+
* Permission is hereby granted, free of charge, to any person obtaining a copy
6+
* of this software and associated documentation files (the "Software"), to deal
7+
* in the Software without restriction, including without limitation the rights
8+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
* copies of the Software, and to permit persons to whom the Software is
10+
* furnished to do so, subject to the following conditions:
11+
* <p>
12+
* The above copyright notice and this permission notice shall be included in
13+
* all copies or substantial portions of the Software.
14+
* <p>
15+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21+
* THE SOFTWARE.
22+
*/
23+
24+
package com.iluwatar.leaderelection;
25+
26+
import java.util.List;
27+
import java.util.Map;
28+
import java.util.stream.Collectors;
29+
30+
/**
31+
* Abstract class of all the message manager classes.
32+
*/
33+
public abstract class AbstractMessageManager implements MessageManager {
34+
35+
/**
36+
* Contain all the instances in the system. Key is its ID, and value is the instance itself.
37+
*/
38+
protected Map<Integer, Instance> instanceMap;
39+
40+
/**
41+
* Construtor of AbstractMessageManager
42+
*/
43+
public AbstractMessageManager(Map<Integer, Instance> instanceMap) {
44+
this.instanceMap = instanceMap;
45+
}
46+
47+
/**
48+
* Find the next instance with smallest ID.
49+
* @return The next instance.
50+
*/
51+
protected Instance findNextInstance(int currentId) {
52+
Instance result = null;
53+
List<Integer> candidateList = instanceMap.keySet()
54+
.stream()
55+
.filter((i) -> i > currentId && instanceMap.get(i).isAlive())
56+
.sorted()
57+
.collect(Collectors.toList());
58+
if (candidateList.isEmpty()) {
59+
int index = instanceMap.keySet()
60+
.stream()
61+
.filter((i) -> instanceMap.get(i).isAlive())
62+
.sorted()
63+
.collect(Collectors.toList())
64+
.get(0);
65+
result = instanceMap.get(index);
66+
} else {
67+
int index = candidateList.get(0);
68+
result = instanceMap.get(index);
69+
}
70+
return result;
71+
}
72+
73+
}
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/**
2+
* The MIT License
3+
* Copyright (c) 2014-2016 Ilkka Seppälä
4+
*
5+
* Permission is hereby granted, free of charge, to any person obtaining a copy
6+
* of this software and associated documentation files (the "Software"), to deal
7+
* in the Software without restriction, including without limitation the rights
8+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
* copies of the Software, and to permit persons to whom the Software is
10+
* furnished to do so, subject to the following conditions:
11+
*
12+
* The above copyright notice and this permission notice shall be included in
13+
* all copies or substantial portions of the Software.
14+
*
15+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21+
* THE SOFTWARE.
22+
*/
23+
24+
package com.iluwatar.leaderelection;
25+
26+
/**
27+
* Instance interface
28+
*/
29+
public interface Instance {
30+
31+
/**
32+
* Check if the instance is alive or not.
33+
* @return {@code true} if the instance is alive.
34+
*/
35+
boolean isAlive();
36+
37+
/**
38+
* Set the health status of the certain instance.
39+
* @param alive {@code true} for alive.
40+
*/
41+
void setAlive(boolean alive);
42+
43+
/**
44+
* Consume messages from other instances.
45+
* @param message Message sent by other instances
46+
*/
47+
void onMessage(Message message);
48+
49+
}

0 commit comments

Comments
 (0)