From 66538ddcdad120deb86c580164ca7c4f3bdb7b3a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ilkka=20Sepp=C3=A4l=C3=A4?= Date: Tue, 9 Apr 2024 21:02:36 +0300 Subject: [PATCH] docs: update Dirty Flag docs (#2908) --- dirty-flag/README.md | 129 ++++++++++++++++-- .../com/iluwatar/dirtyflag/DataFetcher.java | 8 +- dirty-flag/src/main/resources/world.txt | 23 ---- .../src/test/java/org/dirty/flag/AppTest.java | 1 - 4 files changed, 125 insertions(+), 36 deletions(-) diff --git a/dirty-flag/README.md b/dirty-flag/README.md index 5eb6c052b..275ee9fd0 100644 --- a/dirty-flag/README.md +++ b/dirty-flag/README.md @@ -3,26 +3,139 @@ title: Dirty Flag category: Behavioral language: en tag: - - Game programming - - Performance + - Game programming + - Performance + - Resource management + - State tracking --- ## Also known as -* IsDirty pattern + +* Change Tracking +* Is-Modified Flag ## Intent -To avoid expensive re-acquisition of resources. The resources retain their identity, are kept in some -fast-access storage, and are re-used to avoid having to acquire them again. + +The Dirty Flag design pattern is employed to avoid unnecessary computations or resource-heavy operations by maintaining a boolean flag that tracks whether the state of an object has changed ('dirty') or remains unchanged ('clean'). This flag, when set, indicates that a particular operation, such as recalculating or refreshing data, needs to be performed again to reflect the updated state. + +## Explanation + +Real world example + +> Imagine a library with an electronic catalog system that tracks which books are checked out and returned. Each book record has a "dirty flag" that gets marked whenever a book is checked out or returned. At the end of each day, the library staff reviews only those records marked as "dirty" to update the physical inventory, instead of checking every single book in the library. This system significantly reduces the effort and time required for daily inventory checks by focusing only on the items that have changed status, analogous to how the Dirty Flag design pattern minimizes resource-intensive operations by performing them only when necessary. + +In plain words + +> The Dirty Flag design pattern minimizes unnecessary operations by using a flag to track when an object's state has changed and an update is needed. + +Wikipedia says + +> A dirty bit or modified bit is a bit that is associated with a block of computer memory and indicates whether the corresponding block of memory has been modified. The dirty bit is set when the processor writes to (modifies) this memory. The bit indicates that its associated block of memory has been modified and has not been saved to storage yet. When a block of memory is to be replaced, its corresponding dirty bit is checked to see if the block needs to be written back to secondary memory before being replaced or if it can simply be removed. Dirty bits are used by the CPU cache and in the page replacement algorithms of an operating system. + +**Programmatic Example** + +The DataFetcher class is responsible for fetching data from a file. It has a dirty flag that indicates whether the data in the file has changed since the last fetch. + +```java +public class DataFetcher { +private long lastFetched; +private boolean isDirty = true; +// ... +} +``` + +The DataFetcher class has a fetch method that checks the dirty flag before fetching data. If the flag is true, it fetches the data from the file and sets the flag to false. If the flag is false, it returns the previously fetched data. + +```java +public List fetch() { + if (!isDirty) { + return data; + } + data = fetchFromDatabase(); + isDirty = false; + return data; +} +``` + +The World class uses the DataFetcher to fetch data. It has a fetch method that calls the fetch method of the DataFetcher. + +```java +public class World { + private final DataFetcher fetcher = new DataFetcher(); + + public List fetch() { + return fetcher.fetch(); + } +} +``` + +The App class contains the main method that demonstrates the use of the Dirty Flag pattern. It creates a World object and fetches data from it in a loop. The World object uses the DataFetcher to fetch data, and the DataFetcher only fetches data from the file if the dirty flag is true. + +```java +public class App { + public void run() { + final var executorService = Executors.newSingleThreadScheduledExecutor(); + executorService.scheduleAtFixedRate(new Runnable() { + final World world = new World(); + + @Override + public void run() { + var countries = world.fetch(); + // ... + } + }, 0, 15, TimeUnit.SECONDS); // Run at every 15 seconds. + } +} +``` + +The program output is as follows: + +``` +20:51:42.490 [pool-1-thread-1] INFO com.iluwatar.dirtyflag.DataFetcher -- world.txt is dirty! Re-fetching file content... +20:51:42.494 [pool-1-thread-1] INFO com.iluwatar.dirtyflag.App -- Our world currently has the following countries:- +20:51:42.494 [pool-1-thread-1] INFO com.iluwatar.dirtyflag.App -- UNITED_KINGDOM +20:51:42.494 [pool-1-thread-1] INFO com.iluwatar.dirtyflag.App -- MALAYSIA +20:51:42.494 [pool-1-thread-1] INFO com.iluwatar.dirtyflag.App -- UNITED_STATES +``` ## Class diagram -![alt text](./etc/dirty-flag.png "Dirty Flag") + +![Dirty Flag](./etc/dirty-flag.png "Dirty Flag") ## Applicability -Use the Dirty Flag pattern when -* Repetitious acquisition, initialization, and release of the same resource causes unnecessary performance overhead. +* When an operation is resource-intensive and only necessary after certain changes have occurred. +* In scenarios where checking for changes is significantly cheaper than performing the operation itself. +* Within systems where objects maintain state that is expensive to update and the updates are infrequent. + +## Known Uses + +* Graphic rendering engines to update only parts of the scene that have changed. +* Web applications for partial page rendering or caching strategies. +* Database applications for tracking changes in datasets to minimize write operations. + +## Consequences + +Benefits: + +* Reduces computational and resource overhead by avoiding unnecessary operations. +* Can significantly improve performance in systems where operations are costly and changes are infrequent. +* Simplifies the decision-making process about when to perform certain operations. + +Trade-offs: + +* Introduces complexity by adding state management responsibility to the system. +* Requires diligent management of the flag to ensure it accurately reflects the state changes, avoiding stale or incorrect data. +* Potentially increases the risk of bugs related to improper flag resetting. + +## Related Patterns + +* [Observer](https://java-design-patterns.com/patterns/observer/): Can be used in conjunction to notify interested parties when the dirty flag is set or cleared. +* [Memento](https://java-design-patterns.com/patterns/memento/): Useful for storing the previous state of an object, which can work hand in hand with dirty flag logic to revert to clean states. +* [Command](https://java-design-patterns.com/patterns/command/): Commands can set the dirty flag when executed, indicating a change in state that requires attention. ## Credits +* [Game Programming Patterns](https://amzn.to/3PUzbgu) * [Design Patterns: Dirty Flag](https://www.takeupcode.com/podcast/89-design-patterns-dirty-flag/) * [J2EE Design Patterns](https://www.amazon.com/gp/product/0596004273/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596004273&linkCode=as2&tag=javadesignpat-20&linkId=48d37c67fb3d845b802fa9b619ad8f31) diff --git a/dirty-flag/src/main/java/com/iluwatar/dirtyflag/DataFetcher.java b/dirty-flag/src/main/java/com/iluwatar/dirtyflag/DataFetcher.java index 81bd3b48a..7f8760fd5 100644 --- a/dirty-flag/src/main/java/com/iluwatar/dirtyflag/DataFetcher.java +++ b/dirty-flag/src/main/java/com/iluwatar/dirtyflag/DataFetcher.java @@ -40,7 +40,7 @@ import lombok.extern.slf4j.Slf4j; @Slf4j public class DataFetcher { - private final String filename = "world.txt"; + private static final String FILENAME = "world.txt"; private long lastFetched; public DataFetcher() { @@ -62,14 +62,14 @@ public class DataFetcher { */ public List fetch() { var classLoader = getClass().getClassLoader(); - var file = new File(classLoader.getResource(filename).getFile()); + var file = new File(classLoader.getResource(FILENAME).getFile()); if (isDirty(file.lastModified())) { - LOGGER.info(filename + " is dirty! Re-fetching file content..."); + LOGGER.info(FILENAME + " is dirty! Re-fetching file content..."); try (var br = new BufferedReader(new FileReader(file))) { return br.lines().collect(Collectors.collectingAndThen(Collectors.toList(), List::copyOf)); } catch (IOException e) { - e.printStackTrace(); + LOGGER.error("An error occurred: ", e); } } diff --git a/dirty-flag/src/main/resources/world.txt b/dirty-flag/src/main/resources/world.txt index 0c25bc5c5..280ea3702 100644 --- a/dirty-flag/src/main/resources/world.txt +++ b/dirty-flag/src/main/resources/world.txt @@ -1,26 +1,3 @@ -==== - The MIT License - Copyright © 2014-2021 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. -==== - UNITED_KINGDOM MALAYSIA UNITED_STATES \ No newline at end of file diff --git a/dirty-flag/src/test/java/org/dirty/flag/AppTest.java b/dirty-flag/src/test/java/org/dirty/flag/AppTest.java index c2d3f86ae..8dc52ea44 100644 --- a/dirty-flag/src/test/java/org/dirty/flag/AppTest.java +++ b/dirty-flag/src/test/java/org/dirty/flag/AppTest.java @@ -36,7 +36,6 @@ class AppTest { /** * Issue: Add at least one assertion to this test case. - * * Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])} * throws an exception. */