Compare commits

..

2 Commits

Author SHA1 Message Date
Ilkka Seppälä
06678a5888 #1617 update license headers 2021-01-24 20:07:40 +02:00
Ilkka Seppälä
11d0912c6e #1617 merge dto pattern examples 2021-01-24 19:57:21 +02:00
49 changed files with 1430 additions and 142 deletions

View File

@@ -1377,33 +1377,6 @@
"contributions": [
"translation"
]
},
{
"login": "rohit10000",
"name": "Rohit Singh",
"avatar_url": "https://avatars.githubusercontent.com/u/20845565?v=4",
"profile": "https://github.com/rohit10000",
"contributions": [
"code"
]
},
{
"login": "byoungju94",
"name": "byoungju94",
"avatar_url": "https://avatars.githubusercontent.com/u/42516378?v=4",
"profile": "https://github.com/byoungju94",
"contributions": [
"code"
]
},
{
"login": "moustafafarhat",
"name": "Moustafa Farhat",
"avatar_url": "https://avatars.githubusercontent.com/u/38836727?v=4",
"profile": "https://github.com/moustafafarhat",
"contributions": [
"translation"
]
}
],
"contributorsPerLine": 4,

View File

@@ -1,6 +1,6 @@
The MIT License (MIT)
Copyright (c) 2014-2021 Ilkka Seppälä
Copyright (c) 2014-2020 Ilkka Seppälä
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal

View File

@@ -10,12 +10,12 @@
[![Coverage](https://sonarcloud.io/api/project_badges/measure?project=iluwatar_java-design-patterns&metric=coverage)](https://sonarcloud.io/dashboard?id=iluwatar_java-design-patterns)
[![Join the chat at https://gitter.im/iluwatar/java-design-patterns](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/iluwatar/java-design-patterns?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->
[![All Contributors](https://img.shields.io/badge/all_contributors-154-orange.svg?style=flat-square)](#contributors-)
[![All Contributors](https://img.shields.io/badge/all_contributors-151-orange.svg?style=flat-square)](#contributors-)
<!-- ALL-CONTRIBUTORS-BADGE:END -->
<br/>
Read in different language : [![CN](/assets/flags/CN.png)**CN**](/zh/README.md),[![KR](/assets/flags/KR.png)**KR**](/ko/README.md),[![FR](/assets/flags/FR.png)**FR**](/fr/README.md),[![TR](/assets/flags/TR.png)**TR**](/tr/README.md),[![AR](/assets/flags/AR.png)**AR**](/ar/README.md),
Read in different language : [![CN](/assets/flags/CN.png)**CN**](/zh/README.md),[![KR](/assets/flags/KR.png)**KR**](/ko/README.md),[![FR](/assets/flags/FR.png)**FR**](/fr/README.md),[![TR](/assets/flags/TR.png)**TR**](/tr/README.md),
<br/>
@@ -301,11 +301,6 @@ This project is licensed under the terms of the MIT license.
<td align="center"><a href="http://libkhadir.fr"><img src="https://avatars1.githubusercontent.com/u/45130488?v=4?s=100" width="100px;" alt=""/><br /><sub><b>KHADIR Tayeb</b></sub></a><br /><a href="#translation-tkhadir" title="Translation">🌍</a></td>
<td align="center"><a href="https://github.com/ignite1771"><img src="https://avatars2.githubusercontent.com/u/59446563?v=4?s=100" width="100px;" alt=""/><br /><sub><b>ignite1771</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=ignite1771" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/demirhalil"><img src="https://avatars1.githubusercontent.com/u/22895118?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Halil Demir</b></sub></a><br /><a href="#translation-demirhalil" title="Translation">🌍</a></td>
<td align="center"><a href="https://github.com/rohit10000"><img src="https://avatars.githubusercontent.com/u/20845565?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Rohit Singh</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=rohit10000" title="Code">💻</a></td>
</tr>
<tr>
<td align="center"><a href="https://github.com/byoungju94"><img src="https://avatars.githubusercontent.com/u/42516378?v=4?s=100" width="100px;" alt=""/><br /><sub><b>byoungju94</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=byoungju94" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/moustafafarhat"><img src="https://avatars.githubusercontent.com/u/38836727?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Moustafa Farhat</b></sub></a><br /><a href="#translation-moustafafarhat" title="Translation">🌍</a></td>
</tr>
</table>

View File

@@ -213,8 +213,8 @@ Example use cases
## Related patterns
* [Factory Method](https://java-design-patterns.com/patterns/factory-method/)
* [Factory Kit](https://java-design-patterns.com/patterns/factory-kit/)
[Factory Method](https://java-design-patterns.com/patterns/factory-method/)
[Factory Kit](https://java-design-patterns.com/patterns/factory-kit/)
## Credits

View File

@@ -1,42 +0,0 @@
# أنماط التصميم بلغة برمجة الجافا
![Java CI with Maven](https://github.com/iluwatar/java-design-patterns/workflows/Java%20CI%20with%20Maven/badge.svg)
[![License MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://raw.githubusercontent.com/iluwatar/java-design-patterns/master/LICENSE.md)
[![Lines of Code](https://sonarcloud.io/api/project_badges/measure?project=iluwatar_java-design-patterns&metric=ncloc)](https://sonarcloud.io/dashboard?id=iluwatar_java-design-patterns)
[![Coverage](https://sonarcloud.io/api/project_badges/measure?project=iluwatar_java-design-patterns&metric=coverage)](https://sonarcloud.io/dashboard?id=iluwatar_java-design-patterns)
[![Join the chat at https://gitter.im/iluwatar/java-design-patterns](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/iluwatar/java-design-patterns?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->
[![All Contributors](https://img.shields.io/badge/all_contributors-148-orange.svg?style=flat-square)](#contributors-)
<!-- ALL-CONTRIBUTORS-BADGE:END -->
# مقدمة
أنماط التصميم هي أفضل التدريبات التي يمكن للمبرمج استخدامها لحل المشكلات الشائعة عند تصميم تطبيق أو نظام.
يمكن لأنماط التصميم تسريع عملية التطوير من خلال توفير نماذج تطوير مجربة ومثبتة ومفيدة.
تساعد إعادة استخدام أنماط التصميم في منع المشكلات الدقيقة التي تسبب مشكلات كبيرة ، كما تعمل على تحسين قابلية قراءة الكود للمهندسين البرمجيات الذين هم على دراية بالأنماط.
# البدء في التعلم
يعرض هذا الموقع أنماط تصميم جافا. تم تطوير الحلول من قبل المبرمجين والمهندسين ذوي الخبرة من مجتمع المصادر المفتوحة. يمكن تصفح الأنماط من خلال أوصافها عالية المستوى أو بالنظر إلى كود المصدر الخاص بها. تم كتابة الشرح على أمثلة الكود المصدري جيدًا ويمكن اعتبارها برامج تعليمية حول كيفية تنفيذ نمط معين. نحن نستخدم تقنيات Java مفتوحة المصدر الأكثر شيوعًا والتي أثبتت جدارتها في مشاريع الجافا.
قبل الغوص في المادة ، يجب أن تكون على دراية [بمبادئ تصميم البرامج المختلفة](https://java-design-patterns.com/principles/).
يجب أن تكون جميع التصميمات بسيطة قدر الإمكان. يجب أن تبدأ بـ KISS و YAGNI وافعل أبسط شيء يمكن أن يعمل بهذه المبادىء. يجب إستخدام الأنماط فقط عند الحاجة إليها من أجل تمديد البرنامج بشكل عملي.
بمجرد أن تصبح معتادًا على هذه المفاهيم ، يمكنك البدء في التعمق في [أنماط التصميم المتاحة](https://java-design-patterns.com/patterns/) من خلال أي من الأساليب التالية
ابحث عن نمط محدد بالاسم. لا يمكنك العثور على واحد؟ الرجاء الإبلاغ عن نمط جديد [هنا](https://github.com/iluwatar/java-design-patterns/issues).
استخدام علامات مثل Performance أو Gang of Four أو الوصول إلى البيانات.
استخدام فئات الأنماط و Creational, Behavioral وغيرها.
نأمل أن تجد الحلول الموجهة للكائنات المعروضة على هذا الموقع مفيدة في مشاريعك البرمجية وأن تستمتع بتعلمها بقدر ما قمنا بتطويرها.
# كيف تساهم؟
إذا كنت على استعداد للمساهمة في المشروع ، فستجد المعلومات ذات الصلة في [ويكي المطور الخاص بنا](https://github.com/iluwatar/java-design-patterns/wiki). سنساعدك ونجيب على أسئلتك في [غرفة الدردشة Gitter](https://gitter.im/iluwatar/java-design-patterns).
# الترخيص
هذا المشروع مرخص بموجب شروط ترخيص MIT.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 252 B

View File

@@ -20,14 +20,12 @@ callbacks or waiting until everything is done.
## Applicability
Use async method invocation pattern when
* You have multiple independent tasks that can run in parallel
* You need to improve the performance of a group of sequential tasks
* You have limited amount of processing capacity or long running tasks and the
* you have multiple independent tasks that can run in parallel
* you need to improve the performance of a group of sequential tasks
* you have limited amount of processing capacity or long running tasks and the
caller should not wait the tasks to be ready
## Real world examples
* [FutureTask](http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/FutureTask.html)
* [CompletableFuture](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html)
* [ExecutorService](http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html)
* [Task-based Asynchronous Pattern](https://msdn.microsoft.com/en-us/library/hh873175.aspx)
* [FutureTask](http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/FutureTask.html), [CompletableFuture](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html) and [ExecutorService](http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html) (Java)
* [Task-based Asynchronous Pattern](https://msdn.microsoft.com/en-us/library/hh873175.aspx) (.NET)

View File

@@ -23,15 +23,13 @@
package com.iluwatar.caching;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* Application test
*/
class CachingTest {
public class CachingTest {
private App app;
/**
@@ -49,26 +47,22 @@ class CachingTest {
}
@Test
void testReadAndWriteThroughStrategy() {
assertNotNull(app);
public void testReadAndWriteThroughStrategy() {
app.useReadAndWriteThroughStrategy();
}
@Test
void testReadThroughAndWriteAroundStrategy() {
assertNotNull(app);
public void testReadThroughAndWriteAroundStrategy() {
app.useReadThroughAndWriteAroundStrategy();
}
@Test
void testReadThroughAndWriteBehindStrategy() {
assertNotNull(app);
public void testReadThroughAndWriteBehindStrategy() {
app.useReadThroughAndWriteBehindStrategy();
}
@Test
void testCacheAsideStrategy() {
assertNotNull(app);
public void testCacheAsideStrategy() {
app.useCacheAsideStategy();
}
}

View File

@@ -49,7 +49,7 @@ remote calls.
The service architecture is as follows:
![alt text](./etc/ServiceDiagram.png "Service Diagram")
![alt text](./etc/ServiceDiagram.PNG "Service Diagram")
In terms of code, the end user application is:
@@ -292,7 +292,7 @@ public class DefaultCircuitBreaker implements CircuitBreaker {
How does the above pattern prevent failures? Let's understand via this finite state machine
implemented by it.
![alt text](./etc/StateDiagram.png "State Diagram")
![alt text](./etc/StateDiagram.PNG "State Diagram")
- We initialize the Circuit Breaker object with certain parameters: `timeout`, `failureThreshold` and `retryTimePeriod` which help determine how resilient the API is.
- Initially, we are in the `closed` state and nos remote calls to the API have occurred.

View File

Before

Width:  |  Height:  |  Size: 23 KiB

After

Width:  |  Height:  |  Size: 23 KiB

View File

Before

Width:  |  Height:  |  Size: 19 KiB

After

Width:  |  Height:  |  Size: 19 KiB

View File

@@ -105,4 +105,4 @@ domain equivalence.
## Credits
* [Converter Pattern in Java 8](http://www.xsolve.pl/blog/converter-pattern-in-java-8/)
* [Converter](http://www.xsolve.pl/blog/converter-pattern-in-java-8/)

View File

@@ -67,7 +67,7 @@ public class DbCustomerDao implements CustomerDao {
public Stream<Customer> getAll() throws Exception {
try {
var connection = getConnection();
var statement = connection.prepareStatement("SELECT * FROM CUSTOMERS"); // NOSONAR
var statement = connection.prepareStatement("SELECT * FROM CUSTOMERS");
var resultSet = statement.executeQuery(); // NOSONAR
return StreamSupport.stream(new Spliterators.AbstractSpliterator<Customer>(Long.MAX_VALUE,
Spliterator.ORDERED) {

31
mutex/README.md Normal file
View File

@@ -0,0 +1,31 @@
---
layout: pattern
title: Mutex
folder: mutex
permalink: /patterns/mutex/
categories: Concurrency
tags:
- Decoupling
---
## Also known as
* Mutual Exclusion Lock
* Binary Semaphore
## Intent
Create a lock which only allows a single thread to access a resource at any one instant.
## Class diagram
![alt text](./etc/mutex.png "Mutex")
## Applicability
Use a Mutex when
* You need to prevent two threads accessing a critical section at the same time
* Concurrent access to a resource could lead to a race condition
## Credits
* [Lock (computer science)](http://en.wikipedia.org/wiki/Lock_(computer_science))
* [Semaphores](http://tutorials.jenkov.com/java-concurrency/semaphores.html)

BIN
mutex/etc/mutex.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

27
mutex/etc/mutex.urm.puml Normal file
View File

@@ -0,0 +1,27 @@
@startuml
package com.iluwatar.mutex {
class App {
+ App()
+ main(args : String[]) {static}
}
class Jar {
- beans : int
- lock : Lock
+ Jar(beans : int, lock : Lock)
+ takeBean() : boolean
}
interface Lock {
+ acquire() {abstract}
+ release() {abstract}
}
class Mutex {
- owner : Object
+ Mutex()
+ acquire()
+ getOwner() : Object
+ release()
}
}
Jar --> "-lock" Lock
Mutex ..|> Lock
@enduml

61
mutex/pom.xml Normal file
View File

@@ -0,0 +1,61 @@
<?xml version="1.0"?>
<!--
The MIT License
Copyright © 2014-2019 Ilkka Seppälä
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-->
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.iluwatar</groupId>
<artifactId>java-design-patterns</artifactId>
<version>1.24.0-SNAPSHOT</version>
</parent>
<artifactId>mutex</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.mutex.App</mainClass>
</manifest>
</archive>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@@ -0,0 +1,49 @@
/*
* The MIT License
* Copyright © 2014-2019 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.mutex;
/**
* A Mutex prevents multiple threads from accessing a resource simultaneously.
*
* <p>In this example we have two thieves who are taking beans from a jar. Only one thief can take
* a bean at a time. This is ensured by a Mutex lock which must be acquired in order to access the
* jar. Each thief attempts to acquire the lock, take a bean and then release the lock. If the lock
* has already been acquired, the thief will be prevented from continuing (blocked) until the lock
* has been released. The thieves stop taking beans once there are no beans left to take.
*/
public class App {
/**
* main method.
*/
public static void main(String[] args) {
var mutex = new Mutex();
var jar = new Jar(1000, mutex);
var peter = new Thief("Peter", jar);
var john = new Thief("John", jar);
peter.start();
john.start();
}
}

View File

@@ -0,0 +1,67 @@
/*
* The MIT License
* Copyright © 2014-2019 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.mutex;
/**
* A Jar has a resource of beans which can only be accessed by a single Thief (thread) at any one
* time. A Mutex lock is used to prevent more than one Thief taking a bean simultaneously.
*/
public class Jar {
/**
* The lock which must be acquired to access the beans resource.
*/
private final Lock lock;
/**
* The resource within the jar.
*/
private int beans;
public Jar(int beans, Lock lock) {
this.beans = beans;
this.lock = lock;
}
/**
* Method for a thief to take a bean.
*/
public boolean takeBean() {
var success = false;
try {
lock.acquire();
success = beans > 0;
if (success) {
beans = beans - 1;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.release();
}
return success;
}
}

View File

@@ -0,0 +1,35 @@
/*
* The MIT License
* Copyright © 2014-2019 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.mutex;
/**
* Lock is an interface for a lock which can be acquired and released.
*/
public interface Lock {
void acquire() throws InterruptedException;
void release();
}

View File

@@ -0,0 +1,67 @@
/*
* The MIT License
* Copyright © 2014-2019 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.mutex;
/**
* Mutex is an implementation of a mutual exclusion lock.
*/
public class Mutex implements Lock {
/**
* The current owner of the lock.
*/
private Object owner;
/**
* Returns the current owner of the Mutex, or null if available.
*/
public Object getOwner() {
return owner;
}
/**
* Method called by a thread to acquire the lock. If the lock has already been acquired this will
* wait until the lock has been released to re-attempt the acquire.
*/
@Override
public synchronized void acquire() throws InterruptedException {
while (owner != null) {
wait();
}
owner = Thread.currentThread();
}
/**
* Method called by a thread to release the lock.
*/
@Override
public synchronized void release() {
if (Thread.currentThread() == owner) {
owner = null;
notify();
}
}
}

View File

@@ -0,0 +1,67 @@
/*
* The MIT License
* Copyright © 2014-2019 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.mutex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Thief is a class which continually tries to acquire a jar and take a bean from it. When the jar
* is empty the thief stops.
*/
public class Thief extends Thread {
private static final Logger LOGGER = LoggerFactory.getLogger(Thief.class);
/**
* The name of the thief.
*/
private final String name;
/**
* The jar.
*/
private final Jar jar;
public Thief(String name, Jar jar) {
this.name = name;
this.jar = jar;
}
/**
* In the run method the thief repeatedly tries to take a bean until none are left.
*/
@Override
public void run() {
var beans = 0;
while (jar.takeBean()) {
beans = beans + 1;
LOGGER.info("{} took a bean.", name);
}
LOGGER.info("{} took {} beans.", name, beans);
}
}

View File

@@ -0,0 +1,39 @@
/*
* The MIT License
* Copyright © 2014-2019 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.mutex;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/**
* Application Test Entrypoint
*/
class AppTest {
@Test
void shouldExecuteApplicationWithoutException() {
assertDoesNotThrow(() -> App.main(new String[]{}));
}
}

View File

@@ -0,0 +1,45 @@
/*
* The MIT License
* Copyright © 2014-2019 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.mutex;
import static org.junit.jupiter.api.Assertions.assertFalse;
import java.util.stream.IntStream;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
/**
* Test case for taking beans from a Jar
*/
public class JarTest {
@Test
public void testTakeBeans() {
var mutex = new Mutex();
var jar = new Jar(10, mutex);
IntStream.range(0, 10).mapToObj(i -> jar.takeBean()).forEach(Assertions::assertTrue);
assertFalse(jar.takeBean());
}
}

View File

@@ -0,0 +1,51 @@
/*
* The MIT License
* Copyright © 2014-2019 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.mutex;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.fail;
import org.junit.jupiter.api.Test;
/**
* Test case for acquiring and releasing a Mutex
*/
public class MutexTest {
@Test
public void acquireReleaseTest() {
var mutex = new Mutex();
assertNull(mutex.getOwner());
try {
mutex.acquire();
assertEquals(mutex.getOwner(), Thread.currentThread());
} catch (InterruptedException e) {
fail(e.toString());
}
mutex.release();
assertNull(mutex.getOwner());
}
}

View File

@@ -25,7 +25,6 @@
<inceptionYear>2014-2019</inceptionYear>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<sonar-maven-plugin.version>3.8.0.2131</sonar-maven-plugin.version>
<hibernate.version>5.2.18.Final</hibernate.version>
<spring.version>5.0.13.RELEASE</spring.version>
<spring-boot.version>2.0.9.RELEASE</spring-boot.version>
@@ -142,6 +141,8 @@
<module>module</module>
<module>monad</module>
<module>mute-idiom</module>
<module>mutex</module>
<module>semaphore</module>
<module>hexagonal</module>
<module>abstract-document</module>
<module>aggregator-microservices</module>
@@ -426,7 +427,7 @@
<plugin>
<groupId>org.sonarsource.scanner.maven</groupId>
<artifactId>sonar-maven-plugin</artifactId>
<version>${sonar-maven-plugin.version}</version>
<version>3.7.0.1746</version>
</plugin>
</plugins>
</pluginManagement>

33
semaphore/README.md Normal file
View File

@@ -0,0 +1,33 @@
---
layout: pattern
title: Semaphore
folder: semaphore
permalink: /patterns/semaphore/
categories: Concurrency
tags:
- Performance
---
## Also known as
Counting Semaphore
## Intent
Create a lock which mediates access to a pool of resources.
Only a limited number of threads, specified at the creation
of the semaphore, can access the resources at any given time.
A semaphore which only allows one concurrent access to a resource
is called a binary semaphore.
## Class diagram
![alt text](./etc/semaphore.png "Semaphore")
## Applicability
Use a Semaphore when
* You have a pool of resources to allocate to different threads
* Concurrent access to a resource could lead to a race condition
## Credits
* [Semaphore(programming)] (http://en.wikipedia.org/wiki/Semaphore_(programming))
* [Semaphores] (http://tutorials.jenkov.com/java-concurrency/semaphores.html)

BIN
semaphore/etc/semaphore.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

View File

@@ -0,0 +1,56 @@
@startuml
package com.iluwatar.semaphore {
class App {
+ App()
+ main(args : String[]) {static}
}
class Fruit {
- type : FruitType
+ Fruit(type : FruitType)
+ getType() : FruitType
+ toString() : String
}
enum FruitType {
+ APPLE {static}
+ LEMON {static}
+ ORANGE {static}
+ valueOf(name : String) : FruitType {static}
+ values() : FruitType[] {static}
}
class FruitBowl {
- fruit : List<Fruit>
+ FruitBowl()
+ countFruit() : int
+ put(f : Fruit)
+ take() : Fruit
+ toString() : String
}
class FruitShop {
- available : boolean[]
- bowls : FruitBowl[]
- semaphore : Semaphore
+ FruitShop()
+ countFruit() : int
+ returnBowl(bowl : FruitBowl)
+ takeBowl() : FruitBowl
}
interface Lock {
+ acquire() {abstract}
+ release() {abstract}
}
class Semaphore {
- counter : int
- licenses : int
+ Semaphore(licenses : int)
+ acquire()
+ getAvailableLicenses() : int
+ getNumLicenses() : int
+ release()
}
}
FruitType ..+ Fruit
Fruit --> "-type" FruitType
FruitShop --> "-semaphore" Semaphore
FruitBowl --> "-fruit" Fruit
Semaphore ..|> Lock
@enduml

61
semaphore/pom.xml Normal file
View File

@@ -0,0 +1,61 @@
<?xml version="1.0"?>
<!--
The MIT License
Copyright © 2014-2019 Ilkka Seppälä
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-->
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.iluwatar</groupId>
<artifactId>java-design-patterns</artifactId>
<version>1.24.0-SNAPSHOT</version>
</parent>
<artifactId>semaphore</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.semaphore.App</mainClass>
</manifest>
</archive>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@@ -0,0 +1,50 @@
/*
* The MIT License
* Copyright © 2014-2019 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.semaphore;
/**
* A Semaphore mediates access by a group of threads to a pool of resources.
*
* <p>In this example a group of customers are taking fruit from a fruit shop. There is a bowl each
* of apples, oranges and lemons. Only one customer can access a bowl simultaneously. A Semaphore is
* used to indicate how many resources are currently available and must be acquired in order for a
* bowl to be given to a customer. Customers continually try to take fruit until there is no fruit
* left in the shop.
*/
public class App {
/**
* main method.
*/
public static void main(String[] args) {
var shop = new FruitShop();
new Customer("Peter", shop).start();
new Customer("Paul", shop).start();
new Customer("Mary", shop).start();
new Customer("John", shop).start();
new Customer("Ringo", shop).start();
new Customer("George", shop).start();
}
}

View File

@@ -0,0 +1,82 @@
/*
* The MIT License
* Copyright © 2014-2019 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.semaphore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A Customer attempts to repeatedly take Fruit from the FruitShop by taking Fruit from FruitBowl
* instances.
*/
public class Customer extends Thread {
private static final Logger LOGGER = LoggerFactory.getLogger(Customer.class);
/**
* Name of the Customer.
*/
private final String name;
/**
* The FruitShop he is using.
*/
private final FruitShop fruitShop;
/**
* Their bowl of Fruit.
*/
private final FruitBowl fruitBowl;
/**
* Customer constructor.
*/
public Customer(String name, FruitShop fruitShop) {
this.name = name;
this.fruitShop = fruitShop;
this.fruitBowl = new FruitBowl();
}
/**
* The Customer repeatedly takes Fruit from the FruitShop until no Fruit remains.
*/
public void run() {
while (fruitShop.countFruit() > 0) {
var bowl = fruitShop.takeBowl();
if (bowl != null) {
var fruit = bowl.take();
if (fruit != null) {
LOGGER.info("{} took an {}", name, fruit);
fruitBowl.put(fruit);
fruitShop.returnBowl(bowl);
}
}
}
LOGGER.info("{} took {}", name, fruitBowl);
}
}

View File

@@ -0,0 +1,64 @@
/*
* The MIT License
* Copyright © 2014-2019 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.semaphore;
/**
* Fruit is a resource stored in a FruitBowl.
*/
public class Fruit {
/**
* Enumeration of Fruit Types.
*/
public enum FruitType {
ORANGE, APPLE, LEMON
}
private final FruitType type;
public Fruit(FruitType type) {
this.type = type;
}
public FruitType getType() {
return type;
}
/**
* toString method.
*/
public String toString() {
switch (type) {
case ORANGE:
return "Orange";
case APPLE:
return "Apple";
case LEMON:
return "Lemon";
default:
return "";
}
}
}

View File

@@ -0,0 +1,92 @@
/*
* The MIT License
* Copyright © 2014-2019 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.semaphore;
import java.util.ArrayList;
import java.util.List;
/**
* A FruitBowl contains Fruit.
*/
public class FruitBowl {
private final List<Fruit> fruit = new ArrayList<>();
/**
* Returns the amount of fruits left in bowl.
*
* @return The amount of Fruit left in the bowl.
*/
public int countFruit() {
return fruit.size();
}
/**
* Put an item of Fruit into the bowl.
*
* @param f fruit
*/
public void put(Fruit f) {
fruit.add(f);
}
/**
* Take an item of Fruit out of the bowl.
*
* @return The Fruit taken out of the bowl, or null if empty.
*/
public Fruit take() {
if (fruit.isEmpty()) {
return null;
} else {
return fruit.remove(0);
}
}
/**
* toString method.
*/
public String toString() {
var apples = 0;
var oranges = 0;
var lemons = 0;
for (var f : fruit) {
switch (f.getType()) {
case APPLE:
apples++;
break;
case ORANGE:
oranges++;
break;
case LEMON:
lemons++;
break;
default:
}
}
return apples + " Apples, " + oranges + " Oranges, and " + lemons + " Lemons";
}
}

View File

@@ -0,0 +1,120 @@
/*
* The MIT License
* Copyright © 2014-2019 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.semaphore;
/**
* A FruitShop contains three FruitBowl instances and controls access to them.
*/
public class FruitShop {
/**
* The FruitBowl instances stored in the class.
*/
private final FruitBowl[] bowls = {
new FruitBowl(),
new FruitBowl(),
new FruitBowl()
};
/**
* Access flags for each of the FruitBowl instances.
*/
private final boolean[] available = {
true,
true,
true
};
/**
* The Semaphore that controls access to the class resources.
*/
private final Semaphore semaphore;
/**
* FruitShop constructor.
*/
public FruitShop() {
for (var i = 0; i < 100; i++) {
bowls[0].put(new Fruit(Fruit.FruitType.APPLE));
bowls[1].put(new Fruit(Fruit.FruitType.ORANGE));
bowls[2].put(new Fruit(Fruit.FruitType.LEMON));
}
semaphore = new Semaphore(3);
}
/**
* Returns the amount of fruits left in shop.
*
* @return The amount of Fruit left in the shop.
*/
public synchronized int countFruit() {
return bowls[0].countFruit() + bowls[1].countFruit() + bowls[2].countFruit();
}
/**
* Method called by Customer to get a FruitBowl from the shop. This method will try to acquire the
* Semaphore before returning the first available FruitBowl.
*/
public synchronized FruitBowl takeBowl() {
FruitBowl bowl = null;
try {
semaphore.acquire();
if (available[0]) {
bowl = bowls[0];
available[0] = false;
} else if (available[1]) {
bowl = bowls[1];
available[1] = false;
} else if (available[2]) {
bowl = bowls[2];
available[2] = false;
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
semaphore.release();
}
return bowl;
}
/**
* Method called by a Customer instance to return a FruitBowl to the shop. This method releases
* the Semaphore, making the FruitBowl available to another Customer.
*/
public synchronized void returnBowl(FruitBowl bowl) {
if (bowl == bowls[0]) {
available[0] = true;
} else if (bowl == bowls[1]) {
available[1] = true;
} else if (bowl == bowls[2]) {
available[2] = true;
}
}
}

View File

@@ -0,0 +1,35 @@
/*
* The MIT License
* Copyright © 2014-2019 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.semaphore;
/**
* Lock is an interface for a lock which can be acquired and released.
*/
public interface Lock {
void acquire() throws InterruptedException;
void release();
}

View File

@@ -0,0 +1,77 @@
/*
* The MIT License
* Copyright © 2014-2019 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.semaphore;
/**
* Semaphore is an implementation of a semaphore lock.
*/
public class Semaphore implements Lock {
private final int licenses;
/**
* The number of concurrent resource accesses which are allowed.
*/
private int counter;
public Semaphore(int licenses) {
this.licenses = licenses;
this.counter = licenses;
}
/**
* Returns the number of licenses managed by the Semaphore.
*/
public int getNumLicenses() {
return licenses;
}
/**
* Returns the number of available licenses.
*/
public int getAvailableLicenses() {
return counter;
}
/**
* Method called by a thread to acquire the lock. If there are no resources available this will
* wait until the lock has been released to re-attempt the acquire.
*/
public synchronized void acquire() throws InterruptedException {
while (counter == 0) {
wait();
}
counter = counter - 1;
}
/**
* Method called by a thread to release the lock.
*/
public synchronized void release() {
if (counter < licenses) {
counter = counter + 1;
notify();
}
}
}

View File

@@ -0,0 +1,39 @@
/*
* The MIT License
* Copyright © 2014-2019 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.semaphore;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/**
* Application Test Entrypoint
*/
class AppTest {
@Test
void shouldExecuteWithoutException() {
assertDoesNotThrow(() -> App.main(new String[]{}));
}
}

View File

@@ -0,0 +1,55 @@
/*
* The MIT License
* Copyright © 2014-2019 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.semaphore;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import org.junit.jupiter.api.Test;
/**
* Test taking from and putting Fruit into a FruitBowl
*/
public class FruitBowlTest {
@Test
public void fruitBowlTest() {
var fbowl = new FruitBowl();
assertEquals(0, fbowl.countFruit());
for (var i = 1; i <= 10; i++) {
fbowl.put(new Fruit(Fruit.FruitType.LEMON));
assertEquals(i, fbowl.countFruit());
}
for (var i = 9; i >= 0; i--) {
assertNotNull(fbowl.take());
assertEquals(i, fbowl.countFruit());
}
assertNull(fbowl.take());
}
}

View File

@@ -0,0 +1,59 @@
/*
* The MIT License
* Copyright © 2014-2019 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.semaphore;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
import org.junit.jupiter.api.Test;
/**
* Test case for acquiring and releasing a Semaphore
*/
public class SemaphoreTest {
@Test
public void acquireReleaseTest() {
var sphore = new Semaphore(3);
assertEquals(3, sphore.getAvailableLicenses());
for (var i = 2; i >= 0; i--) {
try {
sphore.acquire();
assertEquals(i, sphore.getAvailableLicenses());
} catch (InterruptedException e) {
fail(e.toString());
}
}
for (var i = 1; i <= 3; i++) {
sphore.release();
assertEquals(i, sphore.getAvailableLicenses());
}
sphore.release();
assertEquals(3, sphore.getAvailableLicenses());
}
}

View File

@@ -23,7 +23,7 @@
package com.iluwatar.spatialpartition;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Random;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -44,11 +44,11 @@ import org.slf4j.LoggerFactory;
* <b>{@link Rect}</b> class to define the boundary of the quadtree. We use an abstract class
* <b>{@link Point}</b>
* with x and y coordinate fields and also an id field so that it can easily be put and looked up in
* the hashmap. This class has abstract methods to define how the object moves (move()), when to
* the hashtable. This class has abstract methods to define how the object moves (move()), when to
* check for collision with any object (touches(obj)) and how to handle collision
* (handleCollision(obj)), and will be extended by any object whose position has to be kept track of
* in the quadtree. The <b>{@link SpatialPartitionGeneric}</b> abstract class has 2 fields - a
* hashmap containing all objects (we use hashmap for faster lookups, insertion and deletion)
* hashtable containing all objects (we use hashtable for faster lookups, insertion and deletion)
* and a quadtree, and contains an abstract method which defines how to handle interactions between
* objects using the quadtree.</p>
* <p>Using the quadtree data structure will reduce the time complexity of finding the objects
@@ -61,7 +61,7 @@ public class App {
private static final Logger LOGGER = LoggerFactory.getLogger(App.class);
private static final String BUBBLE = "Bubble ";
static void noSpatialPartition(int numOfMovements, HashMap<Integer, Bubble> bubbles) {
static void noSpatialPartition(int numOfMovements, Hashtable<Integer, Bubble> bubbles) {
//all bubbles have to be checked for collision for all bubbles
var bubblesToCheck = bubbles.values();
@@ -81,9 +81,9 @@ public class App {
}
static void withSpatialPartition(
int height, int width, int numOfMovements, HashMap<Integer, Bubble> bubbles) {
int height, int width, int numOfMovements, Hashtable<Integer, Bubble> bubbles) {
//creating quadtree
var rect = new Rect(width / 2D, height / 2D, width, height);
var rect = new Rect(width / 2, height / 2, width, height);
var quadTree = new QuadTree(rect, 4);
//will run numOfMovement times or till all bubbles have popped
@@ -110,15 +110,15 @@ public class App {
*/
public static void main(String[] args) {
var bubbles1 = new HashMap<Integer, Bubble>();
var bubbles2 = new HashMap<Integer, Bubble>();
var bubbles1 = new Hashtable<Integer, Bubble>();
var bubbles2 = new Hashtable<Integer, Bubble>();
var rand = new Random();
for (int i = 0; i < 10000; i++) {
var b = new Bubble(rand.nextInt(300), rand.nextInt(300), i, rand.nextInt(2) + 1);
bubbles1.put(i, b);
bubbles2.put(i, b);
LOGGER.info(BUBBLE, i, " with radius ", b.radius,
" added at (", b.coordinateX, ",", b.coordinateY + ")");
LOGGER.info(BUBBLE + i + " with radius " + b.radius
+ " added at (" + b.coordinateX + "," + b.coordinateY + ")");
}
var start1 = System.currentTimeMillis();
@@ -127,8 +127,8 @@ public class App {
var start2 = System.currentTimeMillis();
App.withSpatialPartition(300, 300, 20, bubbles2);
var end2 = System.currentTimeMillis();
LOGGER.info("Without spatial partition takes ", (end1 - start1), "ms");
LOGGER.info("With spatial partition takes ", (end2 - start2), "ms");
LOGGER.info("Without spatial partition takes " + (end1 - start1) + "ms");
LOGGER.info("With spatial partition takes " + (end2 - start2) + "ms");
}
}

View File

@@ -24,7 +24,7 @@
package com.iluwatar.spatialpartition;
import java.util.Collection;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Random;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -58,13 +58,13 @@ public class Bubble extends Point<Bubble> {
<= (this.radius + b.radius) * (this.radius + b.radius);
}
void pop(HashMap<Integer, Bubble> allBubbles) {
LOGGER.info("Bubble ", this.id,
" popped at (", this.coordinateX, ",", this.coordinateY, ")!");
void pop(Hashtable<Integer, Bubble> allBubbles) {
LOGGER.info("Bubble " + this.id
+ " popped at (" + this.coordinateX + "," + this.coordinateY + ")!");
allBubbles.remove(this.id);
}
void handleCollision(Collection<? extends Point> toCheck, HashMap<Integer, Bubble> allBubbles) {
void handleCollision(Collection<? extends Point> toCheck, Hashtable<Integer, Bubble> allBubbles) {
var toBePopped = false; //if any other bubble collides with it, made true
for (var point : toCheck) {
var otherId = point.id;

View File

@@ -24,7 +24,7 @@
package com.iluwatar.spatialpartition;
import java.util.Collection;
import java.util.HashMap;
import java.util.Hashtable;
/**
* The abstract Point class which will be extended by any object in the field whose location has to
@@ -64,5 +64,5 @@ public abstract class Point<T> {
* @param toCheck contains the objects which need to be checked
* @param all contains hashtable of all points on field at this time
*/
abstract void handleCollision(Collection<? extends Point> toCheck, HashMap<Integer, T> all);
abstract void handleCollision(Collection<? extends Point> toCheck, Hashtable<Integer, T> all);
}

View File

@@ -24,7 +24,7 @@
package com.iluwatar.spatialpartition;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
/**
* This class extends the generic SpatialPartition abstract class and is used in our example to keep
@@ -33,10 +33,10 @@ import java.util.HashMap;
public class SpatialPartitionBubbles extends SpatialPartitionGeneric<Bubble> {
private final HashMap<Integer, Bubble> bubbles;
private final Hashtable<Integer, Bubble> bubbles;
private final QuadTree quadTree;
SpatialPartitionBubbles(HashMap<Integer, Bubble> bubbles, QuadTree quadTree) {
SpatialPartitionBubbles(Hashtable<Integer, Bubble> bubbles, QuadTree quadTree) {
this.bubbles = bubbles;
this.quadTree = quadTree;
}
@@ -44,7 +44,7 @@ public class SpatialPartitionBubbles extends SpatialPartitionGeneric<Bubble> {
void handleCollisionsUsingQt(Bubble b) {
// finding points within area of a square drawn with centre same as
// centre of bubble and length = radius of bubble
var rect = new Rect(b.coordinateX, b.coordinateY, 2D * b.radius, 2D * b.radius);
var rect = new Rect(b.coordinateX, b.coordinateY, 2 * b.radius, 2 * b.radius);
var quadTreeQueryResult = new ArrayList<Point>();
this.quadTree.query(rect, quadTreeQueryResult);
//handling these collisions

View File

@@ -29,7 +29,7 @@ import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import org.junit.jupiter.api.Test;
/**
@@ -63,11 +63,11 @@ class BubbleTest {
void popTest() {
var b1 = new Bubble(10, 10, 1, 2);
var b2 = new Bubble(0, 0, 2, 2);
var bubbles = new HashMap<Integer, Bubble>();
var bubbles = new Hashtable<Integer, Bubble>();
bubbles.put(1, b1);
bubbles.put(2, b2);
b1.pop(bubbles);
//after popping, bubble no longer in hashMap containing all bubbles
//after popping, bubble no longer in hashtable containing all bubbles
assertNull(bubbles.get(1));
assertNotNull(bubbles.get(2));
}
@@ -77,7 +77,7 @@ class BubbleTest {
var b1 = new Bubble(0, 0, 1, 2);
var b2 = new Bubble(1, 1, 2, 1);
var b3 = new Bubble(10, 10, 3, 1);
var bubbles = new HashMap<Integer, Bubble>();
var bubbles = new Hashtable<Integer, Bubble>();
bubbles.put(1, b1);
bubbles.put(2, b2);
bubbles.put(3, b3);

View File

@@ -26,7 +26,7 @@ package com.iluwatar.spatialpartition;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import java.util.HashMap;
import java.util.Hashtable;
import org.junit.jupiter.api.Test;
/**
@@ -41,7 +41,7 @@ class SpatialPartitionBubblesTest {
var b2 = new Bubble(5, 5, 2, 1);
var b3 = new Bubble(9, 9, 3, 1);
var b4 = new Bubble(8, 8, 4, 2);
var bubbles = new HashMap<Integer, Bubble>();
var bubbles = new Hashtable<Integer, Bubble>();
bubbles.put(1, b1);
bubbles.put(2, b2);
bubbles.put(3, b3);

View File

@@ -38,13 +38,16 @@ public class Db {
*
* @return singleton instance of Db class
*/
public static synchronized Db getInstance() {
public static Db getInstance() {
if (instance == null) {
Db newInstance = new Db();
newInstance.userName2User = new HashMap<>();
newInstance.user2Account = new HashMap<>();
newInstance.itemName2Product = new HashMap<>();
instance = newInstance;
synchronized (Db.class) {
if (instance == null) {
instance = new Db();
instance.userName2User = new HashMap<>();
instance.user2Account = new HashMap<>();
instance.itemName2Product = new HashMap<>();
}
}
}
return instance;
}

View File

@@ -38,9 +38,13 @@ public class MaintenanceLock {
*
* @return singleton instance of MaintenanceLock
*/
public static synchronized MaintenanceLock getInstance() {
public static MaintenanceLock getInstance() {
if (instance == null) {
instance = new MaintenanceLock();
synchronized (MaintenanceLock.class) {
if (instance == null) {
instance = new MaintenanceLock();
}
}
}
return instance;
}
@@ -51,6 +55,6 @@ public class MaintenanceLock {
public void setLock(boolean lock) {
this.lock = lock;
LOGGER.info("Maintenance lock is set to: ", lock);
LOGGER.info("Maintenance lock is set to: " + lock);
}
}

View File

@@ -49,7 +49,7 @@ public class HotelDaoImpl implements HotelDao {
public Stream<Room> getAll() throws Exception {
try {
var connection = getConnection();
var statement = connection.prepareStatement("SELECT * FROM ROOMS"); // NOSONAR
var statement = connection.prepareStatement("SELECT * FROM ROOMS");
var resultSet = statement.executeQuery(); // NOSONAR
return StreamSupport.stream(new Spliterators.AbstractSpliterator<Room>(Long.MAX_VALUE,
Spliterator.ORDERED) {