Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions marker/src/main/java/App.java
Original file line number Diff line number Diff line change
Expand Up @@ -46,17 +46,18 @@ public class App {
* @param args command line args
*/
public static void main(String[] args) {
final var logger = LoggerFactory.getLogger(App.class);
var guard = new Guard();
var thief = new Thief();

final Logger logger = LoggerFactory.getLogger(App.class);
Guard guard = new Guard();
Thief thief = new Thief();

//noinspection ConstantConditions
if (guard instanceof Permission) {
guard.enter();
} else {
logger.info("You have no permission to enter, please leave this area");
}

//noinspection ConstantConditions
if (thief instanceof Permission) {
thief.steal();
} else {
Expand Down
4 changes: 1 addition & 3 deletions marker/src/main/java/Guard.java
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,9 @@
* Class defining Guard.
*/
public class Guard implements Permission {

private static final Logger LOGGER = LoggerFactory.getLogger(Guard.class);

protected static void enter() {

protected void enter() {
LOGGER.info("You can enter");
}
}
5 changes: 2 additions & 3 deletions marker/src/main/java/Thief.java
Original file line number Diff line number Diff line change
Expand Up @@ -28,14 +28,13 @@
* Class defining Thief.
*/
public class Thief {

private static final Logger LOGGER = LoggerFactory.getLogger(Thief.class);

protected static void steal() {
protected void steal() {
LOGGER.info("Steal valuable items");
}

protected static void doNothing() {
protected void doNothing() {
LOGGER.info("Pretend nothing happened and just leave");
}
}
3 changes: 1 addition & 2 deletions marker/src/test/java/AppTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ public class AppTest {

@Test
public void test() {
String[] args = {};
App.main(args);
App.main(new String[]{});
}
}
2 changes: 1 addition & 1 deletion marker/src/test/java/GuardTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public class GuardTest {

@Test
public void testGuard() {
Guard guard = new Guard();
var guard = new Guard();
assertThat(guard, instanceOf(Permission.class));
}
}
10 changes: 6 additions & 4 deletions marker/src/test/java/ThiefTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,17 +21,19 @@
* THE SOFTWARE.
*/

import org.junit.jupiter.api.Test;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.MatcherAssert.assertThat;

import static org.junit.jupiter.api.Assertions.assertFalse;
import org.junit.jupiter.api.Test;

/**
* Thief test
*/
public class ThiefTest {
@Test
public void testThief() {
Thief thief = new Thief();
assertFalse(thief instanceof Permission);
var thief = new Thief();
assertThat(thief, not(instanceOf(Permission.class)));
}
}
67 changes: 34 additions & 33 deletions master-worker-pattern/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -22,38 +22,39 @@
THE SOFTWARE.

-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.iluwatar</groupId>
<artifactId>java-design-patterns</artifactId>
<version>1.23.0-SNAPSHOT</version>
</parent>
<artifactId>master-worker-pattern</artifactId>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.iluwatar</groupId>
<artifactId>java-design-patterns</artifactId>
<version>1.23.0-SNAPSHOT</version>
</parent>
<artifactId>master-worker-pattern</artifactId>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<configuration>
<archive>
<manifest>
<mainClass>com.iluwatar.masterworker.App</mainClass>
</manifest>
</archive>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<configuration>
<archive>
<manifest>
<mainClass>com.iluwatar.masterworker.App</mainClass>
</manifest>
</archive>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Original file line number Diff line number Diff line change
Expand Up @@ -34,27 +34,25 @@

/**
* <p>The <b><em>Master-Worker</em></b> pattern is used when the problem at hand can be solved by
* dividing into
* multiple parts which need to go through the same computation and may need to be aggregated to get
* final result. Parallel processing is performed using a system consisting of a master and some
* number of workers, where a master divides the work among the workers, gets the result back from
* them and assimilates all the results to give final result. The only communication is between the
* master and the worker - none of the workers communicate among one another and the user only
* communicates with the master to get required job done.</p>
* dividing into multiple parts which need to go through the same computation and may need to be
* aggregated to get final result. Parallel processing is performed using a system consisting of a
* master and some number of workers, where a master divides the work among the workers, gets the
* result back from them and assimilates all the results to give final result. The only
* communication is between the master and the worker - none of the workers communicate among one
* another and the user only communicates with the master to get required job done.</p>
* <p>In our example, we have generic abstract classes {@link MasterWorker}, {@link Master} and
* {@link Worker} which
* have to be extended by the classes which will perform the specific job at hand (in this case
* finding transpose of matrix, done by {@link ArrayTransposeMasterWorker}, {@link
* ArrayTransposeMaster} and {@link ArrayTransposeWorker}). The Master class divides the work into
* parts to be given to the workers, collects the results from the workers and aggregates it when
* all workers have responded before returning the solution. The Worker class extends the Thread
* class to enable parallel processing, and does the work once the data has been received from the
* Master. The MasterWorker contains a reference to the Master class, gets the input from the App
* and passes it on to the Master. These 3 classes define the system which computes the result. We
* also have 2 abstract classes {@link Input} and {@link Result}, which contain the input data and
* result data respectively. The Input class also has an abstract method divideData which defines
* how the data is to be divided into segments. These classes are extended by {@link ArrayInput} and
* {@link ArrayResult}.</p>
* {@link Worker} which have to be extended by the classes which will perform the specific job at
* hand (in this case finding transpose of matrix, done by {@link ArrayTransposeMasterWorker},
* {@link ArrayTransposeMaster} and {@link ArrayTransposeWorker}). The Master class divides the work
* into parts to be given to the workers, collects the results from the workers and aggregates it
* when all workers have responded before returning the solution. The Worker class extends the
* Thread class to enable parallel processing, and does the work once the data has been received
* from the Master. The MasterWorker contains a reference to the Master class, gets the input from
* the App and passes it on to the Master. These 3 classes define the system which computes the
* result. We also have 2 abstract classes {@link Input} and {@link Result}, which contain the input
* data and result data respectively. The Input class also has an abstract method divideData which
* defines how the data is to be divided into segments. These classes are extended by {@link
* ArrayInput} and {@link ArrayResult}.</p>
*/

public class App {
Expand All @@ -68,12 +66,12 @@ public class App {
*/

public static void main(String[] args) {
ArrayTransposeMasterWorker mw = new ArrayTransposeMasterWorker();
int rows = 10;
int columns = 20;
int[][] inputMatrix = ArrayUtilityMethods.createRandomIntMatrix(rows, columns);
ArrayInput input = new ArrayInput(inputMatrix);
ArrayResult result = (ArrayResult) mw.getResult(input);
var mw = new ArrayTransposeMasterWorker();
var rows = 10;
var columns = 20;
var inputMatrix = ArrayUtilityMethods.createRandomIntMatrix(rows, columns);
var input = new ArrayInput(inputMatrix);
var result = (ArrayResult) mw.getResult(input);
if (result != null) {
ArrayUtilityMethods.printMatrix(inputMatrix);
ArrayUtilityMethods.printMatrix(result.data);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
* Class ArrayInput extends abstract class {@link Input} and contains data of type int[][].
Expand All @@ -37,12 +38,12 @@ public ArrayInput(int[][] data) {
}

static int[] makeDivisions(int[][] data, int num) {
int initialDivision = data.length / num; //equally dividing
int[] divisions = new int[num];
var initialDivision = data.length / num; //equally dividing
var divisions = new int[num];
Arrays.fill(divisions, initialDivision);
if (initialDivision * num != data.length) {
int extra = data.length - initialDivision * num;
int l = 0;
var extra = data.length - initialDivision * num;
var l = 0;
//equally dividing extra among all parts
while (extra > 0) {
divisions[l] = divisions[l] + 1;
Expand All @@ -58,22 +59,20 @@ static int[] makeDivisions(int[][] data, int num) {
}

@Override
public ArrayList<Input> divideData(int num) {
public List<Input<int[][]>> divideData(int num) {
if (this.data == null) {
return null;
} else {
int[] divisions = makeDivisions(this.data, num);
ArrayList<Input> result = new ArrayList<Input>(num);
int rowsDone = 0; //number of rows divided so far
for (int i = 0; i < num; i++) {
int rows = divisions[i];
var divisions = makeDivisions(this.data, num);
var result = new ArrayList<Input<int[][]>>(num);
var rowsDone = 0; //number of rows divided so far
for (var i = 0; i < num; i++) {
var rows = divisions[i];
if (rows != 0) {
int[][] divided = new int[rows][this.data[0].length];
for (int j = 0; j < rows; j++) {
divided[j] = this.data[rowsDone + j];
}
var divided = new int[rows][this.data[0].length];
System.arraycopy(this.data, rowsDone, divided, 0, rows);
rowsDone += rows;
ArrayInput dividedInput = new ArrayInput(divided);
var dividedInput = new ArrayInput(divided);
result.add(dividedInput);
} else {
break; //rest of divisions will also be 0
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,8 @@ public static boolean arraysSame(int[] a1, int[] a2) {
if (a1.length != a2.length) {
return false;
} else {
boolean answer = false;
for (int i = 0; i < a1.length; i++) {
var answer = false;
for (var i = 0; i < a1.length; i++) {
if (a1[i] == a2[i]) {
answer = true;
} else {
Expand All @@ -69,8 +69,8 @@ public static boolean matricesSame(int[][] m1, int[][] m2) {
if (m1.length != m2.length) {
return false;
} else {
boolean answer = false;
for (int i = 0; i < m1.length; i++) {
var answer = false;
for (var i = 0; i < m1.length; i++) {
if (arraysSame(m1[i], m2[i])) {
answer = true;
} else {
Expand All @@ -88,9 +88,9 @@ public static boolean matricesSame(int[][] m1, int[][] m2) {
* @return it (int[][]).
*/
public static int[][] createRandomIntMatrix(int rows, int columns) {
int[][] matrix = new int[rows][columns];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
var matrix = new int[rows][columns];
for (var i = 0; i < rows; i++) {
for (var j = 0; j < columns; j++) {
//filling cells in matrix
matrix[i][j] = RANDOM.nextInt(10);
}
Expand All @@ -104,9 +104,9 @@ public static int[][] createRandomIntMatrix(int rows, int columns) {

public static void printMatrix(int[][] matrix) {
//prints out int[][]
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
LOGGER.info(matrix[i][j] + " ");
for (var ints : matrix) {
for (var j = 0; j < matrix[0].length; j++) {
LOGGER.info(ints[j] + " ");
}
LOGGER.info("");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@

package com.iluwatar.masterworker;

import java.util.ArrayList;
import java.util.List;

/**
* The abstract Input class, having 1 public field which contains input data, and abstract method
Expand All @@ -40,5 +40,5 @@ public Input(T data) {
this.data = data;
}

public abstract ArrayList<Input> divideData(int num);
public abstract List<Input<T>> divideData(int num);
}
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public MasterWorker(int numOfWorkers) {

abstract Master setMaster(int numOfWorkers);

public Result getResult(Input input) {
public Result<?> getResult(Input<?> input) {
this.master.doWork(input);
return this.master.getFinalResult();
}
Expand Down
Loading