Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitc2786e5

Browse files
Dev-AliGhasemiohbusiluwatar
authored
add monitor design pattern (iluwatar#1640)
* add monitor design pattern .* add extra line and change compiler version to 11 in pom.xml.* encapsulate getBalance method .* update puml file .* export uml as png .* duplicate codes eliminated .* update tag* change the format of pom.xml* using logger to print* change AtomicRefrence to type inference var* explanations added !* Update monitor/README.mdCo-authored-by: Ilkka Seppälä <iluwatar@users.noreply.github.com>* Update monitor/README.mdCo-authored-by: Ilkka Seppälä <iluwatar@users.noreply.github.com>* Update monitor/src/main/java/com/iluwatar/monitor/Main.javaCo-authored-by: Ilkka Seppälä <iluwatar@users.noreply.github.com>* Update monitor/src/main/java/com/iluwatar/monitor/Main.javaCo-authored-by: Ilkka Seppälä <iluwatar@users.noreply.github.com>* Update monitor/src/main/java/com/iluwatar/monitor/Main.javaCo-authored-by: Ilkka Seppälä <iluwatar@users.noreply.github.com>* Update monitor/src/main/java/com/iluwatar/monitor/Main.javaCo-authored-by: Ilkka Seppälä <iluwatar@users.noreply.github.com>* e.printStackTrace have changed to logger to prints standard output (STD OUT) .* add programmatic example .* Delete mvnw* mvnw.cmd deleted .* added mvnw from master* AddUnitTest* Add language to readme.mdCo-authored-by: Subhrodip Mohanta <subhrodipmohanta@gmail.com>Co-authored-by: Ilkka Seppälä <iluwatar@users.noreply.github.com>Co-authored-by: Subhrodip Mohanta <subhromo@cisco.com>Co-authored-by: Subhrodip Mohanta <contact@subho.xyz>
1 parenta1f3c6f commitc2786e5

File tree

7 files changed

+294
-0
lines changed

7 files changed

+294
-0
lines changed

‎monitor/README.md

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
---
2+
layout:pattern
3+
title:Monitor
4+
folder:monitor
5+
permalink:/patterns/monitor/
6+
categories:Concurrency
7+
language:en
8+
tags:
9+
-Performance
10+
---
11+
12+
##Intent
13+
Monitor pattern is used to create thread-safe objects and prevent conflicts between threads in concurrent applications.
14+
15+
##Explanation
16+
17+
In plain words
18+
19+
>Monitor pattern is used to enforce single-threaded access to data. Only one thread at a time is allowed to execute code within the monitor object.
20+
21+
Wikipedia says
22+
23+
>In concurrent programming (also known as parallel programming), a monitor is a synchronization construct that allows threads to have both mutual exclusion and the ability to wait (block) for a certain condition to become false. Monitors also have a mechanism for signaling other threads that their condition has been met.
24+
25+
**Programmatic Examples**
26+
27+
Consider there is a bank that transfers money from an account to another account with transfer method . it is`synchronized` mean just one thread can access to this method because if many threads access to it and transfer money from an account to another account in same time balance changed !
28+
29+
```
30+
class Bank {
31+
32+
private int[] accounts;
33+
Logger logger;
34+
35+
public Bank(int accountNum, int baseAmount, Logger logger) {
36+
this.logger = logger;
37+
accounts = new int[accountNum];
38+
Arrays.fill(accounts, baseAmount);
39+
}
40+
41+
public synchronized void transfer(int accountA, int accountB, int amount) {
42+
if (accounts[accountA] >= amount) {
43+
accounts[accountB] += amount;
44+
accounts[accountA] -= amount;
45+
logger.info("Transferred from account :" + accountA + " to account :" + accountB + " , amount :" + amount + " . balance :" + getBalance());
46+
}
47+
}
48+
```
49+
50+
getBalance always return total amount and the total amount should be same after each transfers
51+
52+
```
53+
private synchronized int getBalance() {
54+
int balance = 0;
55+
for (int account : accounts) {
56+
balance += account;
57+
}
58+
return balance;
59+
}
60+
}
61+
```
62+
63+
##Class diagram
64+
![alt text](./etc/monitor.urm.png"Monitor class diagram")
65+
66+
##Applicability
67+
Use the Monitor pattern when
68+
69+
* we have a shared resource and there is critical section .
70+
* you want to create thread-safe objects .
71+
* you want to achieve mutual exclusion in high level programming language .

‎monitor/etc/monitor.urm.png

10.2 KB
Loading

‎monitor/etc/monitor.urm.puml

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
@startuml
2+
Main-Bank : use
3+
classMain{
4+
+main(args : String[]) : void
5+
}
6+
classBank{
7+
-accounts : int[]
8+
+Bank (accountNum : int , baseAccount : int)
9+
+transfer(accountA : int , accountB : int , amount : int) : void {synchronized}
10+
-getBalance() : void {synchronized}
11+
}
12+
@enduml

‎monitor/pom.xml

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<!--
3+
The MIT License
4+
Copyright © 2014-2021 Ilkka Seppälä
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+
The above copyright notice and this permission notice shall be included in
12+
all copies or substantial portions of the Software.
13+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19+
THE SOFTWARE.
20+
-->
21+
<projectxmlns="http://maven.apache.org/POM/4.0.0"
22+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
23+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
24+
<modelVersion>4.0.0</modelVersion>
25+
<parent>
26+
<artifactId>java-design-patterns</artifactId>
27+
<groupId>com.iluwatar</groupId>
28+
<version>1.24.0-SNAPSHOT</version>
29+
</parent>
30+
<artifactId>monitor</artifactId>
31+
<dependencies>
32+
<dependency>
33+
<groupId>org.junit.jupiter</groupId>
34+
<artifactId>junit-jupiter-engine</artifactId>
35+
<scope>test</scope>
36+
</dependency>
37+
</dependencies>
38+
<build>
39+
<plugins>
40+
<!-- Maven assembly plugin is invoked with default setting which we have
41+
in parent pom and specifying the class having main method-->
42+
<plugin>
43+
<groupId>org.apache.maven.plugins</groupId>
44+
<artifactId>maven-assembly-plugin</artifactId>
45+
<executions>
46+
<execution>
47+
<configuration>
48+
<archive>
49+
<manifest>
50+
<mainClass>com.iluwatar.abstractdocument.Main</mainClass>
51+
</manifest>
52+
</archive>
53+
</configuration>
54+
</execution>
55+
</executions>
56+
</plugin>
57+
</plugins>
58+
</build>
59+
</project>
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
packagecom.iluwatar.monitor;
2+
3+
importjava.util.Arrays;
4+
importjava.util.logging.Logger;
5+
6+
// Bank class implements the Monitor pattern
7+
publicclassBank {
8+
9+
privateint[]accounts;
10+
Loggerlogger;
11+
12+
publicBank(intaccountNum,intbaseAmount,Loggerlogger) {
13+
this.logger =logger;
14+
accounts =newint[accountNum];
15+
Arrays.fill(accounts,baseAmount);
16+
}
17+
18+
publicsynchronizedvoidtransfer(intaccountA,intaccountB,intamount) {
19+
if (accounts[accountA] >=amount) {
20+
accounts[accountB] +=amount;
21+
accounts[accountA] -=amount;
22+
logger.info("Transferred from account :" +accountA +" to account :" +accountB +" , amount :" +amount +" . balance :" +getBalance());
23+
}
24+
}
25+
26+
publicsynchronizedintgetBalance() {
27+
intbalance =0;
28+
for (intaccount :accounts) {
29+
balance +=account;
30+
}
31+
returnbalance;
32+
}
33+
34+
publicint[]getAccounts() {
35+
returnaccounts;
36+
}
37+
}
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
/*
2+
* The MIT License
3+
* Copyright © 2014-2021 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+
packagecom.iluwatar.monitor;
25+
26+
importjava.util.*;
27+
importjava.util.concurrent.ExecutorService;
28+
importjava.util.concurrent.Executors;
29+
importjava.util.logging.Logger;
30+
31+
/**
32+
* <p>The Monitor pattern is used in concurrent algorithms to achieve mutual exclusion.</p>
33+
*
34+
* <p>Bank is a simple class that transfers money from an account to another account using
35+
* {@link Bank#transfer}. It can also return the balance of the bank account stored in the bank.</p>
36+
*
37+
* <p>Main class uses ThreadPool to run threads that do transactions on the bank accounts.</p>
38+
*/
39+
40+
publicclassMain {
41+
42+
publicstaticvoidmain(String[]args) {
43+
Loggerlogger =Logger.getLogger("monitor");
44+
varbank =newBank(4,1000,logger);
45+
Runnablerunnable = () -> {
46+
try {
47+
Thread.sleep((long) (Math.random() *1000));
48+
Randomrandom =newRandom();
49+
for (inti =0;i <1000000;i++)
50+
bank.transfer(random.nextInt(4),random.nextInt(4), (int) (Math.random() *1000));
51+
}catch (InterruptedExceptione) {
52+
logger.info(e.getMessage());
53+
}
54+
};
55+
ExecutorServiceexecutorService =Executors.newFixedThreadPool(5);
56+
for (inti =0;i <5;i++) {
57+
executorService.execute(runnable);
58+
}
59+
}
60+
}
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
packagecom.iluwater.java;
2+
3+
importcom.iluwatar.monitor.Bank;
4+
importorg.junit.jupiter.api.AfterAll;
5+
importorg.junit.jupiter.api.BeforeAll;
6+
importorg.junit.jupiter.api.Test;
7+
8+
importstaticorg.junit.jupiter.api.Assertions.*;
9+
importstaticorg.junit.jupiter.api.Assumptions.*;
10+
11+
importjava.util.logging.Logger;
12+
13+
publicclassBankTest {
14+
15+
privatestaticBankbank;
16+
privatestaticfinalintACCOUNT_NUM =4;
17+
privatestaticfinalintBASE_AMOUNT =1000;
18+
privatestaticfinalLoggerLOGGER =Logger.getLogger("monitor");
19+
20+
@BeforeAll
21+
publicstaticvoidSetup() {
22+
bank =newBank(ACCOUNT_NUM,BASE_AMOUNT,LOGGER);
23+
}
24+
25+
@Test
26+
publicvoidGetAccountHaveNotBeNull() {
27+
assertNotNull(bank.getAccounts());
28+
}
29+
30+
@Test
31+
publicvoidLengthOfAccountsHaveToEqualsToAccountNumConstant() {
32+
assumeTrue(bank.getAccounts() !=null);
33+
assertEquals(ACCOUNT_NUM,bank.getAccounts().length);
34+
}
35+
36+
@Test
37+
publicvoidTransferMethodHaveToTransferAmountFromAnAccountToOtherAccount() {
38+
bank.transfer(0,1,1000);
39+
intaccounts[] =bank.getAccounts();
40+
assertEquals(0,accounts[0]);
41+
assertEquals(2000,2000);
42+
}
43+
44+
@Test
45+
publicvoidBalanceHaveToBeOK() {
46+
assertEquals(4000,bank.getBalance());
47+
}
48+
49+
50+
@AfterAll
51+
publicstaticvoidTearDown() {
52+
bank =null;
53+
}
54+
55+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp