<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Asatryan Manuk on Medium]]></title>
        <description><![CDATA[Stories by Asatryan Manuk on Medium]]></description>
        <link>https://medium.com/@asatryanmanuk2000?source=rss-75a8f9cbc05d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*G4ipyZsXOxu0dq9QJ59cyQ.jpeg</url>
            <title>Stories by Asatryan Manuk on Medium</title>
            <link>https://medium.com/@asatryanmanuk2000?source=rss-75a8f9cbc05d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 12:06:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@asatryanmanuk2000/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[5 Library Architecture Patterns Every Java/Microservices Engineer Should Know]]></title>
            <link>https://medium.com/@asatryanmanuk2000/doctype-html-dbdbcf05e583?source=rss-75a8f9cbc05d------2</link>
            <guid isPermaLink="false">https://medium.com/p/dbdbcf05e583</guid>
            <dc:creator><![CDATA[Asatryan Manuk]]></dc:creator>
            <pubDate>Sun, 03 May 2026 12:35:10 GMT</pubDate>
            <atom:updated>2026-05-03T12:38:48.403Z</atom:updated>
            <content:encoded><![CDATA[<p>Feature-Based vs. Layered vs. API/SPI vs. Core + Extensions vs. Micro-Library — when to use each, when to avoid them, and which famous libraries got it right.</p><p>By <strong>Manuk Asatryan</strong> · 12 min read</p><p><strong>TL;DR</strong> — If you’re building an internal Java microservices library, you almost always want a hybrid: a <em>Core + Feature Extensions</em> layout, with an <em>API/SPI split</em> on anything that might swap providers (storage, messaging, identity). Avoid the “commons-everything” kitchen sink.</p><p>Every team eventually hits the same question: <em>how do we organize our shared code?</em> Do we put everything into one big commons module, split it by feature, split it by layer, or go full plugin-architecture?</p><p>Each answer is a real architectural pattern, with real trade-offs, and there are famous open-source libraries that have lived with each choice for over a decade. This article walks through the five most important patterns, with concrete examples and clear guidance on <strong>when to use them</strong> — and, just as importantly, <strong>when not to</strong>.</p><h3>1. The Feature-Based Strategy</h3><h3>What is it?</h3><p>In this architecture, the repository is partitioned <strong>vertically</strong> by domain, service, or business capability. Each module is designed to do exactly one thing end-to-end. There is no sharing of heavy underlying engines; if a module needs an external dependency, it declares it privately so that other modules are unaffected.</p><h3>Famous Libraries Using This Approach</h3><h4>AWS SDK for Java (v2)</h4><p><strong>GitHub:</strong> <a href="https://github.com/aws/aws-sdk-java-v2">aws/aws-sdk-java-v2</a></p><pre>aws-sdk-java-v2/<br>├── services/<br>│   ├── s3/                 # Feature: S3 file storage capabilities<br>│   ├── dynamodb/           # Feature: DynamoDB database capabilities<br>│   ├── sqs/                # Feature: Simple Queue Service capabilities<br>│   └── lambda/             # Feature: Serverless function capabilities</pre><h4>Google Cloud Java Client</h4><p><strong>GitHub:</strong> <a href="https://github.com/googleapis/google-cloud-java">googleapis/google-cloud-java</a></p><pre>google-cloud-java/<br>├── java-storage/           # Feature: Cloud Storage (blobs/files)<br>├── java-pubsub/            # Feature: Cloud Pub/Sub (messaging)<br>├── java-spanner/           # Feature: Cloud Spanner (relational DB)<br>└── java-vision/            # Feature: Cloud Vision AI</pre><h4>Testcontainers (Java)</h4><p><strong>GitHub:</strong> <a href="https://github.com/testcontainers/testcontainers-java">testcontainers/testcontainers-java</a></p><pre>testcontainers-java/<br>├── modules/<br>│   ├── postgresql/         # Feature: Postgres database container testing<br>│   ├── kafka/              # Feature: Kafka messaging container testing<br>│   ├── mongodb/            # Feature: Mongo database container testing<br>│   └── localstack/         # Feature: AWS LocalStack container testing</pre><h3>When to Use It</h3><ul><li><strong>Heavy, isolated integrations.</strong> If your library integrates with external systems (AWS S3, Redis, Stripe, Kafka), these belong in feature modules.</li><li><strong>Microservices with vastly different needs.</strong> If Service A needs S3 uploads but Service B only needs to publish to Kafka, they shouldn’t share dependencies.</li><li><strong>Strict dependency isolation.</strong> Prevents “dependency hell” where an upgrade to a JSON parser for the Kafka feature breaks the S3 feature.</li></ul><h3>When NOT to Use It</h3><ul><li><strong>Purely technical utilities.</strong> If you’re just writing StringUtils, DateUtils, or custom internal annotations without third-party SDKs, breaking them into feature modules is overkill.</li><li><strong>Heavily intertwined features.</strong> If your commons-s3 module frequently calls into commons-kafka, feature-based isolation will lead to circular dependency errors.</li><li><strong>No external dependencies.</strong> The primary benefit of this pattern is preventing dependency bloat. If your code is pure Java, the overhead of managing 15 different build files isn’t worth it.</li></ul><h3>2. The Horizontal / Layered Pattern</h3><h3>What is it?</h3><p>In this architecture, the repository is sliced <strong>horizontally</strong> by technical role, architectural layer, or execution phase rather than by what the code actually <em>does</em> for the business. You group files by what they <em>are</em> (annotations, low-level parsers, compile-time processors) instead of what feature they belong to.</p><h3>Famous Libraries Using This Approach</h3><h4>Jackson (JSON Processor)</h4><p><strong>GitHub:</strong> <a href="https://github.com/FasterXML">FasterXML/jackson</a> — Jackson splits these into separate repos under the same organization, but functionally they form a layered ecosystem.</p><pre>jackson/<br>├── jackson-annotations/    # Layer: Only @JsonProperty, @JsonIgnore (no logic)<br>├── jackson-core/           # Layer: The low-level streaming parser engine<br>└── jackson-databind/       # Layer: Maps JSON to Java Objects (depends on core)</pre><h4>JUnit 5</h4><p><strong>GitHub:</strong> <a href="https://github.com/junit-team/junit5">junit-team/junit5</a></p><pre>junit5/<br>├── junit-jupiter-api/      # Layer: The API developers use to write tests (@Test)<br>├── junit-platform-engine/  # Layer: The heavy JVM engine that executes the tests<br>└── junit-vintage-engine/   # Layer: Adapter layer for backwards compatibility</pre><h4>MapStruct (Java Bean Mapper)</h4><p><strong>GitHub:</strong> <a href="https://github.com/mapstruct/mapstruct">mapstruct/mapstruct</a></p><pre>mapstruct/<br>├── core/                   # Layer: The API and annotations (@Mapper, @Mapping)<br>└── processor/              # Layer: The annotation processor (compile-time only)</pre><h3>When to Use It</h3><ul><li><strong>Pure technical utilities.</strong> If your library is a tool (a JSON parser, a testing framework) rather than a collection of business integrations, layering separates the lightweight API from the heavy processing engine.</li><li><strong>Separating annotations from engines.</strong> If you build custom @ValidEmployee annotations, you want the annotation interface in an annotations layer and the validation logic in an implementation layer. This lets a microservice place the annotation on a DTO and share that DTO across the network without forcing the receiving service to download your validation engine.</li><li><strong>Compile-time vs. runtime.</strong> If you’re writing a Java Annotation Processor (like Lombok or MapStruct), the processor code must live in its own layer so it doesn’t get packaged into the final production container.</li></ul><h3>When NOT to Use It</h3><ul><li><strong>Organizing business features.</strong> Never create a commons-integrations layer that dumps S3, Redis, and Kafka logic into the same module just because they are all “integrations.”</li><li><strong>Avoiding dependency bloat.</strong> If a developer just wants commons-utils for a simple String helper, they shouldn’t be forced to download a massive module containing 50 unrelated utilities.</li><li><strong>The “Kitchen Sink” anti-pattern.</strong> Horizontal grouping often degenerates into a commons-core or commons-misc module that becomes a dumping ground for code nobody knows where else to put.</li></ul><h3>3. The API / Implementation Split (SPI Pattern)</h3><h3>What is it?</h3><p>SPI stands for <strong>Service Provider Interface</strong>. In this architecture, you strictly separate the <em>What</em> from the <em>How</em>.</p><p>You create an <strong>API module</strong> that contains only Java interfaces, basic DTOs, and custom exceptions. This module has zero logic and zero third-party dependencies. Then, you create one or more <strong>Implementation modules</strong> that contain the heavy code (like the AWS SDK) required to actually make those interfaces work.</p><p>The microservice only ever imports the API module during its core development, and the actual implementation is “plugged in” at runtime — usually via Spring DI or the Java ServiceLoader.</p><h3>Famous Libraries Using This Approach</h3><h4>SLF4J (Simple Logging Facade for Java)</h4><p><strong>GitHub:</strong> <a href="https://github.com/qos-ch/slf4j">qos-ch/slf4j</a></p><p><strong>Why:</strong> To allow developers to write logging code (log.info()) without locking themselves into a specific logging framework. The app developer chooses the engine (Logback, Log4j) at runtime.</p><pre>slf4j/<br>├── slf4j-api/              # THE API: Only the Logger interface (the &quot;What&quot;)<br>├── slf4j-simple/           # IMPLEMENTATION 1: A basic console logger (the &quot;How&quot;)<br>└── slf4j-jdk14/            # IMPLEMENTATION 2: Uses java.util.logging</pre><p>Third-party libraries like Logback act as additional implementations of slf4j-api.</p><h4>Micrometer (Metrics Collection)</h4><p><strong>GitHub:</strong> <a href="https://github.com/micrometer-metrics/micrometer">micrometer-metrics/micrometer</a></p><p><strong>Why:</strong> Micrometer is the default metrics engine for Spring Boot. It provides a generic API to record metrics, while different companies use different dashboards (Datadog, Prometheus, New Relic) to view them.</p><pre>micrometer/<br>├── micrometer-core/                   # THE API: MeterRegistry, Counter, Timer<br>├── micrometer-registry-prometheus/    # IMPL: Translates metrics to Prometheus<br>├── micrometer-registry-datadog/       # IMPL: Translates metrics to Datadog<br>└── micrometer-registry-dynatrace/     # IMPL: Translates metrics to Dynatrace</pre><h4>Jakarta Persistence (JPA) &amp; Hibernate</h4><p><strong>GitHub:</strong> <a href="https://github.com/jakartaee/persistence">jakartaee/persistence</a> (API) and <a href="https://github.com/hibernate/hibernate-orm">hibernate/hibernate-orm</a> (Implementation)</p><p><strong>Why:</strong> In enterprise Java, standards are defined first. Jakarta provides the interfaces (EntityManager), and vendors like Hibernate or EclipseLink provide the heavy engines.</p><pre>java-enterprise-ecosystem/<br>├── jakarta.persistence-api/  # THE API: Interfaces like @Entity, EntityManager<br>└── hibernate-core/           # IMPLEMENTATION: Reads the API and generates SQL</pre><h3>When to Use It</h3><ul><li><strong>To prevent vendor lock-in.</strong> If your company uses AWS S3 today but might migrate to Azure or on-premise MinIO, write an ImageStorageApi interface. When the vendor changes, you write a new implementation module — none of your microservices have to rewrite their core business logic.</li><li><strong>For local development &amp; testing.</strong> Create commons-s3-api, commons-s3-aws (production), and commons-s3-mock (in-memory) so developers don’t need real AWS credentials to run tests.</li><li><strong>Building an open-source framework.</strong> If you want third parties to write their own plugins for your library, you must publish a clean API module for them to implement.</li></ul><h3>When NOT to Use It</h3><ul><li><strong>You will never change the provider.</strong> If your company has a 10-year enterprise contract with AWS and you’re 100% certain you won’t switch, this pattern is largely a waste of time. It forces you to write extra interfaces for things that will only ever have one implementation.</li><li><strong>Simple, internal domain logic.</strong> Don’t create interfaces for basic internal data processing classes if there’s no scenario where that processing logic would be swapped out for a different “vendor.”</li></ul><h3>4. The Core + Feature Extensions Model</h3><h3>What is it?</h3><p>This is a <strong>hybrid architecture</strong>. You establish a strict, foundational <strong>core module</strong> with universally required logic — standard HTTP error responses, base entity classes, logging configurations, basic utilities — everything every microservice must have.</p><p>Then, you build <strong>extension modules</strong> (often called plugins or starters) that depend on the core. These extensions contain specific business capabilities or third-party SDKs (like AWS S3 or Kafka). Microservices import the core by default, then opt-in to the specific extensions they need.</p><h3>Famous Libraries Using This Approach</h3><h4>Spring Boot</h4><p><strong>GitHub:</strong> <a href="https://github.com/spring-projects/spring-boot">spring-projects/spring-boot</a></p><p><strong>Why:</strong> To guarantee every application has the same underlying engine and auto-configuration logic, while letting developers bolt on heavy features (web servers, databases) only when needed.</p><pre>spring-boot/<br>├── spring-boot-project/<br>│   ├── spring-boot/                  # THE CORE: Base classes, ApplicationContext<br>│   ├── spring-boot-autoconfigure/    # THE CORE: Engine that evaluates what to load<br>│   └── spring-boot-starters/         # THE EXTENSIONS:<br>│       ├── spring-boot-starter-web/      # Pulls in Tomcat &amp; REST features<br>│       └── spring-boot-starter-data-jpa/ # Pulls in Hibernate &amp; DB features</pre><h4>Hibernate ORM</h4><p><strong>GitHub:</strong> <a href="https://github.com/hibernate/hibernate-orm">hibernate/hibernate-orm</a></p><p><strong>Why:</strong> The SQL generation engine is mandatory for everyone, but specialized features like geographic coordinates or history auditing require massive external dependencies that most projects don’t need.</p><pre>hibernate-orm/<br>├── hibernate-core/         # THE CORE: Session management, ORM engine, SQL gen<br>├── hibernate-envers/       # EXTENSION: Entity auditing and history tracking<br>├── hibernate-spatial/      # EXTENSION: Geographic and location data features<br>└── hibernate-jcache/       # EXTENSION: Caching integrations</pre><h4>Retrofit (by Square)</h4><p><strong>GitHub:</strong> <a href="https://github.com/square/retrofit">square/retrofit</a></p><p><strong>Why:</strong> Retrofit handles HTTP cleanly but refuses to force a specific JSON parser (Gson or Jackson) on you. You import the core client and add the converter extension you prefer.</p><pre>retrofit/<br>├── retrofit/               # THE CORE: HTTP client interfaces and routing<br>├── retrofit-converters/    # EXTENSIONS (Serialization):<br>│   ├── gson/                   # Extension: Gson parsing integration<br>│   └── jackson/                # Extension: Jackson parsing integration<br>└── retrofit-adapters/      # EXTENSIONS (Reactive programming):<br>    └── rxjava3/                # Extension: RxJava support</pre><h3>When to Use It</h3><ul><li><strong>Building an internal company framework.</strong> This is the absolute best pattern for an internal microservices library. Your company-core handles standardization (JWT validation filters, ErrorResponse objects, trace IDs), and your extensions (company-s3, company-redis) provide heavy capabilities.</li><li><strong>When domains share common ground.</strong> If your S3 module and your Kafka module both throw a custom CompanyNetworkException, you need a shared core to house that exception so both modules can use it.</li><li><strong>Creating auto-configured starters.</strong> If you’re using Spring Boot, this is the pattern. Your core defines the logic, and your starter modules automatically wire it into the Spring context.</li></ul><h3>When NOT to Use It</h3><ul><li><strong>Highly independent tools.</strong> If you’re building a generic open-source library where modules do completely different things and share zero common logic, forcing them to depend on a central core creates artificial coupling.</li><li><strong>No shared baseline.</strong> If your microservices ecosystem is highly fragmented (different teams use completely different error handling and logging standards), a mandatory core module will cause massive friction across teams.</li></ul><h3>5. The Micro-Library (Extreme Granularity) Pattern</h3><h3>What is it?</h3><p>In this architecture, functionality is broken down to its <strong>absolute smallest viable unit</strong> — often a single class, a single component, or even a single function.</p><p>Instead of importing a commons-math module, you would import a commons-math-addition module. The goal is to ensure that a consumer downloads <em>zero dead code</em>. If they only need one function, they only download that one function.</p><blockquote>This pattern is extremely rare in Java backend development because Maven/Gradle and the JVM are not optimized to handle hundreds of tiny 2-kilobyte JAR files. However, it absolutely dominates the frontend JavaScript/Node.js ecosystem (NPM).</blockquote><h3>Famous Libraries Using This Approach</h3><h4>Lodash (JavaScript Utility Library)</h4><p><strong>GitHub:</strong> <a href="https://github.com/lodash/lodash">lodash/lodash</a></p><p><strong>Why:</strong> In frontend development, every kilobyte sent to a user’s browser slows the website. Lodash publishes hundreds of independent micro-packages so developers can use one helper function without downloading the entire library.</p><pre>lodash-ecosystem/<br>├── lodash.isequal/         # NPM Package: Only the deep-equals function<br>├── lodash.clone/           # NPM Package: Only the object cloning function<br>├── lodash.debounce/        # NPM Package: Only the debounce function<br>└── lodash.camelcase/       # NPM Package: Only the camelCase string function</pre><h4>date-fns (Modern JavaScript Date Utility)</h4><p><strong>GitHub:</strong> <a href="https://github.com/date-fns/date-fns">date-fns/date-fns</a></p><p><strong>Why:</strong> Built specifically as a micro-library alternative to the massive Moment.js. Every single date manipulation is its own isolated file/module.</p><pre>date-fns/<br>├── addDays/                # Module: Logic just to add days to a date<br>├── format/                 # Module: Logic just to format a date to a string<br>├── isAfter/                # Module: Logic just to compare two dates<br>└── parseISO/               # Module: Logic just to parse ISO strings</pre><h4>Babel (JavaScript Compiler)</h4><p><strong>GitHub:</strong> <a href="https://github.com/babel/babel">babel/babel</a></p><p><strong>Why:</strong> Babel translates modern code into older code that runs on legacy browsers. Because different browsers support different things, Babel breaks every single syntax translation into a tiny, isolated micro-plugin.</p><pre>babel/<br>├── packages/<br>│   ├── babel-plugin-transform-arrow-functions/  # Only translates &quot;() =&gt; {}&quot;<br>│   ├── babel-plugin-transform-classes/          # Only translates &quot;class X {}&quot;<br>│   └── babel-plugin-transform-for-of/           # Only translates &quot;for (let x of y)&quot;</pre><h3>When to Use It</h3><ul><li><strong>Frontend web development.</strong> If you’re building libraries for browsers (React, Vue, plain JS), this pattern is king. Tiny bundle sizes mean faster page loads.</li><li><strong>Strict independent versioning.</strong> If one algorithm updates rapidly and another never changes, splitting them into micro-libraries lets you release math-addition v5.0.0 while leaving math-subtraction at v1.0.0.</li><li><strong>When tree-shaking is unavailable.</strong> If your build tools cannot automatically detect and remove unused code, micro-libraries force developers to import only what they use.</li></ul><h3>When NOT to Use It (Especially in Java)</h3><ul><li><strong>Java / Spring Boot microservices.</strong> Don’t use this pattern for your Java backend. Maven and Gradle require a pom.xml or build.gradle for every module. Managing 40 build files for tiny utility classes is a massive waste of time. A 5MB JAR file makes virtually no difference to a backend server with gigabytes of RAM.</li><li><strong>To avoid “dependency hell.”</strong> If your microservice pom.xml requires 30 imports just to get basic utilities, it becomes unreadable and incredibly difficult to maintain.</li><li><strong>When cohesion is required.</strong> If you break a single business concept (like “S3 Storage”) into s3-upload, s3-download, and s3-presign, you destroy the logical grouping of the domain. Developers have to hunt across multiple repositories or modules to find related logic.</li></ul><h3>Choosing the Right Pattern</h3><p>If you’re still not sure which one fits your situation, here’s a quick decision shortcut:</p><ul><li>You’re wrapping <strong>multiple heavy SDKs</strong> (AWS, Stripe, Kafka)? → <strong>Feature-Based</strong>.</li><li>You’re building a <strong>technical tool</strong> (parser, mapper, test framework)? → <strong>Layered</strong>.</li><li>You might <strong>swap providers</strong> later (storage, identity, messaging)? → <strong>API/SPI Split</strong>.</li><li>You’re building an <strong>internal company framework</strong> for many microservices? → <strong>Core + Extensions</strong> (often combined with API/SPI for select capabilities).</li><li>You’re shipping code to <strong>browsers</strong> and bundle size matters? → <strong>Micro-Library</strong>.</li></ul><p>The most common mistake teams make is picking one pattern and applying it everywhere. The libraries you admire didn’t do that — Spring Boot is Core + Extensions, but inside it uses API/SPI for things like logging and metrics. Hibernate is Core + Extensions but consumes the JPA API. <em>Real systems mix patterns deliberately.</em></p><p>Pick the pattern that fits the problem in front of you, not the one that fits everything.</p><p><em>If you found this useful, consider following for more deep dives on Java, microservices, and backend architecture.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dbdbcf05e583" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Threads Decoded: Navigating java.util.concurrent.* Interfaces with Ease]]></title>
            <link>https://medium.com/@asatryanmanuk2000/java-threads-decoded-navigating-java-util-concurrent-interfaces-with-ease-935cb882bc8a?source=rss-75a8f9cbc05d------2</link>
            <guid isPermaLink="false">https://medium.com/p/935cb882bc8a</guid>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[multithreading-in-java]]></category>
            <dc:creator><![CDATA[Asatryan Manuk]]></dc:creator>
            <pubDate>Tue, 02 Jan 2024 18:59:33 GMT</pubDate>
            <atom:updated>2024-01-02T19:26:08.465Z</atom:updated>
            <content:encoded><![CDATA[<h4>Mastering Multithreading: Core Interfaces in java.util.concurrent.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YktYhip2CCuUJywPC4ryuQ.png" /></figure><h3>Popular interfaces from the java.util.concurrent.*</h3><ol><li><a href="https://medium.com/p/00d6e930014a/edit"><strong><em>ExecutorService</em></strong>:</a><br>Extends Executor and provides a more complete set of methods for managing the execution of tasks.<br>-<strong><em>Submit a Task for Execution:<br></em></strong>-<strong><em>ExecutorService Configuration:<br>-Invoke All and Invoke Any:</em></strong></li><li><a href="https://medium.com/p/00d6e930014a/edit"><strong><em>ScheduledExecutorService:</em></strong><br></a>Extends ExecutorService and supports the scheduling of tasks to run periodically or with a delay.<br>-Task Scheduling</li><li><a href="https://medium.com/@asatryanmanuk2000/callable-runnable-future-exploring-javas-asynchronous-task-models-da74b700efb2"><strong><em>Future:</em></strong></a><strong><em><br></em></strong>Represents the result of an asynchronous computation. Allows checking if the computation is complete and retrieving the result.</li><li><a href="https://shorturl.at/beKW4"><strong><em>Callable</em></strong>:</a><br>Similar to Runnable but can return a result and throw exceptions.</li><li><a href="#ecad"><strong><em>RunnableFuture</em></strong></a>:<br>Extends Runnable and Future, representing a runnable future.</li><li><a href="#eecb"><strong><em>CompletionService</em></strong></a>:<br>CompletionService in Java manages concurrent tasks, separating submission from result retrieval for efficient asynchronous computation handling. It&#39;s valuable for scenarios with multiple tasks producing and consuming results.</li></ol><h3>RunnableFuture</h3><p>RunnableFuture is an interface in Java that combines the features of both Runnable and Future. It extends the Runnable interface and also implements the Future interface. This means that a class implementing RunnableFuture can represent a task that not only can be executed concurrently but also produces a result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*miHBCupa10s52mjuj16C-Q.png" /></figure><p>This interface combines the methods of Runnable (having the run() method) and Future (having methods like cancel(), isCancelled(), isDone(), and get()).</p><p>Example</p><pre>import java.util.concurrent.*;<br><br>public class RunnableFutureExample {<br><br>    public static void main(String[] args) {<br>        // Create a single-threaded executor<br>        ExecutorService executor = Executors.newSingleThreadExecutor();<br><br>        // Create a RunnableFuture with a Callable task<br>        RunnableFuture&lt;String&gt; runnableFuture = new FutureTask&lt;&gt;(() -&gt; {<br>            // Simulate a time-consuming task<br>            try {<br>                Thread.sleep(2000);<br>                System.out.println(&quot;Hello World!&quot;);<br>            } catch (InterruptedException e) {<br>                throw new RuntimeException(e);<br>            }<br>        }, &quot;&quot;);<br><br>        // Submit the RunnableFuture to the executor<br>        executor.submit(runnableFuture);<br><br>        try {<br>            // Wait for the task to complete, but timeout after 1 second<br>            runnableFuture.get(1, TimeUnit.SECONDS);<br>            System.out.println(&quot;Task completed: &quot; + runnableFuture.get());<br>        } catch (TimeoutException e) {<br>            System.err.println(&quot;Task timed out!&quot;);<br>        } catch (Exception e) {<br>            e.printStackTrace();<br>        } finally {<br>            // Shutdown the executor<br>            executor.shutdown();<br>        }<br>    }<br>}</pre><h3>CompletionService</h3><p>CompletionService is designed to help manage asynchronous tasks and their results. It is often used in scenarios where you have a pool of tasks that need to be executed concurrently, and you want to efficiently retrieve the results as soon as they become available.</p><blockquote><strong><em>submit(Callable&lt;V&gt; task): Future&lt;V&gt;</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*LBNNAKI8kQf9RjTxf18Qjw.png" /></figure><p>Callable returned V type object and that object put into Future and returned</p><pre>  import java.util.concurrent.*;<br>  <br>  public class CompletionServiceExample {<br>  <br>  <br>      // Shutdown the ExecutorService<br>      public static void main(String[] args) {<br>          // Create an ExecutorService with a fixed number of threads<br>          ExecutorService executorService = Executors.newFixedThreadPool(5);<br>  <br>          // Create a CompletionService using the ExecutorService<br>          CompletionService&lt;Integer&gt; completionService = new ExecutorCompletionService&lt;&gt;(executorService);<br>  <br>          Future&lt;Integer&gt; submit = completionService.submit(() -&gt; {<br>              // Simulate some computation<br>              Thread.sleep(ThreadLocalRandom.current().nextInt(1000));<br>              return 1;<br>          });<br>  <br>          executorService.shutdown();<br>      }<br>  }</pre><blockquote><strong><em>submit(Runnable task, V result): Future&lt;V&gt;</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*K4urSwMlXgtHq85eDn-_5w.png" /></figure><p>This method submits a Runnable task for execution and returns a Future representing that task with a specified result. Here&#39;s an example:</p><pre>import java.util.concurrent.*;<br><br>public class SubmitExample {<br><br>    public static void main(String[] args) {<br>        // Create an ExecutorService with a fixed number of threads<br>        ExecutorService executorService = Executors.newFixedThreadPool(1);<br><br>        // Create a Runnable task<br>        Runnable task = () -&gt; {<br>            try {<br>                Thread.sleep(2000); // Simulate a time-consuming task<br>                System.out.println(&quot;Task completed&quot;);<br>            } catch (InterruptedException e) {<br>                e.printStackTrace();<br>            }<br>        };<br><br>        // Create a result object<br>        String result = &quot;Task Result&quot;;<br><br>        // Submit the Runnable task with a result to the executor<br>        Future&lt;String&gt; future = executorService.submit(task, result);<br><br>        try {<br>            // Wait for the task to complete and retrieve the result<br>            String taskResult = future.get();<br>            System.out.println(&quot;Result from the completed task: &quot; + taskResult);<br>        } catch (InterruptedException | ExecutionException e) {<br>            e.printStackTrace();<br>        } finally {<br>            // Shutdown the ExecutorService<br>            executorService.shutdown();<br>        }<br>    }<br>}</pre><p>Output of code:<br>Task completed<br>Result from the completed task: Task Result</p><blockquote><strong><em>take() : Future&lt;V&gt;</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*iw6n5DhOpWV2R3HUxWhm2g.png" /></figure><p>The take() method in the CompletionService interface is used to retrieve and remove the Future representing the next completed task. This method blocks if no tasks are immediately available.</p><p><em>Returns: the Future representing the next completed task<br>Throws: InterruptedException — if interrupted while waiting</em></p><pre>import java.util.concurrent.*;<br><br>public class CompletionServiceTakeExample {<br><br>    public static void main(String[] args) {<br>        // Create an ExecutorService with a fixed number of threads<br>        ExecutorService executorService = Executors.newFixedThreadPool(5);<br><br>        // Create a CompletionService using the ExecutorService<br>        CompletionService&lt;Integer&gt; completionService = new ExecutorCompletionService&lt;&gt;(executorService);<br><br>        // Submit some tasks to the CompletionService<br>        for (int i = 1; i &lt;= 5; i++) {<br>            final int taskId = i;<br>            completionService.submit(() -&gt; {<br>                // Simulate some computation<br>                Thread.sleep(ThreadLocalRandom.current().nextInt(1000));<br>                return taskId;<br>            });<br>        }<br><br>        // Retrieve and process completed tasks using take()<br>        for (int i = 1; i &lt;= 5; i++) {<br>            try {<br>                Future&lt;Integer&gt; completedTask = completionService.take();<br>                Integer result = completedTask.get();<br>                System.out.println(&quot;Task &quot; + result + &quot; completed&quot;);<br>            } catch (InterruptedException | ExecutionException e) {<br>                e.printStackTrace();<br>            }<br>        }<br><br>        // Shutdown the ExecutorService<br>        executorService.shutdown();<br>    }<br>}</pre><p>In this example:</p><ol><li>We submit five tasks to the CompletionService using the submit method.</li><li>We use a loop to retrieve and process the completed tasks using take(). The take() method blocks until a task is completed.</li><li>The Future representing the completed task is obtained, and the result is printed.</li><li>Finally, we shut down the ExecutorService.</li></ol><p>Please note that the order in which the completed tasks are processed may vary since they are processed as soon as they become available.</p><blockquote><strong><em>poll(): Future&lt;V&gt;</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*dqbVqpVikSAT5J8OjfxDaQ.png" /></figure><p>method is used to retrieve and remove the Future representing the next completed task, or null if no task is available. Unlike the take() method, poll() does not block; it returns immediately.</p><p><em>Returns: the Future representing the next completed task, or null if none are present</em></p><pre>import java.util.concurrent.*;<br><br>public class CompletionServicePollExample {<br><br>    public static void main(String[] args) {<br>        // Create an ExecutorService with a fixed number of threads<br>        ExecutorService executorService = Executors.newFixedThreadPool(5);<br><br>        // Create a CompletionService using the ExecutorService<br>        CompletionService&lt;Integer&gt; completionService = new ExecutorCompletionService&lt;&gt;(executorService);<br><br>        // Submit some tasks to the CompletionService<br>        for (int i = 1; i &lt;= 5; i++) {<br>            final int taskId = i;<br>            completionService.submit(() -&gt; {<br>                // Simulate some computation<br>                Thread.sleep(ThreadLocalRandom.current().nextInt(1000));<br>                return taskId;<br>            });<br>        }<br><br>        // Retrieve and process completed tasks using poll()<br>        for (int i = 1; i &lt;= 5; i++) {<br>            Future&lt;Integer&gt; completedTask = completionService.poll();<br>            if (completedTask != null) {<br>                try {<br>                    Integer result = completedTask.get();<br>                    System.out.println(&quot;Task &quot; + result + &quot; completed&quot;);<br>                } catch (InterruptedException | ExecutionException e) {<br>                    e.printStackTrace();<br>                }<br>            } else {<br>                System.out.println(&quot;No task completed yet&quot;);<br>            }<br>        }<br><br>        // Shutdown the ExecutorService<br>        executorService.shutdown();<br>    }<br>}</pre><p>In this example:</p><ol><li>We submit five tasks to the CompletionService using the submit method.</li><li>We use a loop to repeatedly call poll() to retrieve and process completed tasks. If no task is available, poll() returns null.</li><li>The Future representing the completed task is obtained (if available), and the result is printed.</li><li>Finally, we shut down the ExecutorService.</li></ol><p>Please note that the order in which the completed tasks are processed may vary, and poll() allows you to check for completed tasks without blocking.</p><blockquote><strong><em>poll(long timeout, TimeUnit unit): Future&lt;V&gt;</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*ZP8YAXsY9Agk-QLr9Hx6fA.png" /></figure><p>This method is similar to the poll() method, but it allows you to specify a timeout for how long to wait for a completed task if none is immediately available. If no task is available within the specified timeout, it returns null.</p><pre>import java.util.concurrent.*;<br><br>public class CompletionServicePollWithTimeoutExample {<br><br>    public static void main(String[] args) {<br>        // Create an ExecutorService with a fixed number of threads<br>        ExecutorService executorService = Executors.newFixedThreadPool(5);<br><br>        // Create a CompletionService using the ExecutorService<br>        CompletionService&lt;Integer&gt; completionService = new ExecutorCompletionService&lt;&gt;(executorService);<br><br>        // Submit some tasks to the CompletionService<br>        for (int i = 1; i &lt;= 5; i++) {<br>            final int taskId = i;<br>            completionService.submit(() -&gt; {<br>                // Simulate some computation<br>                Thread.sleep(ThreadLocalRandom.current().nextInt(1000));<br>                return taskId;<br>            });<br>        }<br><br>        // Retrieve and process completed tasks using poll() with timeout<br>        for (int i = 1; i &lt;= 5; i++) {<br>            try {<br>                Future&lt;Integer&gt; completedTask = completionService.poll(1, TimeUnit.SECONDS);<br>                if (completedTask != null) {<br>                    Integer result = completedTask.get();<br>                    System.out.println(&quot;Task &quot; + result + &quot; completed&quot;);<br>                } else {<br>                    System.out.println(&quot;No task completed within the timeout&quot;);<br>                }<br>            } catch (InterruptedException | ExecutionException e) {<br>                e.printStackTrace();<br>            }<br>        }<br><br>        // Shutdown the ExecutorService<br>        executorService.shutdown();<br>    }<br>}</pre><p>In this example:</p><ol><li>We submit five tasks to the CompletionService using the submit method.</li><li>We use a loop to repeatedly call poll(long timeout, TimeUnit unit) to retrieve and process completed tasks. If no task is available within the specified timeout, poll() returns null.</li><li>The Future representing the completed task is obtained (if available), and the result is printed. If no task is available within the timeout, a message indicating this is printed.</li><li>Finally, we shut down the ExecutorService.</li></ol><p>The use of a timeout allows for more flexibility in handling completed tasks without blocking indefinitely.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=935cb882bc8a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Callable & Runnable & Future : Exploring Java’s Asynchronous Task Models]]></title>
            <link>https://medium.com/@asatryanmanuk2000/callable-runnable-future-exploring-javas-asynchronous-task-models-da74b700efb2?source=rss-75a8f9cbc05d------2</link>
            <guid isPermaLink="false">https://medium.com/p/da74b700efb2</guid>
            <category><![CDATA[runnable]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[callable]]></category>
            <category><![CDATA[future]]></category>
            <dc:creator><![CDATA[Asatryan Manuk]]></dc:creator>
            <pubDate>Mon, 01 Jan 2024 20:55:19 GMT</pubDate>
            <atom:updated>2024-01-01T20:55:19.766Z</atom:updated>
            <content:encoded><![CDATA[<h3>Callable &amp; Runnable &amp; Future : Exploring Java’s Asynchronous Task Models</h3><h4>From Basics to Mastery: Understanding the Ins and Outs of Runnable &amp; Callable &amp; Future in Java Concurrency</h4><p>In this article you will found explained of interfaces Runnable and Callable .And you will be understand different and simiarilation beatwen both interfaces</p><h4>Article structure</h4><p><a href="#4708"><strong><em>-Runnable</em></strong></a><strong><em><br>-</em></strong><a href="#d44e"><strong><em>Callable</em></strong></a><strong><em><br>-</em></strong><a href="#5039"><strong><em>Similarities &amp; Differentes</em></strong></a><strong><em><br></em></strong><a href="#a00d"><strong><em>-Future</em></strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1021/1*xDYd5EHaMB-QjRsk3Wx9Nw.png" /></figure><h3>Understanding the Essence of Java’s Runnable Interface</h3><p>In Java, the Runnable interface is part of the java.lang package and is a functional interface that represents a task that can be executed concurrently by a thread. The primary purpose of the Runnable interface is to provide a common protocol for objects that can be executed by a thread.</p><p>The Runnable interface declares a single method, run(), which does not take any arguments and does not return any value. The run() method contains the code that defines the task to be executed. When an object implementing the Runnable interface is passed to a thread and that thread is started, the run() method of the Runnable object will be invoked in a new thread.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*YgT8q10JzyE3CU6XRpi6-w.png" /></figure><p>This method represents the entry point of the task to be executed. It contains the code that will run in the new thread when started.</p><p>Here’s a simple example demonstrating the use of Runnable to create a thread:</p><pre>public class MyRunnable implements Runnable {<br>    @Override<br>    public void run() {<br>        // Code to be executed in the new thread<br>        for (int i = 0; i &lt; 5; i++) {<br>            System.out.println(&quot;Thread: &quot; + Thread.currentThread().getId() + &quot;, Value: &quot; + i);<br>        }<br>    }<br><br>    public static void main(String[] args) {<br>        // Create an instance of the class implementing Runnable<br>        MyRunnable myRunnable = new MyRunnable();<br><br>        // Create a new thread and pass the Runnable object to it<br>        Thread thread = new Thread(myRunnable);<br><br>        // Start the thread<br>        thread.start();<br>    }<br>}</pre><p>In this example, the MyRunnable class implements the Runnable interface, providing the implementation for the run() method. An instance of MyRunnable is then passed to a new Thread object, and the start() method is called to begin the execution of the run() method in a separate thread.</p><h3>Callable Interface: A Result-Returning Alternative to Runnable</h3><p>The Callable interface is similar to Runnable, in that both are designed for classes whose instances are potentially executed by another thread. A Runnable, however, does not return a result and cannot throw a checked exception.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*JXaxqW54TdI2LX9UGcdBNg.png" /></figure><p>This method represents the task to be executed. It returns a result of type V and can throw an Exception</p><p>Here’s a simple example demonstrating the use of Callable and Future:</p><pre>import java.util.concurrent.Callable;<br><br>public class MyCallable implements Callable&lt;String&gt; {<br>    @Override<br>    public String call() throws Exception {<br>        // Simulate a time-consuming task<br>        Thread.sleep(2000);<br>        return &quot;Task completed!&quot;;<br>    }<br><br>    public static void main(String[] args) {<br>        // Create an instance of the class implementing Callable<br>        MyCallable myCallable = new MyCallable();<br><br>        // Create a new Thread and pass the Callable object to its constructor<br>        Thread thread = new Thread(() -&gt; {<br>            try {<br>                // Call the call() method of the Callable<br>                String result = myCallable.call();<br>                System.out.println(result);<br>            } catch (Exception e) {<br>                e.printStackTrace();<br>            }<br>        });<br><br>        // Start the thread<br>        thread.start();<br><br>        // Perform other operations while the task is running...<br><br>        try {<br>            // Wait for the thread to complete<br>            thread.join();<br>        } catch (InterruptedException e) {<br>            e.printStackTrace();<br>        }<br>    }<br>}</pre><ol><li>MyCallable is a class implementing Callable&lt;String&gt;, with a simulated time-consuming task in the call() method.</li><li>An instance of MyCallable is created.</li><li>A new Thread is created, and its start() method is called to begin asynchronous execution.</li><li>While the new thread is running, the main thread continues its work.</li><li>The main thread waits for the new thread to complete using thread.join().</li><li>After the new thread finishes, the main thread completes its execution.</li></ol><h3>Callable and Runnable similarities and difriends</h3><p>Certainly! Both Callable and Runnable are interfaces in Java that are used to represent tasks that can be executed asynchronously, but there are some key differences between them.</p><h3>Similarities:</h3><ol><li>Asynchronous Execution:<br>Both Callable and Runnable are used for defining tasks that can be executed asynchronously in a separate thread.</li><li>Interface Nature:<br>Both are interfaces. This means that classes implementing these interfaces provide the actual implementation for the tasks to be executed.</li></ol><h3>Differences:</h3><blockquote><strong><em>Return Value:</em></strong></blockquote><p><strong><em>Runnable</em></strong>:</p><ul><li>The run() method of the Runnable interface does not return a value. It is designed for tasks that don&#39;t produce a result.</li></ul><p><strong><em>Callable</em></strong>:</p><ul><li>The call() method of the Callable interface returns a result of a specified type. It is designed for tasks that produce a result.</li></ul><blockquote><strong><em>Exception Handling:</em></strong></blockquote><p><strong><em>Runnable</em></strong>:</p><ul><li>The run() method in Runnable cannot throw checked exceptions directly. Any checked exceptions need to be caught and handled within the run() method.</li></ul><p><strong><em>Callable:</em></strong></p><ul><li>The call() method in Callable is allowed to throw checked exceptions directly. The calling code needs to handle or propagate these exceptions.</li></ul><blockquote><strong><em>Usage with ExecutorService:</em></strong></blockquote><p><strong><em>Runnable:</em></strong></p><ul><li>Typically used with ExecutorService via the execute(Runnable command) method.</li></ul><p><strong><em>Callable</em></strong>:</p><ul><li>Typically used with ExecutorService via the submit(Callable&lt;T&gt; task) method. This method returns a Future&lt;T&gt; that can be used to retrieve the result.</li></ul><h3>Mastering Asynchronous Computations with Java’s Future Interface</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*_5kMpRukzbDN13UzrMrLiw.png" /></figure><p>The Future interface in Java is used in concurrent programming to represent the result of an asynchronous computation. It provides methods to check if the computation is complete, retrieve the result, and handle cancellation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*J8brLaQqsxsYR__aw_bitw.png" /></figure><blockquote><strong><em>cancel(boolean mayInterruptIfRunning): boolean</em></strong></blockquote><p>method is used to attempt to cancel the execution of the associated asynchronous task. It takes a boolean parameter mayInterruptIfRunning that determines whether the thread executing the task should be interrupted if it&#39;s currently running.</p><p><strong><em>possible employment options</em></strong></p><ul><li>If the task has not started, it may be cancelled, and the method returns true.</li><li>If the task is already running and mayInterruptIfRunning is true, the task is interrupted, and the method returns true.</li><li>If the task is already running and mayInterruptIfRunning is false, the task is not interrupted, and the method returns false.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*HPkSnIe-Zh1jV88eDi8KZQ.png" /></figure><blockquote><strong><em>isCancelled(): boolean</em></strong></blockquote><p>Returns true if this task was cancelled before it completed normally.<br>Returns:<br>true if this task was cancelled before it completed</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*hHc2C8yilRQWdcj56QDkNQ.png" /></figure><blockquote><strong><em>isDone(): boolean</em></strong></blockquote><p>Returns true if this task completed. Completion may be due to normal termination, an exception, or cancellation — in all of these cases, this method will return true.<br>Returns:<br>true if this task completed</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*ECAABJCgCtzpBWf6BAlI-Q.png" /></figure><blockquote><strong><em>get(): V</em></strong></blockquote><p>Method is used to retrieve the result of the associated asynchronous computation. It is a blocking operation, meaning it will wait until the computation is complete and then return the result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*OChbfLBOlMkJpBJXbwjAxA.png" /></figure><p>In this method V type is String</p><blockquote><strong><em>get(long timeout, TimeUnit unit): V</em></strong></blockquote><p>method allows you to specify a maximum time to wait for the result of a computation before throwing a TimeoutException. Here&#39;s how you can modify your code to use this method:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*2cpTSOfaxxT98-uQdbBjig.png" /></figure><h3>Finish</h3><p>In this article explains the best and popular interfaces of concurrent package :<br><strong><em>-</em></strong><a href="#4708"><strong><em>Runnable</em></strong></a><strong><em><br>-</em></strong><a href="#d44e"><strong><em>Callable</em></strong></a><strong><em><br></em></strong><a href="#a00d"><strong><em>-Future</em></strong></a><br>Article have more examples and theory that fully explains those concepts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da74b700efb2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Efficient Asynchronous Programming in Java: Executor & ExecutorService & ScheduledExecutorService…]]></title>
            <link>https://medium.com/@asatryanmanuk2000/java-util-concurrent-00d6e930014a?source=rss-75a8f9cbc05d------2</link>
            <guid isPermaLink="false">https://medium.com/p/00d6e930014a</guid>
            <dc:creator><![CDATA[Asatryan Manuk]]></dc:creator>
            <pubDate>Sat, 30 Dec 2023 23:16:14 GMT</pubDate>
            <atom:updated>2024-01-04T11:17:45.323Z</atom:updated>
            <content:encoded><![CDATA[<h3>Efficient Asynchronous Programming in Java: Executor &amp; ExecutorService &amp; ScheduledExecutorService Strategies</h3><h4>Maximizing Asynchronous Efficiency: A Deep Dive into Java’s Executor &amp; ExecutorService &amp; ScheduledExecutorService</h4><h4>What will this article offer to the reader?</h4><ol><li><a href="#9518"><strong><em>Executor</em></strong></a><strong><em>:<br></em></strong>Defines a simple interface for executing tasks asynchronously.<br>- <a href="#c5f2"><strong><em>Implementation for EXECUTOR</em></strong></a></li><li><a href="#d300"><strong><em>ExecutorService:</em></strong></a><strong><em><br></em></strong>Extends Executor and provides a more complete set of methods for managing the execution of tasks.<br>-<a href="#d2c8"><strong><em>Submit a Task for Execution:</em></strong></a><strong><em><br></em></strong><a href="#ef2e">-<strong><em>ExecutorService Configuration:</em></strong></a><strong><em><br>-</em></strong><a href="#ef2e"><strong><em>Invoke All and Invoke Any:</em></strong></a></li><li><a href="#d4ac"><strong><em>ScheduledExecutorService</em></strong></a><strong><em>:<br></em></strong>Extends ExecutorService and supports the scheduling of tasks to run periodically or with a delay.<br>-<a href="#d4ac">Task Scheduling</a></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*TcNF2vzmJVClwySepPx43Q.png" /></figure><h4><strong>INTERFACE EXECUTOR</strong></h4><p>The main purpose of the Executor interface is to decouple task submission from the details of how each task will be run, including details about thread creation, scheduling, and synchronization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*U7aO-BPACtge9oYJOIW54w.png" /></figure><p><strong>execute(Runnable command):</strong><br> This method is used to submit a Runnable task for execution. The implementation of the execute method is responsible for managing how and when the task is executed. It may run the task in a new thread, in a pooled thread, or even in the calling thread.</p><blockquote><strong><em>Executors have Implementation for EXECUTOR</em></strong></blockquote><h3>Static Factory Methods Of Executors</h3><p><a href="#cf62"><strong><em>ExecutorService FixedThreadPool(int n);</em></strong></a></p><p><a href="#7a23"><strong><em>ExecutorService newCachedThreadPool()</em></strong></a></p><p><a href="#7a90"><strong><em>ExecutorService newSingleThreadExecutor()</em></strong></a></p><p><a href="#1975"><strong><em>ExecutorService newWorkStealingPool()</em></strong></a></p><p><a href="#1975"><strong><em>ExecutorService newWorkStealingPool(int parallelism)</em></strong></a></p><h4><a href="#d4ac">Task Scheduling (by </a><a href="#d4ac">ScheduledExecutorService):</a></h4><p><a href="#d4ac"><strong><em>ScheduledExecutorService newScheduledThreadPool(int corePoolSize)</em></strong></a><strong><em><br></em></strong><a href="#dc58"><strong><em>-schedule(Runnable command, long delay, TimeUnit unit)</em></strong></a><strong><em><br>-</em></strong><a href="#db57"><strong><em>scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit):</em></strong></a><strong><em><br>-</em></strong><a href="#17ae"><strong><em>scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit):</em></strong></a></p><p><a href="#62d9"><strong><em>ScheduledExecutorService newSingleThreadScheduledExecutor()</em></strong></a></p><h4>Shutdown Methods:</h4><p><a href="#5155"><strong><em>void shutdown() </em></strong></a><strong><em><br></em></strong><a href="#6253"><strong><em>List&lt;Runnable&gt; shutdownNow()</em></strong></a></p><blockquote><strong>This methods for close threads:</strong></blockquote><blockquote><strong><em>void shutdown()</em></strong></blockquote><blockquote>It provides a way to signal that you want to stop accepting new tasks and allow the existing tasks to complete before shutting down the executor service.It’s a good practice to call shutdown() when you’re done using the executor service to ensure that resources are released properly.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*zwbzL-1TVkKSltTi2rcoOw.png" /></figure><blockquote><strong><em>List&lt;Runnable&gt; shutdownNow()</em></strong></blockquote><blockquote>The shutdownNow() method in the ScheduledExecutorService interface is used to attempt to stop all actively executing tasks, halt the processing of waiting tasks, and return a list of the tasks that were waiting to be executed. This method provides a more forceful shutdown compared to the shutdown() method, and it is often used when immediate termination is required.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*P5ftdp0Z94gBQ16AjJK8tw.png" /></figure><blockquote><strong>FixedThreadPool(int n) :</strong>ExecutorService</blockquote><p>The newFixedThreadPool(int n) method in the Executors class creates a fixed-size thread pool with a specified number of threads. The thread pool will contain exactly n threads, and each thread is capable of executing tasks concurrently.And any additional tasks will be queued until a thread becomes available.</p><pre>import java.util.concurrent.ExecutorService;<br>import java.util.concurrent.Executors;<br><br>public class FixedThreadPoolExample {<br>    public static void main(String[] args) {<br>        // Create a fixed-size thread pool with 3 threads<br>        ExecutorService executor = Executors.newFixedThreadPool(3);<br><br>        // Submit some tasks for execution<br>        for (int i = 0; i &lt; 5; i++) {<br>            executor.execute(() -&gt; {<br>                // Task implementation<br>                System.out.println(&quot;Executing task&quot;);<br>            });<br>        }<br><br>        // Shutdown the executor<br>        executor.shutdown();<br>    }<br>}</pre><p>In this example, we create a fixed-size thread pool with three threads using Executors.newFixedThreadPool(3). We then submit five tasks for execution. The fixed-size thread pool will maintain exactly three threads, and any additional tasks will be queued until a thread becomes available.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*CuXZ10i3PsLxTIL1K4S1nA.png" /></figure><blockquote>newCachedThreadPool() :ExecutorService</blockquote><p>The newCachedThreadPool() method in the Executors class creates a cached thread pool, dynamically adjusting its size based on the workload. Threads in the pool are created and reused as needed. If a thread remains idle for a certain amount of time, it may be terminated to reduce the pool size.<br>You can use this method to create an ExecutorService suitable for tasks that can be executed concurrently and may have varying levels of workload.</p><pre>import java.util.concurrent.ExecutorService;<br>import java.util.concurrent.Executors;<br><br>public class CachedThreadPoolExample {<br>    public static void main(String[] args) {<br>        // Create a cached thread pool<br>        ExecutorService executor = Executors.newCachedThreadPool();<br><br>        // Submit tasks for execution<br>        for (int i = 0; i &lt; 10; i++) {<br>            final int taskId = i;<br>            executor.execute(() -&gt; {<br>                // Task implementation<br>                System.out.println(&quot;Task &quot; + taskId + &quot; executed by thread &quot; + Thread.currentThread().getName());<br>            });<br>        }<br><br>        // Shutdown the executor<br>        executor.shutdown();<br>    }<br>}</pre><p>In this example, the newCachedThreadPool() is used to create a thread pool. Tasks are submitted for execution using the execute method. The thread pool dynamically adjusts its size based on the workload, creating and reusing threads as needed. The example demonstrates the simplicity of using a cached thread pool for concurrent task execution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*MpW4nSCw-i3JmTDV__0QUg.png" /></figure><blockquote><strong>newSingleThreadExecutor() :</strong>ExecutorService</blockquote><p>The newSingleThreadExecutor() method in the Executors class creates an ExecutorService that uses a single worker thread for executing tasks. This means that tasks submitted to this executor will be processed sequentially, one after another, by the single underlying thread.</p><pre>import java.util.concurrent.ExecutorService;<br>import java.util.concurrent.Executors;<br><br>public class SingleThreadExecutorExample {<br>    public static void main(String[] args) {<br>        // Create a single-threaded executor<br>        ExecutorService executor = Executors.newSingleThreadExecutor();<br><br>        // Submit tasks for execution<br>        executor.execute(() -&gt; {<br>            System.out.println(&quot;Task 1 executed by thread: &quot; + Thread.currentThread().getName());<br>        });<br><br>        executor.execute(() -&gt; {<br>            System.out.println(&quot;Task 2 executed by thread: &quot; + Thread.currentThread().getName());<br>        });<br><br>        // Shutdown the executor<br>        executor.shutdown();<br>    }<br>}</pre><p>In this example, a single-threaded executor is created using Executors.newSingleThreadExecutor(). Two tasks are then submitted for execution using the execute method. Since the executor uses only one thread, the tasks will be executed sequentially, and the output will indicate that each task is executed by the same thread.</p><p>The newSingleThreadExecutor() is useful in situations where you want tasks to be processed one at a time in a sequential manner, perhaps to maintain order or to ensure that tasks do not interfere with each other due to concurrent execution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*HkCzF2-J_qdSsZP4XiMm5A.png" /></figure><blockquote><strong><em>newWorkStealingPool(): ExecutorService<br>newWorkStealingPool(int poolSize): ExecutorService</em></strong></blockquote><p><em>newWorkStealingPool() == newWorkStealingPool(PC_ThreadCount)<br>newWorkStealingPool() worked by Algorithm “Work-Stealing”</em></p><p>Algorithm “Work-Stealing”: The work-stealing algorithm is a task scheduling strategy in parallel computing designed for efficient CPU resource utilization. Key points include:</p><p><strong>Task Decomposition:<br></strong> Tasks are broken down into smaller subtasks that can be executed independently.</p><p><strong>Task Queue:<br></strong> Each thread maintains its own local task queue, storing subtasks it needs to perform.</p><p><strong>Work Stealing: <br></strong>When a thread completes its tasks, it can “steal” tasks from the end of the task queue of another busy or blocked thread. This helps balance the workload between threads.</p><p><strong>Internal Implementation: <br></strong>Internally, the method creates an instance of ForkJoinPool, a specialized implementation of ExecutorService optimized for parallel processing using the fork-join framework.</p><p><strong>Automatic Configuration: <br></strong>The created pool dynamically adapts to the number of available processors, configuring its parallelism level accordingly.</p><p><strong>Overall Benefits:</strong></p><ul><li><em>Effective Parallelism:</em></li><li>The work-stealing algorithm aids in distributing tasks among threads, suitable for scenarios where tasks can be parallelized.</li><li><em>Dynamic Load Balancing:</em></li><li>Threads automatically balance the workload by stealing tasks from other threads, maintaining high CPU utilization.</li><li><em>Parallel Processing:</em></li><li>Suitable for applications benefiting from parallel processing, such as recursive algorithms and parallel computations.</li></ul><h3>ScheduledExecutorService</h3><blockquote><strong><em>newScheduledThreadPool(int corePoolSize):ScheduledExecutorService</em></strong></blockquote><p>The newScheduledThreadPool(int corePoolSize) returned ScheduledExecutorService that supports delayed and periodic task execution,corePoolSize is quantity of threads.</p><h4>Methods of ScheduledExecutorService</h4><blockquote><strong><em>schedule(Callable callable, long delay, TimeUnit unit)<br>schedule(Runnable command, long delay, TimeUnit unit)</em></strong></blockquote><p>Schedules a Runnable | Callabletask for execution after a specified delay.</p><pre>ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2);<br>scheduler.schedule(() -&gt; System.out.println(&quot;Delayed task&quot;), 1, TimeUnit.SECONDS);</pre><blockquote><strong><em>scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit)</em></strong></blockquote><p>Schedules a Runnable task for repeated execution at a fixed rate, with an initial delay before the first execution. Second thread will be run <br>“period” time after run first thread</p><pre>ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2);<br>scheduler.scheduleAtFixedRate(() -&gt; System.out.println(&quot;Repeated task&quot;), 1, 2, TimeUnit.SECONDS);</pre><blockquote><strong><em>scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit)</em></strong></blockquote><p>Second thread will be run “period” time after end first thread.</p><pre>ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2);<br>scheduler.scheduleWithFixedDelay(() -&gt; System.out.println(&quot;Delayed and repeated task&quot;), 1, 2, TimeUnit.SECONDS);</pre><blockquote><strong><em>ScheduledExecutorService newSingleThreadScheduledExecutor()</em></strong></blockquote><p>The SingleThreadScheduledExecutor() method in the Executors class creates a single-threaded ScheduledExecutorService that can be used to schedule tasks for execution after a specified delay or at fixed intervals.SingleThreadScheduledExecutor have all methods of ScheduledExecutorService</p><blockquote><strong><em>END EXECUTERS</em></strong></blockquote><h3>ExecutorService</h3><p>Certainly! ExecutorService is a part of the java.util.concurrent package in Java and provides a higher-level replacement for managing and controlling threads. It is an interface that extends the more basic Executor interface.</p><p>On Executor added many methods</p><blockquote><strong><em>Submit a Task for Execution:</em></strong></blockquote><ul><li><strong><em>submit(Callable&lt;T&gt; task): Future&lt;T&gt;</em></strong>: Submits a value-returning task for execution and returns a Future representing the pending results of the task.</li><li><strong><em>submit(Runnable task, T result): Future&lt;T&gt;</em></strong>: Submits a Runnable task for execution and returns a Future representing that task.</li></ul><blockquote><strong><em>ExecutorService Configuration:</em></strong></blockquote><ul><li><strong><em>isShutdown(): boolean</em></strong>: Returns true if this executor has been shut down.</li><li><strong><em>isTerminated(): boolean</em></strong>: Returns true if all tasks have completed following shut down.</li><li><strong><em>awaitTermination(long timeout, TimeUnit unit): boolean</em></strong>: Is used to block the current thread until all tasks have completed execution after a shutdown request, or until the specified timeout occurs, or until the current thread is interrupted, whichever happens first.</li></ul><pre>ExecutorService executorService = Executors.newFixedThreadPool(5);<br><br>// ... submit tasks to the executor ...<br><br>// Initiating shutdown<br>executorService.shutdown();<br><br>try {<br>    // Block until all tasks have completed or timeout occurs<br>    if (executorService.awaitTermination(10, TimeUnit.SECONDS)) {<br>        System.out.println(&quot;All tasks have completed.&quot;);<br>    } else {<br>        System.out.println(&quot;Timeout elapsed. Some tasks are still running.&quot;);<br>    }<br>} catch (InterruptedException e) {<br>    // Handle interruption (if needed)<br>    e.printStackTrace();<br>}</pre><p>In this example, the awaitTermination method is called after initiating the shutdown of the ExecutorService. It waits for up to 10 seconds for all tasks to complete. If the timeout elapses before all tasks are finished, it prints a message indicating that some tasks are still running.</p><p>T invokeAny(Collection&lt;? extends Callable&lt;T&gt;&gt; tasks, long timeout, TimeUnit unit)</p><blockquote><strong><em>Invoke All and Invoke Any:</em></strong></blockquote><ul><li><strong><em>invokeAll(Collaction&lt;? extends Callable&lt;T&gt;&gt;: List&lt;Future&lt;T&gt;&gt;</em></strong><em><br></em>The calling thread will block until all tasks in the given collection have completed or until the calling thread is interrupted.</li><li><strong><em>invokeAll(Collaction&lt;? extends Callable&lt;T&gt;, long timeout, TimeUnit unit&gt;: List&lt;Future&lt;T&gt;&gt;</em></strong><em><br></em> The calling thread is blocked until all tasks have completed or the specified timeout has elapsed.</li></ul><pre>List&lt;Callable&lt;String&gt;&gt; tasks = Arrays.asList(<br>    () -&gt; &quot;Task 1&quot;,<br>    () -&gt; &quot;Task 2&quot;,<br>    () -&gt; &quot;Task 3&quot;<br>);<br><br>ExecutorService executorService = Executors.newFixedThreadPool(3);<br><br>try {<br>    List&lt;Future&lt;String&gt;&gt; futures = executorService.invokeAll(tasks, 2, TimeUnit.SECONDS);<br><br>    for (Future&lt;String&gt; future : futures) {<br>        try {<br>            String result = future.get(); // Retrieve the result of each task<br>            System.out.println(result);<br>        } catch (ExecutionException e) {<br>            e.printStackTrace(); // Handle exceptions thrown by tasks<br>        }<br>    }<br>} catch (InterruptedException e) {<br>    e.printStackTrace(); // Handle interrupted exception<br>} finally {<br>    executorService.shutdown();<br>}</pre><p>In this example, invokeAll is used with a timeout of 2 seconds. The calling thread will wait for up to 2 seconds for all tasks to complete. If the timeout elapses before all tasks complete, the method returns with the results of the tasks that finished during that time. If all tasks complete within the timeout, the method returns a list of Future objects with the results. The ExecutorService is then properly shut down in the finally block.</p><ul><li><strong><em>invokeAny(Collaction&lt;? extends Callable&lt;T&gt;&gt;: T</em></strong><em><br></em>The invokeAny method blocks the calling thread until it returns the result of the first successfully completed task from a collection and if no task completes within that time, a TimeoutException is thrown.</li><li><strong><em>invokeAny(Collaction&lt;? extends Callable&lt;T&gt;, long timeout, TimeUnit unit&gt;: T</em></strong><em><br></em> The invokeAny method blocks the calling thread until it returns the result of the first successfully completed task from a collection. It allows you to set a timeout for the operation, and if no task completes within that time, a TimeoutException is thrown.</li></ul><pre>List&lt;Callable&lt;String&gt;&gt; tasks = Arrays.asList(<br>    () -&gt; { Thread.sleep(3000); return &quot;Task 1&quot;; },<br>    () -&gt; &quot;Task 2&quot;,<br>    () -&gt; &quot;Task 3&quot;<br>);<br><br>ExecutorService executorService = Executors.newFixedThreadPool(3);<br><br>try {<br>    String result = executorService.invokeAny(tasks, 2, TimeUnit.SECONDS);<br>    System.out.println(&quot;Result: &quot; + result);<br>} catch (InterruptedException | ExecutionException | TimeoutException e) {<br>    e.printStackTrace(); // Handle exceptions<br>} finally {<br>    executorService.shutdown();<br>}</pre><p>In this example, invokeAny is used with a timeout of 2 seconds. The calling thread will wait for up to 2 seconds for at least one task to complete. If a task completes within that time, its result is returned. If none of the tasks complete within the timeout, a TimeoutException is thrown. The ExecutorService is then properly shut down in the finally block.</p><blockquote><strong><em>END EXECUTORSERIVCE</em></strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=00d6e930014a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Algorithm Asymptotic Complexity, Big O ,Omega Theta Notations]]></title>
            <link>https://medium.com/@asatryanmanuk2000/algorithm-asymptotic-complexity-big-o-omega-theta-notations-cdea905b3e47?source=rss-75a8f9cbc05d------2</link>
            <guid isPermaLink="false">https://medium.com/p/cdea905b3e47</guid>
            <dc:creator><![CDATA[Asatryan Manuk]]></dc:creator>
            <pubDate>Tue, 19 Dec 2023 18:43:16 GMT</pubDate>
            <atom:updated>2024-06-21T15:58:20.883Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong><em>Algorithm Asymptotic Complexity, Big O , Omega , Theta Notations․</em></strong>Սկսնակից մինչև առաջադեմ</h3><h4>Հոդվածը նախատեսված է լրիվ սկսնակների և թեմային ծանոթ ոչ խորքային տիրապետող մարդկանց համար</h4><p>Հոդվածում օգտվել եմ Cormen Algorithms գրքից և ավելի խորը գրտելիքներ ձեռք բերելու համար խորհուրդ է տրվում կարդալ այն։</p><blockquote><a href="https://vk.com/doc163931991_654615555?hash=BCfGGQZ3TPHX3xtlb1jt3sJFo0A6MDiZpksNCDTj4j4">Download Cormen Algorithms 4th edition en</a><br><a href="https://djvu.online/download/Q37VAnSfuiEhX">Download Cormen Algorithms 3th edition ru</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6npzMHK7iZNg_kgOHbOYsg.jpeg" /></figure><p>Այս հոդվածում ամբողջությամ տրվելու է հետևյալ հասկացողությունների սահամանումները և բացատրությունները․</p><blockquote><a href="#1ae4"><strong><em>Algorithm TimeComplexity</em></strong></a><strong><em><br></em></strong><a href="#4344"><strong><em>Algorithm Space Complexity</em></strong></a><strong><em><br></em></strong><a href="#5c4e"><strong><em>Algorithm Asymptotic Complexity</em></strong></a><strong><em><br></em></strong><a href="#13d3"><strong><em>Complexity Notations</em></strong></a><strong><em><br></em></strong><a href="#99e2"><strong><em>Big O Notation</em></strong></a><strong><em><br></em></strong><a href="#9f1a"><strong><em>Omega Notation</em></strong></a><strong><em><br></em></strong><a href="#5326"><strong><em>Theta Notation (</em></strong></a><a href="#5326"><strong><em>Θ)</em></strong></a><strong><em><br></em></strong><a href="#774a"><strong><em>Constant Complexity: O(1)</em></strong></a><strong><em><br></em></strong><a href="#374b"><strong><em>Linear Complexity: O(n)</em></strong></a><strong><em><br></em></strong><a href="#d02d"><strong><em>Quadratic Complexity: O(N²)</em></strong></a><strong><em><br></em></strong><a href="#e3d8"><strong><em>Logarithmic Complexity: O(log n)</em></strong></a></blockquote><p>Հոդվածում հասկացողությունները բացատվելու են նաև մաթեմատիկայի օգնությամբ ,բայց բոլորին հասկանալի եղանակով։</p><h4><strong>Ինչ կտա ձեզ այս հոդվածը</strong></h4><p>Այս հոդվածի միջոցով դուք կկարողանակ միարժեքորեն պատասխանել <strong><em>հարցազրույցներում տրվող</em></strong> ալգորիթմների բարդության մասին հարցերից 90%֊ին ,և ինչը ամենակարևորն է այն ամբողջությամբ հասկանալով և պատկերացնելով ։</p><h4>Ներածություն</h4><p>Սկզբից հասկանանք երբ է առաջացել Algorithm Complexity հասկացողությունը․<br>Երբ անհրաժեշտ է եղել ասել այս ալգորթմը որևէ առումով ավելի լավն է քան մյուսը։</p><p>Ալգորիթմները բնութագրվում են 2 հիմանական հասկացողություններով՝</p><blockquote><strong><em>Algorithm Time Complexity</em></strong><br>Ալգորիթմի ծախսած ժամանակի (կատարած գործողությունների քանակի) կախումն է (ֆունկցիա է) ալգորիթմի մուտքային տվայլների քանակից։</blockquote><blockquote><strong><em>Algorithm Space Complexity</em></strong><br>Ալգորիթմի օգտագործված հիշողության կախումն է (ֆունկցիա է) ալգորիթմի մուտքային տվայլների քանակից։</blockquote><p>Քանի որ երկու բնութագրիչնները նմանատիպ ֆունկցիաներ են, ապա քննարկելով <strong><em>Time </em>Complexity֊ին</strong> կհասկանանք նաև <strong><em>Space Complexity</em>֊ին<em>։</em></strong></p><p>Քանի որ սահմանումները առաջին հայացքից կարող են անհասկանալի թվալ, դրա համար փորձեմ մանրամասնել և բացատրել հասարակ օրինակով.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p4UaxGWRyEUmMO7ay8bS_w.png" /></figure><p>Եթե պատկերացնենք, որ x-ի արժեքները համապատասխանում են մեր ալգորիթմի մուտքային տվյալների քանակին, իսկ y-ի արժեքները համապատասխանում են կատարված գործությունների քանակին, ապա կարող ենք ասել որ ալգորիթմը C չափանի մուտքի դեպքում կկատարի E հատ գործողություն, իսկ F չափանաիի դեպքում H հատ։ Այսինքն, կախված մուտքային տվյալի քանակից ցույց ենք տալիս ծախսած ժամանակը։</p><p><strong><em>Բայց կուզենամ հատուկ նշել որ մեզ ոչ թե հետաքրքրում է կոնկրետ ծախսած ժամանակը, այլ նրանաց միջև կախումը (ֆունկցիան)։</em></strong></p><p>Ալգորիթմի բարդությունը ցույց տալու համար մեզ անհրաժեշտ է գրել ալգորիթմի աշխատանքի ֆունկցիայի հավասարումը, բայց քանի որ ալգորտմի համար կոնկրետ ֆունկցիա հաշվելը կարող է շատ բարդ լինել և հաճախ ոչ անհրաժեշտ, այդ իսկ պատճառով ներմուծվել է <strong><em>Algorithm Asymptotic Complexity </em></strong><em>հասկացողությունը․</em></p><h3>Algorithm Asymptotic Complexity</h3><h4><strong><em>Asymptotic Time Complexity</em></strong></h4><blockquote>Ծախսված ժամանակի աճի (կատարված գործողությունների աճի) կախումն է մուտքային տվյալի աճից, սկսած որևէ n-րդ էլեմաենտից, երբ մուտքային տվյալները ձգտում են անվերջության։</blockquote><h4><strong><em>Asymptotic Space Complexity</em></strong></h4><blockquote>Օգտագործած հիշողության աճի կախումն է մուտքային տվյալի աճից, երբ մուտքային տվյալները ձգտում են անվերջության։</blockquote><p>Ավելի պարզ բառերով՝ մուտքային տվյալի մեկ միավոր աճի և դրա հետևանքով ծախսված ժամանակի աճի միջև կապն է :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*3i0ZHaTLZ3Cx_qbqDL5bxg.png" /><figcaption>Նկար 1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/929/1*nG_NLiwj08_LKGx-AuPQGQ.png" /><figcaption>Նկար 2</figcaption></figure><p>Փորձենք բացատրել նկարների միջոցով․<br>Նկար 1֊ում մեկ միավորով (օրինակաի համար մեկ էլեմենտով) մուտքային տվյալ ավելացնելուց տեսնում ենք որ ծախսված ժամանակը աճեց մեկ միավորով, որը ճիշտ է մուտքային տվյալի ցանկացած քանակի դեպքում։ <br>Իսկ նկար 2֊ում երկու միավորով (օրինակաի համար երկու էլեմենտով) մուտքային տվյալ ավելացնելուց տեսնում ենք, որ ծախսված ժամանակը աճեց չորս միավորով, իսկ երեք միավորով մուտքային տվյալը ավելացնելուց ծախսված ժամանակը աճեց իննով ։<br>Ապա կարող ենք հետևություն անել որ նկար 1-ում ֆունկցիան f(x)=x ֆունկցիան է, որի ծախսված ժամանակի աճը կախված է մուտքային տվյալի աճից գծայնորեն, իսկ նկար 2-ում քառակուսային է` f(x) = x²։</p><p>Մինչ այս բացատրվեց սահմանման առաջին մասը, իսկ երկրորդ մասը՝<strong> «սկսած որևէ n-րդ էլեմաենտից, երբ մուտքային տվյալները ձգտում են անվերջության»</strong> բացատրվում է հետևյալ կերպ․</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/1*mggPR3dk0-fBkzkk5XRK5w.png" /></figure><p>Քանի որ հավսարումենը կարող են մեր իմացած պարզ հավասարումները չլինեն, ինչպիսիք են նկար 3-ում պատկերվածները, որտեղ փոքր արժեքների դեպքում f1-ը ավելի էֆեկտիվ է քան f2, որը թույլ կտա մեզ կատարել դիտարկում, ըստ որի նշված միջակայքը կարող ենք համարել բոլոր հնարավոր մուտքային տվյալների քանակի 5%-ը, քանի որ մենք կարող ենք «անսահման» մեծության մուտքային տվյալներ փոխանցել։ Մնացած 95% դեպքում ավելի էֆեկտիվ կլինի f2֊ը քան f1-ը, որից հետևություն՝ մեզ հետաքրքրում է 95% դեպքերը որոնք սկսում են n-րդ էլեմենտից հետո։ Այս ամենը նաշանակում է որ մեզ անհրաժեշտ է անտեսել հավասարման ինչ որ մաս, որը համամատաբար քիչ է ազդում մեծ մուտքային տվյալների դեպքում նշված ֆունկցիայի աճի վրա։ Հասկանալու համար թե հավասարման որ անդամները անտեսենք օգտվենք հետևյալ օրինակներից</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*jnr82TJAT7_RpNtme08mnA.png" /></figure><p>Հետևյալ օրինակներից կարելի է հետևություն անել, որ ֆունկցիայի մանենամեծ աճը ապահովում է ամենաբարձր աստիճան ունեցող անդամը, այ հենց այս կերպովել կարող ենք ասել, որ <strong>Asymptotic Complexity</strong> բնութագրող ֆունկցիա ասելիս նշելու ենք ամենաբարձր աստիճան ունեցող հավասարման անդամին, անտեսելով բոլոր ավելի ցածր աստիճան ունեցող հավասարման անդամներին և թվերին, որոնց կանվանենք <strong><em>Constant Factors:</em></strong></p><blockquote>Այսպիսով մենք սահամանեցինք և բացատրեցինք <strong>Asymptotic Complexity</strong> հասկացողությունը։</blockquote><p>Հաջորդ մասը հոդվածի՝ մարդկանց ամենաշատ շփոթեցնող, անհասկանալի և միաժամանակ ամնաանհրաժեշտ մասն է։</p><h4><strong><em>Complexity Notation</em></strong></h4><blockquote>Մենք ասեցին, որ <strong>Asymptotic Complexity-ն</strong> նախատեսված է ալգորիթմը մոտարկումով բնութագրելու համար, բայց ժամանակի ընթացքում մարդիկ տեսել են, որ իրենց հետաքրքրում է ալգորիթմի կոնկրետ մի քանի վիճակների բնութագրությունը և սահմանեցին <strong>Complexity</strong>-ների տեսակներ որոնցից յուրաքանչյուրը որևէ նշանակություն ունի և որոնց միասին անվանեցին <strong>Complexity Notations։</strong></blockquote><h4>Complexity Notation֊ներն են՝</h4><blockquote><strong><em>Big O Notation (O)<br>Omega notation (Ω)<br>Theta Notation (Θ)</em></strong></blockquote><p>Եկեք շեշտենք մի փաստ, որ ալգորիթմը կարող է տարբեր ձև աշխատել մուտքային տվյալների դասավորվածությունից կախված։ Օրինակ եթե ալգորիթմը պարունակի պայմանի բլոկ (if) ,որտեղ դասավորվածությունից կախված կկատարի կամ չի կատարի բլոկում գրված կոդը, ապա մենք կուննենանք դեպքեր որտեղ ալգորիթմը մուտքից կախված կբնութագրվի հիմանական բնութագիչ ֆունկցաի ինչոր չափսով փոփոխած՝ ամենաէֆեկտիվ կամ ամենաքիչ էֆեկտիվ դեպքերին համապատասխան ֆունկցիաներով։</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/395/1*IWq-9V5xHVtE09MdtvZ3cw.png" /></figure><p>Դիցուկ f(n)֊ը ալգորիթմի հիմանական բարդութության բնութագրիչն է, c1*g(n) այն ֆունկցիան է, որը ալգորիթմը բնութագրում է ամնենա էֆեկտիվ աշխատանքի դեպքում,իսկ c2*g(n) ամենաքիչ էֆեկտիվ աշխատանքի դեպքում։</p><p>Օգտվելով այս ամենից նշենք, որ Complexity Notation֊ները ընդամենը ֆունկցիաներ են և սահամանենք հետևյալ <br>Notation֊ները</p><h4><strong><em>Big O Notation (O)</em></strong></h4><blockquote>Եթե կա այսպիսի անահավասրում c2*g(n)≥ f(n) որը ճիշտ է սկսած որևէ n0 կետից, ապա c2*g(n)֊ին ներքևից ձկտող ամենամոտ գտնվող ֆունկցիաի մոտարկումն կանվանենք Big O:</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*u9ACoIYFRtQ_PTj2Z4vPwg.png" /></figure><p>Այսինքն պարզ բառերով ասած, այն մոտարկված ֆունկցիա է, որը բնութագրում է այն մուտքային տվյալների դեպքերը երբ ֆունկցիան ամենավատ էֆեկտիվությունը կունենա։</p><h4><strong><em>Omega notation (Ω)</em></strong></h4><blockquote>Եթե կա այսպիսի անահավասրում c1*g(n)≤ f(n), որը ճիշտ է սկսած որևէ n0 կետից,ապա c1*g(n)֊ին վերևից ձկտող ամենամոտ գտնվող ֆունկցիաի մոտարկումն կանվանենք <strong><em>Omega</em></strong> O;</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*nuhYll7ImMv9sWQasSlEvQ.png" /></figure><p>Պարզ ասած, այն մոտարկված ֆունկցիա է որը բնութագրում է այն մուտքային տվյալների դեպքերը, երբ ֆունկցիան ամենալավ էֆեկտիվությունը կունենա։</p><h4>Theta Notation (Θ)</h4><blockquote>Եթե կա այնպիսի անահավասրում որտեղ c2*g(n)≥ f(n)≥c1*g(n), որը ճիշտ է սկսած որևէ n0 կետից, ապա f(n)֊ին ներքևից կամ վերևից ձկտող ամենամոտ գտնվող ֆունկցիաի մոտարկումն կանվանենք <strong><em>Theta Notation</em></strong>;</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*J9sfGp-qGq3d8cYhd3NAAw.png" /></figure><p>Պարզ ասած, այն հաճախակի պատահող դեպքերի ժամանակ ալգորիթմի աշխատանքը բնութագրող ֆունկցիան է, ինչպես նաև <strong><em>Theta Notation</em></strong>֊ով կարող ենք բնութագրել այն ալգորիթմները որոնց աշխատանքը հստակ է՝ կախված չէ մուտքային տվյալների քանակից կամ հերթականություններից ։</p><h3><strong><em>Օրինակներ</em></strong></h3><p>Պրակտիկ օրնակով ցույց տանք, որ մեզ ոչ թե հետաքրքրում է գործողությունների քանակը այլ նրանց կախումը մուտքային տվյալից:</p><h4>Constant Complexity: O(1)</h4><p>Այս օրինակում պարզ երևում է, որ ալգորիթմը O(1)-ով կարելի է բնութագրել։</p><pre>1 void main(int[] arr) {<br>2     sum += arr[1];<br>3 }</pre><p>Բայց հաջորդ օրինակի համար կմտածենք, որ եթե 10000 անգամ է O(1) գործողություն անում, ապա ինչ որ բարդ Complexity-ի կունենա, բայց ոչ տվյալ ալգորիթմը կարելի է բնութագրել O(1)-ով,<br>քանի որ զանգվածի ցանկացած չափի դեպքում այն կկատարի 10000 O(1) գործողություն և քանի որ մենք դիտարկում են, որ մեր ալգորիթմը աշխատելու է շատ մեծ զանգվածի հետ, ապա կարող ենք հետևություն անել, որ զանգվածի 10¹⁰ չափի համեմատ 10000 գործողությունը շատ փոքր է և ընդանրապես գործողությունների քանակը չի փոխում զանգվածի տարրերի ավելացման հետ միասի: հետևություն, որ այս ալգորիթմը կարելի է բնութագրել O(1) Asymptotic Complexity-ով:</p><pre>    void main(int[] arr) {<br>       int sum = 0;<br>       for (int i = 1; i &lt;= 10000; i++) {<br>            if(i &lt; arr.length){<br>              sum += arr[i];<br>            }else{<br>              sum += 1;<br>            }<br>        }<br>    }</pre><h3>Linear Complexity: O(n)</h3><p>Հաջորդ օրինակում Algorithm Complexity֊ին f(n) = 2*n։ Այստեղ կարող ենք մի քանի արժեք տալով ֆունկցիային նկատել, որ մեծ n֊երի դեպքում 2 թիվը սկսում է դեր չխաղալ։ Այսինքն մոտարկում անելիս կարելի է անտեսել 2 թվանշանը` ալգորիթմը բնութագրելով O(n) Asymptotic Complexity-ով:</p><pre>void main(int[] arr) {<br>       int sum = 0;<br>       for (int i = 0; i &lt; array.length; i++) {<br>            // Constant-time operation<br>            System.out.println(array[i]);<br>        }<br>        for (int i = 0; i &lt; array.length; i++) {<br>            // Constant-time operation<br>            System.out.println(array[i]);<br>        }<br>}</pre><h3>Quadratic Complexity: O(N²)</h3><p>Եկեք հաշվենք Algorithm Complexity֊ին:<br>2֊րդ տողում գրված է, որ այն կատարվելու է n անգամ, իսկ 3֊րդ տողը յուրաքանչյուր 2֊րդ for-ի իտերացիայի ժամանակ կկատարվի n անգամ՝ հետևություն 2֊րդ տողի n անգամ կատարվելու դեպքում 3֊րդ տողը կկատարվի n * n անամ, իսկ 5֊րդ տողը քանի, որ O(1) է այն կանտեսենք՝ ստանալով որ 2–7 տողերի կատարման բարդությունը f(n) = n² է։ Բայց մենք տեսնում են, որ 8–12 տողերում կա նաև f(n) = n գործողություն։ Այս ամենից օգտվելով կասենք, որ ամբողջ main ֆունկցիայի Algorithm Complexity֊ին f(n) = n² + n, իսկ հիշելով որ մեզ հետաքրքրում են զանգվածի մեծ լինելու դեպը, օրինակ array.length = 10¹⁰ դեպքում, կտեսնենք, որ n֊ը մեծ դեր չի խաղում, ապա կկարողանանք ալգորիթմը բնութագրել O(N²) Asymptotic Complexity֊ով։</p><blockquote>Ֆունկցիայի աճի վրա ամենաշատը ազդում է ֆունկցիայի ամենաբարձր աստիճան ունեցող անդամը, հետևություն մոտարկում անելուց վերցնում ենք միայն ամենաբարձր աստիճան ունեցող անդամին։</blockquote><pre>1 void main(int[] array) {<br>2      for (int i = 0; i &lt; array.length; i++) {<br>3          for (int j = 0; j &lt; array.length; j++) {<br>4              // Constant-time operation<br>5              System.out.println(array[i] + &quot;, &quot; + array[j]);<br>6          }<br>7      }<br>8      for (int j = 0; j &lt; array.length; j++) {<br>9              // Constant-time operation<br>10              System.out.println(array[i] + &quot;, &quot; + array[j]);<br>11      }<br>12 }</pre><h3>Logarithmic Complexity: O(log n)</h3><p>Լոգարիթմական օրիանկ է binarySearch֊ը: Ալգորիթմը աշխատում է միայն սորտաորված զանգվածների վրա։ Այս օրինակը կարելի է բացատրել գրքի էջերի թվանշաներով։ Եթե մենք ունենք 1000 էջանոց գիրք և մեզ անհրաժեշտ է բացել 120 էջը, ապա կարող ենք բացել հենց գրքի կեսը (500֊րդ էջը) տեսնելով, որ մեր ուզած էջը գտնվում է ձախ կեսում մենք այլևս 500-ից 1000 էջերը չենք դիտարկելու։ Նույն լոգիկան կօգտագործենք 0–500 էջերի համար մինջև գնենք մեր էջը։<br>Ցիկլի ամեն իտերացիայում մուտքային տվյալի քանակը կիսով կրճատվում է, իսկ թե քանի անգամ է բաժանվում 2֊ի՝ անհրաժեշտ է իմանալ, թե քանի իտեերացիա է կատարվելու:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*c7QWKdP84axcrgVPjY78Kg.png" /></figure><p>Իմանալով, որ կատարվել է K իտերացիա և ամեն իտերացիայում O(1) գործողություն կասենք, որ Algorithm Complexity֊ն f(n) = logn + O(1) է, իսկ Asymptotic Complexity֊ին՝ O(log n):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*9E9MV97dIzZeY6Kt3cctMQ.jpeg" /></figure><pre>int binarySearch(int[] array, int target) {<br>        int low = 0;<br>        int high = array.length - 1;<br><br>        while (low &lt;= high) {<br>            int mid = low + (high - low) / 2;<br><br>            if (array[mid] == target) {<br>                return mid; // Element found<br>            } else if (array[mid] &lt; target) {<br>                low = mid + 1; // Discard left half<br>            } else {<br>                high = mid - 1; // Discard right half<br>            }<br>        }<br><br>        return -1; // Element not found<br>}</pre><p>Մենք քննարկեցինք մի քանի օրինակներ, բայց հասկանում ենք, որ ալգորիթմները անսամանափակ են, ինպչես նաև իրենց բնութագրող ֆունկցիաները։</p><h4>Asymptotic Complexity֊ների տարբերությունները կոնկրետ օրինակներով</h4><p>Մեր ուզած էլեմենտը զանգվածում գտնելու համար կարող է զանգվածը այնպիսի ձևով դասավորված լինել, որ մենք գտնենք մեկ իտերացիայով, որից ավելի լավ դեպք հնարավոր չէ։ Այս դեպքը կարող ենք բնութագրել <strong><em>Omega notation-ով Ω(1)։</em></strong></p><p>Իսկ եթե մեր ուզած էլեմենտը լինի վերջինը մենք կկատարենք n իտերացիա, որից ավելի վատ դեպք հնարավոր չէ։ Այս դեպքը կարող ենք բնութագրել <strong><em>Big O Notation-ով O(n)։</em></strong></p><p>Իսկ եթե տրված լինի գտնել զանգվածի բոլոր էլեմենտներ գումարը լավագույն և վատագույն դասավորվածություն չենք ունենա և ալգորիթմը կբնութագրենք <strong><em>Terra Notation Θ(n)-</em></strong><em>ով</em><strong><em>։</em></strong></p><p>Հոդվածում պարզաբանեցինք ալգորիթմների բորդության ամենատարածված հասկացողություններնը՝ <br><a href="#5c4e"><strong><em>Algorithm Asymptotic Complexity</em></strong></a><strong><em><br></em></strong><a href="#13d3"><strong><em>Complexity Notations</em></strong></a><strong><em><br></em></strong><a href="#99e2"><strong><em>Big O Notation</em></strong></a><strong><em><br></em></strong><a href="#9f1a"><strong><em>Omega Notation</em></strong></a><strong><em><br></em></strong><a href="#5326"><strong><em>Theta Notation (</em></strong></a><a href="#5326"><strong><em>Θ)</em></strong></a><strong><em><br></em></strong>Եվ բացատրեցինք օրինակների միջոցով։ Շնորակալություն ընթերցողներին, հուսով եմ կարողացել եմ օգտակար լինել։</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cdea905b3e47" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>