├── .gitignore ├── .idea ├── .gitignore ├── gradle.xml ├── misc.xml └── vcs.xml ├── README.md ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src └── main └── java └── org └── alx └── article ├── Main.java ├── _10_introduction_to_stream_api ├── Person.java ├── StreamApiExample.java ├── source │ ├── java_logo.jpeg │ └── stream_main_methods.jpeg └── stream_api_introduction.md ├── _11_singleton_and_multiton ├── Multiton.java ├── Singleton.java ├── SingletonMultitonExample.java ├── ThreadSafeSingleton.java ├── ThreadSafeSingletonWithHolder.java ├── singleton_and_multiton.md └── source │ └── singleton_logo.jpeg ├── _12_variance_in_java ├── contravariant_super_syntax │ └── ContravariantSuperSyntaxExample.java ├── covariant │ ├── simple │ │ └── CovariantExample.java │ └── types │ │ └── CovariantTypesExample.java ├── invariant │ └── InvariantExample.java ├── source │ └── java_logo.jpeg └── variance.md ├── _13_exploring_the_biggest_rectangle_in_a_histogram ├── LargestRectangleInHistogramSimpleExample.java ├── MaximalRectangleExample.java ├── maximal_rectangle_area.md └── source │ ├── histogram_scheme.jpeg │ └── leetcode_logo.jpeg ├── _14_java_design_patterns_strategy ├── CreditCardPaymentStrategy.java ├── PayPalPaymentStrategy.java ├── PaymentStrategy.java ├── ShoppingCart.java ├── StrategyExample.java ├── source │ ├── java_logo.jpeg │ └── strategy_diagram.jpeg └── strategy.md ├── _15_java_functional_programming_with_vavr ├── fundamentals_of_vavr.md └── source │ ├── java_logo.jpeg │ └── vavr_logo.jpeg ├── _16_java_jvm_minimum_what_every_developer_should_know ├── jvm_minimum.md └── source │ ├── java_logo.jpeg │ └── jvm_architecture.jpeg ├── _17_java_classloaders_developing_own_classloader ├── CustomClassLoader.java ├── classloader.md └── source │ ├── java_logo.jpeg │ ├── jvm_classloader_brief_scheme.jpeg │ └── jvm_classloader_scheme.jpeg ├── _18_java_double_check_locking_pattern ├── Singleton.java ├── double_check_locking.md └── source │ ├── java_logo.jpeg │ └── singleton_scheme.jpeg ├── _19_java_event_driven_architecture ├── fundamentals_of_event_driven_architecture.md └── source │ ├── flow_scheme.jpeg │ ├── java_logo.jpeg │ ├── microservice_interactions_scheme.jpeg │ └── service_structure_scheme.jpeg ├── _1_prefix_sum ├── PrefixSumExample.java └── prefix_sum.md ├── _20_java_iot ├── java_iot.md └── source │ ├── java_logo.jpeg │ └── pi4j_logo.jpeg ├── _21_java_iot_pi4j ├── java_iot_pi4j.md └── source │ ├── java_logo.jpeg │ └── pi4j_logo.jpeg ├── _22_java_iot_blynk ├── java_iot_blynk.md └── source │ ├── blynk_1.jpeg │ ├── blynk_2.jpeg │ └── java_logo.jpeg ├── _23_java_microservices_architecture_patterns ├── microservices_and_patterns.md └── source │ ├── api_gateway.jpeg │ ├── bulkhead.jpeg │ ├── circuit_breaker.jpeg │ ├── cqrs.jpeg │ ├── java_logo.jpeg │ ├── load_balancing.jpeg │ ├── retry.jpeg │ ├── saga.jpeg │ └── service_registry.jpeg ├── _24_solid ├── interface_segregation_principle │ ├── area_fixed_example │ │ └── AreaFixedExample.java │ ├── dependency_inversion_principle │ │ ├── notification_example │ │ │ ├── Main.java │ │ │ ├── NotificationService.java │ │ │ └── PaymentService.java │ │ └── notification_fixed_example │ │ │ ├── Main.java │ │ │ ├── NotificationSender.java │ │ │ ├── NotificationService.java │ │ │ └── PaymentService.java │ └── simple_example │ │ └── InterfaceSegregationExample.java ├── liskov_substitution_principle │ ├── logger_example │ │ └── LoggerExample.java │ ├── number_example │ │ └── NumberExample.java │ ├── vehicle_example │ │ └── VehicleExample.java │ └── vehicle_fixed_example │ │ └── VehicleExampleFixed.java ├── open_closed_principle │ ├── pipe_line_example │ │ └── Main.java │ ├── simple_example │ │ └── Main.java │ └── strategy_example │ │ └── Main.java ├── single_responsibiliy_principle │ ├── AccessManager.java │ ├── Movie.java │ ├── SingleResponsibilityPrincipleExample.java │ ├── SubscriptionType.java │ └── User.java └── solid.md ├── _25_global_lock ├── Payment.java ├── Product.java ├── ProductService.java ├── global_lock.md └── source │ ├── classes.jpeg │ ├── sequence_diagram.jpeg │ └── spring.jpeg ├── _26_scheduling_async ├── AsyncConfig.java ├── MyScheduledTasks.java ├── MyScheduledTasksExtended.java ├── SchedulerConfig.java ├── scheduling_async.md └── source │ └── spring.jpeg ├── _27_synchronization_java ├── SynchronizationExample.java ├── source │ └── java.jpeg └── synchronization.md ├── _28_threads_fundamentals ├── DiningPhilosophers.java ├── ThreadState.java ├── ThreadStateExample.java ├── source │ ├── thread_cycle.jpeg │ └── title.jpeg └── thread_fundamentals_pt_1.md ├── _29_threads_fundamentals_2 ├── AtomicExample.java ├── CompletableFutureExample.java ├── MyCallable.java ├── source │ └── title.jpeg └── thread_fundamentals_pt_2.md ├── _2_disjoint_set_data_structure ├── DisjointSetExample.java └── disjoint_set.md ├── _30_java_util_concurrent_1 ├── ConcurrentCollectionsExample.java ├── ConditionExample.java ├── ConditionProducerConsumerExample.java ├── ExecutorServiceExample.java ├── SynchronizersExample.java ├── java_util_concurrent_pt1.md └── source │ ├── concurrent.jpeg │ ├── concurrent_hashmap.jpeg │ ├── concurrent_hierarchy1.jpeg │ ├── concurrent_hierarchy2.jpeg │ └── title.jpeg ├── _31_java_util_concurrent_2 ├── CompletableFutureExample.java ├── CountdownLatchExample.java ├── ForkJoinPoolExample.java ├── java_util_concurrent_pt2.md └── source │ ├── future.jpeg │ ├── java_util_concurrent.jpeg │ └── title.jpeg ├── _32_java_concurrency_best_practices ├── AsynchronousFileIOExample.java ├── AsynchronousHttpClientExample.java ├── ConcurrentHashMapExample.java ├── ExceptionHandlerExample.java ├── ParallelComputationExample.java ├── concurrency_in_java_best_practices.md └── source │ └── title.jpeg ├── _33_grasp ├── controller │ ├── UserController.java │ └── UserService.java ├── creator │ ├── Customer.java │ ├── Order.java │ ├── OrderRepository.java │ ├── OrderService.java │ └── Product.java ├── grasp.md ├── indirection │ ├── PaymentGateway.java │ ├── PaymentProcessor.java │ └── PaymentRequest.java ├── information_expert │ ├── Item.java │ └── ShoppingCart.java └── source │ ├── grasp.jpeg │ ├── title.jpeg │ └── title1.jpeg ├── _34_dry_kiss_yagni ├── dry_kiss_yagni.md └── source │ ├── dry.jpeg │ ├── kiss.jpeg │ ├── princeples.jpeg │ ├── title.jpeg │ └── yagni.jpeg ├── _35_abstraction_extensibility_cohesion ├── abstraction │ ├── AbstractClassesExample.java │ └── InterfacesExample.java ├── abstraction_extensibility_cohesion.md ├── cohesion │ ├── DataProcessor.java │ ├── DatabaseAccessLayer.java │ └── SequentialProcess.java ├── extensibility │ ├── AbstractClassesExample.java │ ├── DesignPatternsExample.java │ ├── InterfacesAndPolymorphismExample.java │ └── InterfacesExample.java └── source │ ├── title1.jpeg │ ├── title2.jpeg │ └── title3.jpeg ├── _36_new_switch_case_java ├── SwitchCaseExample.java ├── new_switch_case.md └── source │ └── title.jpeg ├── _37_spring_beans ├── EmailNotificationService.java ├── EmailSender.java ├── Sender.java ├── applicationContext.xml ├── source │ ├── bean_cycle.jpeg │ ├── spring.jpeg │ └── title.jpeg └── spring_beans.md ├── _38_builder ├── User.java ├── builder.md ├── source │ └── title.jpeg ├── user_builder │ └── User.java └── user_builder_extra │ └── User.java ├── _39_java_architecture_blueprint ├── java_architecture_blueprint.md └── source │ ├── cache.jpeg │ ├── documentation.jpeg │ ├── layered_architecture.jpeg │ ├── test_pyramid.jpeg │ └── title.jpeg ├── _3_knapsack ├── Item.java ├── KnapsackBruteForce.java ├── KnapsackDP.java ├── knapsack.md └── source │ └── knapsack_title_logo.jpeg ├── _40_decorator ├── Coffee.java ├── CoffeeDecorator.java ├── Main.java ├── MilkDecorator.java ├── SimpleCoffee.java ├── SugarDecorator.java ├── decorator.md └── source │ ├── decorator_diagram.jpeg │ └── title.jpeg ├── _41_thread_local ├── MyService.java ├── MyThreadLocalExample.java ├── ThreadLocalExample.java ├── ThreadLocalSimpleExample.java ├── source │ ├── thread_local.jpeg │ └── title.jpeg └── thread_local.md ├── _42_choosing_the_right_collection_in_java ├── CustomComparator.java ├── Main.java ├── choosing_the_right_collection_in_java.md └── source │ └── title.jpg ├── _43_thread_local_vs_scoped_value ├── ScopedValueExample.java ├── ScopedValueSimpleExample.java ├── ThreadLocalExample.java ├── ThreadLocalSimpleExample.java ├── source │ ├── thread_local.jpeg │ └── title.jpg └── thread_local_vs_scoped_value.md ├── _44_multithreaded_programming_anti_patterns_in_java_pt1 └── multithreaded_programming_anti_patterns_in_java_pt1.md ├── _45_multithreaded_programming_anti_patterns_in_java_pt2 └── multithreaded_programming_anti_patterns_in_java_pt2.md ├── _46_java_recursive_generics_example ├── Person.java ├── QueryBuilder.java ├── QueryBuilderExample.java ├── RecursiveGenericsExample.java ├── java_recursive_generics_example.md └── source │ └── title.jpg ├── _47_chain_of_responsibility ├── ChainOfResponsibilityExample.java ├── DataConversionPipeline.java ├── chain_of_responsibility.md └── source │ ├── chain_of_responsibility_diagram.jpg │ ├── handling_chain.jpg │ └── title.jpg ├── _48_java_rest_clients ├── appache_http_client │ ├── PostRequestWithJson.java │ └── SimpleGetRequest.java ├── java_rest_clients.md ├── native_client │ ├── AsyncPostRequest.java │ └── SimpleGetRequest.java ├── okhttp │ ├── AsyncPostRequest.java │ └── SimpleGetRequest.java ├── spring_rest_template │ ├── PostRequestWithJson.java │ └── SimpleGetRequest.java └── spring_web_flux │ ├── PostRequestWithJson.java │ └── SimpleGetRequest.java ├── _49_resilience4j ├── resilience4j.md └── source │ ├── resilience4j.jpeg │ └── title.jpeg ├── _4_radix_sort ├── RadixSort.java ├── radix_sort.md └── source │ └── radix_sort_title_logo.jpeg ├── _50_java8_to_java17_migration └── java8_to_java17_migration.md ├── _51_spring_aop └── spring_aop.md ├── _52_spring_cache └── spring_cache.md ├── _53_fork_join_pool ├── ForkJoinMergeSort.java ├── ForkJoinPoolExample.java ├── fork_join_pool.md └── source │ └── ForkJoinPool.jpeg ├── _54_garbage_collection ├── garbage_collection.md └── source │ └── gc.jpeg ├── _55_java_comilation ├── java_compilation.md └── source │ └── jvm_compiller.jpeg ├── _56_custom_collector └── custom_collector.md ├── _57_merging_two_maps ├── ApacheCollectionUtils.java ├── MapMergeMethod.java ├── MapPutAll.java ├── MapPutIfAbsent.java ├── Person.java ├── StreamConcat.java ├── StreamOf.java └── merge_two_maps.md ├── _58_java_records ├── Person.java ├── Range.java ├── RationalExample.java └── java_records_vs_lombok.md ├── _59_introduction_to_graal_vm └── introduction_to_graal_vm.md ├── _5_java_memory_model ├── java_memory_model.md └── source │ ├── java_memory_brief_scheme.jpeg │ ├── java_memory_detail_scheme.jpeg │ └── java_memory_scheme.jpeg ├── _60_concurrent_map_guide └── concurrent_map_guide.md ├── _60_graalvm └── graalvm.md ├── _61_concurrent_hash_map_for_caching └── concurrent_hash_map_for_caching.md ├── _62_introduction_to_lru_and_lfu_caching_concepts_implementations_and_practical_use_cases └── introduction_to_lru_and_lfu_caching_concepts_implementations_and_practical_use_cases.md ├── _63_introduction_to_caching_with_google_guava_a_simple_and_flexible_solution └── introduction_to_caching_with_google_guava_a_simple_and_flexible_solution.md ├── _64_introduction_to_aspect_oriented_programming_aop_in_spring_with_aspectj └── introduction_to_aspect_oriented_programming_aop_in_spring_with_aspectj.md ├── _65_visitor_pattern_in_java ├── VisitorPatternDemo.java └── visitor_pattern_in_java.md ├── _66_observer_pattern_in_java ├── ObserverPatternDemo.java └── observer_pattern_in_java.md ├── _67_lombok ├── User.java ├── UserSimplified.java └── lombok.md ├── _68_java_reflection_api_overview └── java_reflection_api_overview.md ├── _69_exploring_java_reflection_object_creation_and_dynamic_proxy └── exploring_java_reflection_object_creation_and_dynamic_proxy.md ├── _6_optimizing_java_apps ├── optimizing_java_apps.md └── source │ ├── java_logo.jpeg │ ├── optimization_technics.jpeg │ └── performance_scheme.jpeg ├── _7_fundamentals_of_logging ├── fundamentals_of_java_logging.md └── source │ └── loggers_scheme.jpeg ├── _8_binary_search ├── BinarySearch.java ├── binary_search.md └── source │ └── binary_search_scheme.jpeg └── _9_intellij_plugins ├── intellij_idea_useful_plugins.md └── source └── intellij_idea_logo.jpeg /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | build/ 3 | !gradle/wrapper/gradle-wrapper.jar 4 | !**/src/main/**/build/ 5 | !**/src/test/**/build/ 6 | 7 | ### IntelliJ IDEA ### 8 | .idea/modules.xml 9 | .idea/jarRepositories.xml 10 | .idea/compiler.xml 11 | .idea/libraries/ 12 | *.iws 13 | *.iml 14 | *.ipr 15 | out/ 16 | !**/src/main/**/out/ 17 | !**/src/test/**/out/ 18 | 19 | ### Eclipse ### 20 | .apt_generated 21 | .classpath 22 | .factorypath 23 | .project 24 | .settings 25 | .springBeans 26 | .sts4-cache 27 | bin/ 28 | !**/src/main/**/bin/ 29 | !**/src/test/**/bin/ 30 | 31 | ### NetBeans ### 32 | /nbproject/private/ 33 | /nbbuild/ 34 | /dist/ 35 | /nbdist/ 36 | /.nb-gradle/ 37 | 38 | ### VS Code ### 39 | .vscode/ 40 | 41 | ### Mac OS ### 42 | .DS_Store -------------------------------------------------------------------------------- /.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /shelf/ 3 | /workspace.xml 4 | # Editor-based HTTP Client requests 5 | /httpRequests/ 6 | # Datasource local storage ignored files 7 | /dataSources/ 8 | /dataSources.local.xml 9 | -------------------------------------------------------------------------------- /.idea/gradle.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 15 | 16 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | } 4 | 5 | group 'org.alx.article' 6 | version '1.0-SNAPSHOT' 7 | 8 | sourceCompatibility = 1.21 9 | targetCompatibility = 1.21 10 | 11 | repositories { 12 | mavenCentral() 13 | } 14 | 15 | compileJava { 16 | options.compilerArgs += ['--enable-preview'] 17 | } 18 | 19 | dependencies { 20 | implementation 'org.springframework.boot:spring-boot-starter-integration:3.2.5' 21 | implementation 'org.springframework.integration:spring-integration-core:6.2.4' 22 | implementation 'org.springframework:spring-jdbc:6.1.7' 23 | 24 | // https://mvnrepository.com/artifact/org.springframework/spring-context-support 25 | implementation group: 'org.springframework', name: 'spring-context-support', version: '5.3.35' 26 | 27 | 28 | // https://mvnrepository.com/artifact/javax.servlet/servlet-api 29 | implementation 'javax.servlet:servlet-api:2.5' 30 | 31 | // https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient 32 | implementation group: 'org.apache.httpcomponents', name: 'httpclient', version: '4.5' 33 | 34 | // https://mvnrepository.com/artifact/org.springframework/spring-web 35 | implementation group: 'org.springframework', name: 'spring-web', version: '3.0.2.RELEASE' 36 | 37 | // https://mvnrepository.com/artifact/org.springframework/spring-webflux 38 | implementation group: 'org.springframework', name: 'spring-webflux', version: '5.3.35' 39 | 40 | // https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp 41 | implementation group: 'com.squareup.okhttp3', name: 'okhttp', version: '4.12.0' 42 | 43 | // https://mvnrepository.com/artifact/org.apache.commons/commons-collections4 44 | implementation group: 'org.apache.commons', name: 'commons-collections4', version: '4.4' 45 | 46 | 47 | implementation 'org.springframework:spring-tx:6.1.7' 48 | 49 | implementation 'org.springframework:spring-context:6.1.7' 50 | 51 | compileOnly 'org.projectlombok:lombok:1.18.32' 52 | annotationProcessor 'org.projectlombok:lombok:1.18.32' 53 | 54 | testCompileOnly 'org.projectlombok:lombok:1.18.32' 55 | testAnnotationProcessor 'org.projectlombok:lombok:1.18.32' 56 | 57 | testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.1' 58 | testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.1' 59 | } 60 | 61 | test { 62 | useJUnitPlatform() 63 | } -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.5.1-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%"=="" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%"=="" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if %ERRORLEVEL% equ 0 goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if %ERRORLEVEL% equ 0 goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | set EXIT_CODE=%ERRORLEVEL% 84 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 85 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 86 | exit /b %EXIT_CODE% 87 | 88 | :mainEnd 89 | if "%OS%"=="Windows_NT" endlocal 90 | 91 | :omega 92 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'articles' 2 | 3 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/Main.java: -------------------------------------------------------------------------------- 1 | package org.alx.article; 2 | 3 | public class Main { 4 | public static void main(String[] args) { 5 | System.out.println("Hello world!"); 6 | } 7 | } -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_10_introduction_to_stream_api/Person.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._10_introduction_to_stream_api; 2 | 3 | import java.util.List; 4 | 5 | public class Person { 6 | private String name; 7 | List transactions; 8 | int score; 9 | 10 | public Person(String name, int score) { 11 | this.name = name; 12 | this.score = score; 13 | } 14 | 15 | public Person(String name, List transactions) { 16 | this.name = name; 17 | this.transactions = transactions; 18 | } 19 | 20 | public Person(String name) { 21 | this.name = name; 22 | } 23 | 24 | public String getName() { 25 | return name; 26 | } 27 | 28 | public void setName(String name) { 29 | this.name = name; 30 | } 31 | 32 | public List getTransactions() { 33 | return transactions; 34 | } 35 | 36 | public void setTransactions(List transactions) { 37 | this.transactions = transactions; 38 | } 39 | 40 | public int getScore() { 41 | return score; 42 | } 43 | 44 | public void setScore(int score) { 45 | this.score = score; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_10_introduction_to_stream_api/source/java_logo.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_10_introduction_to_stream_api/source/java_logo.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_10_introduction_to_stream_api/source/stream_main_methods.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_10_introduction_to_stream_api/source/stream_main_methods.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_11_singleton_and_multiton/Multiton.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._11_singleton_and_multiton; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | public class Multiton { 7 | private static Map instances = new HashMap<>(); 8 | private String name; 9 | 10 | private Multiton(String name) { 11 | this.name = name; 12 | } 13 | 14 | public static Multiton getInstance(String name) { 15 | if (!instances.containsKey(name)) { 16 | synchronized (Multiton.class) { 17 | if (!instances.containsKey(name)) { 18 | instances.put(name, new Multiton(name)); 19 | } 20 | } 21 | } 22 | return instances.get(name); 23 | } 24 | 25 | public void doSomething() { 26 | System.out.println("I am " + name); 27 | } 28 | } -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_11_singleton_and_multiton/Singleton.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._11_singleton_and_multiton; 2 | 3 | public class Singleton { 4 | private static Singleton instance; 5 | 6 | private Singleton() {} 7 | 8 | public static Singleton getInstance() { 9 | if (instance == null) { 10 | instance = new Singleton(); 11 | } 12 | return instance; 13 | } 14 | } -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_11_singleton_and_multiton/SingletonMultitonExample.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._11_singleton_and_multiton; 2 | 3 | public class SingletonMultitonExample { 4 | public static void main(String[] args) { 5 | Multiton instance1 = Multiton.getInstance("first"); 6 | Multiton instance2 = Multiton.getInstance("second"); 7 | Multiton instance3 = Multiton.getInstance("first"); 8 | 9 | instance1.doSomething(); // Output: I am first 10 | instance2.doSomething(); // Output: I am second 11 | instance3.doSomething(); // Output: I am first 12 | 13 | System.out.println(instance1 == instance2); // Output: false 14 | System.out.println(instance1 == instance3); // Output: true 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_11_singleton_and_multiton/ThreadSafeSingleton.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._11_singleton_and_multiton; 2 | 3 | public class ThreadSafeSingleton { 4 | private static volatile ThreadSafeSingleton instance; 5 | 6 | private ThreadSafeSingleton() { 7 | // Private constructor to prevent instantiation from outside 8 | } 9 | 10 | public static ThreadSafeSingleton getInstance() { 11 | if (instance == null) { 12 | synchronized (ThreadSafeSingleton.class) { 13 | if (instance == null) { 14 | instance = new ThreadSafeSingleton(); 15 | } 16 | } 17 | } 18 | return instance; 19 | } 20 | } -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_11_singleton_and_multiton/ThreadSafeSingletonWithHolder.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._11_singleton_and_multiton; 2 | 3 | public class ThreadSafeSingletonWithHolder { 4 | private ThreadSafeSingletonWithHolder() { 5 | // Private constructor to prevent instantiation from outside 6 | } 7 | 8 | private static class SingletonHolder { 9 | private static final ThreadSafeSingletonWithHolder INSTANCE = new ThreadSafeSingletonWithHolder(); 10 | } 11 | 12 | public static ThreadSafeSingletonWithHolder getInstance() { 13 | return SingletonHolder.INSTANCE; 14 | } 15 | } -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_11_singleton_and_multiton/source/singleton_logo.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_11_singleton_and_multiton/source/singleton_logo.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_12_variance_in_java/contravariant_super_syntax/ContravariantSuperSyntaxExample.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._12_variance_in_java.contravariant_super_syntax; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | class Animal { 7 | public void makeSound() { 8 | System.out.println("Animal makes a sound"); 9 | } 10 | } 11 | 12 | class Dog extends Animal { 13 | @Override 14 | public void makeSound() { 15 | System.out.println("Dog barks"); 16 | } 17 | } 18 | 19 | public class ContravariantSuperSyntaxExample { 20 | public static void main(String[] args) { 21 | List animals = new ArrayList(); // List of a supertype of Dog 22 | animals.add(new Dog()); // This is valid 23 | //animals.add(new Animal()); // This is not valid 24 | // Dog d = animals.get(0); // Compilation error, can't guarantee the exact type 25 | Object o = animals.get(0); // Valid, since any supertype of Dog can be assigned to Object 26 | } 27 | } -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_12_variance_in_java/covariant/simple/CovariantExample.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._12_variance_in_java.covariant.simple; 2 | import java.util.ArrayList; 3 | import java.util.List; 4 | 5 | class Animal { 6 | public void makeSound() { 7 | System.out.println("Animal makes a sound"); 8 | } 9 | } 10 | 11 | class Dog extends Animal { 12 | @Override 13 | public void makeSound() { 14 | System.out.println("Dog barks"); 15 | } 16 | } 17 | 18 | public class CovariantExample { 19 | // Method that accepts a collection of Animal 20 | public static void processAnimals(List animals) { 21 | for (Animal animal : animals) { 22 | animal.makeSound(); 23 | } 24 | } 25 | 26 | public static void main(String[] args) { 27 | List dogs = new ArrayList<>(); 28 | dogs.add(new Dog()); 29 | 30 | // Pass a List to a method that accepts List 31 | processAnimals(dogs); 32 | } 33 | } -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_12_variance_in_java/covariant/types/CovariantTypesExample.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._12_variance_in_java.covariant.types; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | class Animal { 7 | public String getType() { 8 | return "Animal"; 9 | } 10 | } 11 | 12 | class Dog extends Animal { 13 | @Override 14 | public String getType() { 15 | return "Dog"; 16 | } 17 | } 18 | 19 | public class CovariantTypesExample { 20 | public static void main(String[] args) { 21 | List animals = new ArrayList<>(); 22 | animals.add(new Dog()); 23 | 24 | // Output: Dog 25 | for (Animal animal : animals) { 26 | System.out.println(animal.getType()); 27 | } 28 | } 29 | } -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_12_variance_in_java/invariant/InvariantExample.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._12_variance_in_java.invariant; 2 | 3 | class Animal { 4 | public void makeSound() { 5 | System.out.println("Animal makes a sound"); 6 | } 7 | } 8 | 9 | class Dog extends Animal { 10 | @Override 11 | public void makeSound() { 12 | System.out.println("Dog barks"); 13 | } 14 | } 15 | 16 | public class InvariantExample { 17 | public static void main(String[] args) { 18 | Animal[] animals = new Dog[1]; // Compiler error 19 | animals[0] = new Animal(); // This would cause a runtime error 20 | } 21 | } -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_12_variance_in_java/source/java_logo.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_12_variance_in_java/source/java_logo.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_13_exploring_the_biggest_rectangle_in_a_histogram/LargestRectangleInHistogramSimpleExample.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._13_exploring_the_biggest_rectangle_in_a_histogram; 2 | 3 | public class LargestRectangleInHistogramSimpleExample { 4 | public static int largestRectangleArea(int[] heights) { 5 | int maxArea = 0; 6 | int n = heights.length; 7 | 8 | for (int i = 0; i < n; i++) { 9 | int minHeight = heights[i]; 10 | for (int j = i; j < n; j++) { 11 | minHeight = Math.min(minHeight, heights[j]); 12 | int width = j - i + 1; 13 | int area = minHeight * width; 14 | maxArea = Math.max(maxArea, area); 15 | } 16 | } 17 | return maxArea; 18 | } 19 | 20 | public static void main(String[] args) { 21 | int[] histogram = {2, 1, 5, 6, 2, 3}; 22 | //Output 10 23 | System.out.println("Largest rectangle area: " + largestRectangleArea(histogram)); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_13_exploring_the_biggest_rectangle_in_a_histogram/MaximalRectangleExample.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._13_exploring_the_biggest_rectangle_in_a_histogram; 2 | 3 | import java.util.Stack; 4 | 5 | public class MaximalRectangleExample { 6 | public int maximalRectangle(char[][] matrix) { 7 | int maxArea = 0; 8 | int n = matrix[0].length; 9 | int[] height = new int[n]; 10 | 11 | for (char[] chars : matrix) { 12 | for (int j = 0; j < n; j++) { 13 | if (chars[j] == '1') height[j]++; 14 | else height[j] = 0; 15 | } 16 | maxArea = Math.max(largestRectangleArea(height), maxArea); 17 | } 18 | return maxArea; 19 | } 20 | 21 | public int largestRectangleArea(int[] heights) { 22 | Stack st = new Stack<>(); 23 | int maxArea = 0; 24 | for (int i = 0; i <= heights.length; i++) { 25 | while (!st.isEmpty() && (i == heights.length || heights[st.peek()] > heights[i])) { 26 | int height = heights[st.pop()]; 27 | int width = i; 28 | if (!st.isEmpty()) width = (i - st.peek() - 1); 29 | int curArea = height * width; 30 | maxArea = Math.max(maxArea, curArea); 31 | } 32 | st.push(i); 33 | } 34 | return maxArea; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_13_exploring_the_biggest_rectangle_in_a_histogram/source/histogram_scheme.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_13_exploring_the_biggest_rectangle_in_a_histogram/source/histogram_scheme.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_13_exploring_the_biggest_rectangle_in_a_histogram/source/leetcode_logo.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_13_exploring_the_biggest_rectangle_in_a_histogram/source/leetcode_logo.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_14_java_design_patterns_strategy/CreditCardPaymentStrategy.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._14_java_design_patterns_strategy; 2 | 3 | public class CreditCardPaymentStrategy implements PaymentStrategy { 4 | private String cardNumber; 5 | private String expiryDate; 6 | private String cvv; 7 | 8 | public CreditCardPaymentStrategy(String cardNumber, String expiryDate, String cvv) { 9 | this.cardNumber = cardNumber; 10 | this.expiryDate = expiryDate; 11 | this.cvv = cvv; 12 | } 13 | 14 | @Override 15 | public void pay(double amount) { 16 | System.out.println(amount + " paid with credit/debit card."); 17 | } 18 | } 19 | 20 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_14_java_design_patterns_strategy/PayPalPaymentStrategy.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._14_java_design_patterns_strategy; 2 | 3 | public class PayPalPaymentStrategy implements PaymentStrategy { 4 | private String email; 5 | private String password; 6 | 7 | public PayPalPaymentStrategy(String email, String password) { 8 | this.email = email; 9 | this.password = password; 10 | } 11 | 12 | @Override 13 | public void pay(double amount) { 14 | System.out.println(amount + " paid using PayPal."); 15 | } 16 | } -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_14_java_design_patterns_strategy/PaymentStrategy.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._14_java_design_patterns_strategy; 2 | 3 | public interface PaymentStrategy { 4 | void pay(double amount); 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_14_java_design_patterns_strategy/ShoppingCart.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._14_java_design_patterns_strategy; 2 | 3 | public class ShoppingCart { 4 | private PaymentStrategy paymentStrategy; 5 | 6 | public void setPaymentStrategy(PaymentStrategy paymentStrategy) { 7 | this.paymentStrategy = paymentStrategy; 8 | } 9 | 10 | public void checkout(double amount) { 11 | paymentStrategy.pay(amount); 12 | } 13 | } -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_14_java_design_patterns_strategy/StrategyExample.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._14_java_design_patterns_strategy; 2 | 3 | public class StrategyExample { 4 | public static void main(String[] args) { 5 | ShoppingCart cart = new ShoppingCart(); 6 | 7 | // Use credit card payment 8 | cart.setPaymentStrategy(new CreditCardPaymentStrategy("1234 5678 9012 3456", "12/24", "123")); 9 | cart.checkout(100.0); 10 | 11 | // Use PayPal payment 12 | cart.setPaymentStrategy(new PayPalPaymentStrategy("example@example.com", "password")); 13 | cart.checkout(200.0); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_14_java_design_patterns_strategy/source/java_logo.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_14_java_design_patterns_strategy/source/java_logo.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_14_java_design_patterns_strategy/source/strategy_diagram.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_14_java_design_patterns_strategy/source/strategy_diagram.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_15_java_functional_programming_with_vavr/source/java_logo.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_15_java_functional_programming_with_vavr/source/java_logo.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_15_java_functional_programming_with_vavr/source/vavr_logo.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_15_java_functional_programming_with_vavr/source/vavr_logo.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_16_java_jvm_minimum_what_every_developer_should_know/source/java_logo.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_16_java_jvm_minimum_what_every_developer_should_know/source/java_logo.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_16_java_jvm_minimum_what_every_developer_should_know/source/jvm_architecture.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_16_java_jvm_minimum_what_every_developer_should_know/source/jvm_architecture.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_17_java_classloaders_developing_own_classloader/CustomClassLoader.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._17_java_classloaders_developing_own_classloader; 2 | 3 | import java.io.ByteArrayOutputStream; 4 | import java.io.File; 5 | import java.io.FileInputStream; 6 | import java.io.IOException; 7 | 8 | public class CustomClassLoader extends ClassLoader { 9 | 10 | private final String classPath; 11 | 12 | public CustomClassLoader(String classPath, ClassLoader parent) { 13 | super(parent); 14 | this.classPath = classPath; 15 | } 16 | 17 | @Override 18 | protected Class findClass(String name) throws ClassNotFoundException { 19 | byte[] classBytes = loadClassBytes(name); 20 | return defineClass(name, classBytes, 0, classBytes.length); 21 | } 22 | 23 | private byte[] loadClassBytes(String className) throws ClassNotFoundException { 24 | String fileName = className.replace('.', File.separatorChar) + ".class"; 25 | try { 26 | FileInputStream fis = new FileInputStream(classPath + File.separator + fileName); 27 | ByteArrayOutputStream bos = new ByteArrayOutputStream(); 28 | int b; 29 | while ((b = fis.read()) != -1) { 30 | bos.write(b); 31 | } 32 | fis.close(); 33 | return bos.toByteArray(); 34 | } catch (IOException e) { 35 | throw new ClassNotFoundException("Class '" + className + "' not found.", e); 36 | } 37 | } 38 | 39 | public static void main(String[] args) { 40 | // Define the path to the directory containing the class files 41 | String classPath = "/path/to/class/files"; 42 | 43 | // Create an instance of the custom class loader 44 | CustomClassLoader classLoader = new CustomClassLoader(classPath, ClassLoader.getSystemClassLoader()); 45 | 46 | try { 47 | // Load the class using the custom class loader 48 | Class myClass = classLoader.loadClass("com.example.MyClass"); 49 | 50 | // Create an instance of the loaded class 51 | Object obj = myClass.newInstance(); 52 | 53 | // Invoke methods or access fields of the loaded class 54 | // For example: 55 | // Method method = myClass.getMethod("methodName"); 56 | // Object result = method.invoke(obj); 57 | } catch (ClassNotFoundException | IllegalAccessException | InstantiationException e) { 58 | e.printStackTrace(); 59 | } 60 | } 61 | } -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_17_java_classloaders_developing_own_classloader/source/java_logo.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_17_java_classloaders_developing_own_classloader/source/java_logo.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_17_java_classloaders_developing_own_classloader/source/jvm_classloader_brief_scheme.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_17_java_classloaders_developing_own_classloader/source/jvm_classloader_brief_scheme.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_17_java_classloaders_developing_own_classloader/source/jvm_classloader_scheme.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_17_java_classloaders_developing_own_classloader/source/jvm_classloader_scheme.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_18_java_double_check_locking_pattern/Singleton.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._18_java_double_check_locking_pattern; 2 | 3 | public class Singleton { 4 | private static volatile Singleton instance; 5 | 6 | private Singleton() {} 7 | 8 | public static Singleton getInstance() { 9 | if (instance == null) { 10 | synchronized (Singleton.class) { 11 | if (instance == null) { 12 | instance = new Singleton(); 13 | } 14 | } 15 | } 16 | return instance; 17 | } 18 | } -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_18_java_double_check_locking_pattern/source/java_logo.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_18_java_double_check_locking_pattern/source/java_logo.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_18_java_double_check_locking_pattern/source/singleton_scheme.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_18_java_double_check_locking_pattern/source/singleton_scheme.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_19_java_event_driven_architecture/source/flow_scheme.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_19_java_event_driven_architecture/source/flow_scheme.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_19_java_event_driven_architecture/source/java_logo.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_19_java_event_driven_architecture/source/java_logo.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_19_java_event_driven_architecture/source/microservice_interactions_scheme.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_19_java_event_driven_architecture/source/microservice_interactions_scheme.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_19_java_event_driven_architecture/source/service_structure_scheme.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_19_java_event_driven_architecture/source/service_structure_scheme.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_1_prefix_sum/PrefixSumExample.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._1_prefix_sum; 2 | 3 | public class PrefixSumExample { 4 | public int[] findPrefix(int[] a) { 5 | int n = a.length; 6 | int[] prefix = new int[n + 1]; 7 | for (int i = 0; i < n; i++) { 8 | prefix[i + 1] = prefix[i] + a[i]; 9 | } 10 | return prefix; 11 | } 12 | 13 | public static void main(String[] args) { 14 | int[] inputArray = {1, 2, 3, 4, 5}; 15 | PrefixSumExample prefixSumExample = new PrefixSumExample(); 16 | int[] prefixSum = prefixSumExample.findPrefix(inputArray); 17 | System.out.println("Prefix sum array:"); 18 | for (int num : prefixSum) { 19 | System.out.print(num + " "); 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_1_prefix_sum/prefix_sum.md: -------------------------------------------------------------------------------- 1 | # Prefix Sums and Applications 2 | 3 | In the realm of computer science and mathematics, efficient algorithms play a crucial role in solving complex problems. One such algorithmic technique that finds extensive application in various domains is prefix sums. Originally designed for one-dimensional arrays, prefix sums have been extended to cater to higher dimensions, notably in the form of 2-dimensional prefix sums, which offer remarkable solutions to a wide array of computational challenges. In this article, we delve into the concepts of prefix sums, particularly focusing on half intervals. 4 | 5 | ### Prefix Sums: A Primer 6 | 7 | Prefix sums, also known as cumulative sums, are a fundamental concept in computer science and mathematics. The essence of prefix sums lies in the idea of precomputing cumulative totals of elements in an array up to a certain index. This precomputation allows for swift calculation of sums of subarrays, significantly enhancing efficiency in various algorithms and computations. 8 | 9 | The process of computing prefix sums is straightforward. Given an array a of length n, the prefix sum, on half interval of array prefix can be generated as follows: 10 | 11 | ```java 12 | prefix[0] = 0 13 | prefix[i] = a[0] + a[1] + ... + a[i - 1] 14 | prefix[i + 1] = a[0] + a[1] + ... + a[i - 1] + ar[i] 15 | prefix[i + 1] = prefix[i] + a[i] 16 | ``` 17 | 18 | Let’s assume that we have such array: 19 | 20 | ```java 21 | a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 22 | ``` 23 | 24 | Than, our prefix sum array: 25 | 26 | ```java 27 | prefix = [0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55] 28 | ``` 29 | 30 | Half interval is usefully to avoid such kind of indexes prefix[i — 1]. And in mathematical meaning this will be half interval [left, right) 31 | 32 | ```java 33 | sum_on_interval = prefix[right] - prefix[left] 34 | ``` 35 | 36 | Calculation: 37 | 38 | 39 | ```java 40 | int[] findPrefix(int[] a) { 41 | int n = a.length; 42 | int[] prefix = new int[n + 1]; 43 | for (int i = 0; i < n; i++) { 44 | prefix[i + 1] = prefix[i] + a[i]; 45 | } 46 | return prefix; 47 | } 48 | ``` 49 | 50 | To calculate sum from [l, r) you just need to do the following: 51 | 52 | ```java 53 | prefix[r] - prefix[l] 54 | ``` 55 | 56 | Using half intervals [l, r), instead intervals [l, r]. Helps us avoiding corner cases prefix[right] - prefix[left -1] and handle corner cases left == 0. 57 | 58 | Creation of prefix sum takes O(N) by time and O(N) memory (as we need an array of length N). Sum calculating on prefix array takes O(1) complexity. It is useful for some applications as additional data structure. 59 | 60 | As an example you could try to apply this approach on https://leetcode.com/problems/product-of-array-except-self/ 61 | 62 | Full example you can find on my Github. [Github](https://github.com/alxkm/articles/blob/master/src/main/java/org/alx/article/_1_prefix_sum/PrefixSumExample.java) 63 | 64 | Thank you for your attention! -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_20_java_iot/source/java_logo.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_20_java_iot/source/java_logo.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_20_java_iot/source/pi4j_logo.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_20_java_iot/source/pi4j_logo.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_21_java_iot_pi4j/source/java_logo.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_21_java_iot_pi4j/source/java_logo.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_21_java_iot_pi4j/source/pi4j_logo.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_21_java_iot_pi4j/source/pi4j_logo.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_22_java_iot_blynk/source/blynk_1.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_22_java_iot_blynk/source/blynk_1.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_22_java_iot_blynk/source/blynk_2.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_22_java_iot_blynk/source/blynk_2.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_22_java_iot_blynk/source/java_logo.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_22_java_iot_blynk/source/java_logo.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_23_java_microservices_architecture_patterns/source/api_gateway.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_23_java_microservices_architecture_patterns/source/api_gateway.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_23_java_microservices_architecture_patterns/source/bulkhead.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_23_java_microservices_architecture_patterns/source/bulkhead.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_23_java_microservices_architecture_patterns/source/circuit_breaker.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_23_java_microservices_architecture_patterns/source/circuit_breaker.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_23_java_microservices_architecture_patterns/source/cqrs.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_23_java_microservices_architecture_patterns/source/cqrs.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_23_java_microservices_architecture_patterns/source/java_logo.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_23_java_microservices_architecture_patterns/source/java_logo.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_23_java_microservices_architecture_patterns/source/load_balancing.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_23_java_microservices_architecture_patterns/source/load_balancing.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_23_java_microservices_architecture_patterns/source/retry.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_23_java_microservices_architecture_patterns/source/retry.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_23_java_microservices_architecture_patterns/source/saga.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_23_java_microservices_architecture_patterns/source/saga.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_23_java_microservices_architecture_patterns/source/service_registry.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_23_java_microservices_architecture_patterns/source/service_registry.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_24_solid/interface_segregation_principle/area_fixed_example/AreaFixedExample.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._24_solid.interface_segregation_principle.area_fixed_example; 2 | 3 | interface AreaCalculatable { 4 | double calculateArea(); 5 | } 6 | 7 | interface Shape { 8 | // Other shape-related methods 9 | } 10 | 11 | class Circle implements AreaCalculatable, Shape { 12 | private final double radius; 13 | 14 | public Circle(double radius) { 15 | this.radius = radius; 16 | } 17 | 18 | @Override 19 | public double calculateArea() { 20 | return Math.PI * radius * radius; 21 | } 22 | } 23 | 24 | class Rectangle implements AreaCalculatable, Shape { 25 | private final double width; 26 | private final double height; 27 | 28 | public Rectangle(double width, double height) { 29 | this.width = width; 30 | this.height = height; 31 | } 32 | 33 | @Override 34 | public double calculateArea() { 35 | return width * height; 36 | } 37 | } 38 | 39 | class Square implements AreaCalculatable, Shape { 40 | private final double side; 41 | 42 | public Square(double side) { 43 | this.side = side; 44 | } 45 | 46 | @Override 47 | public double calculateArea() { 48 | return side * side; 49 | } 50 | } 51 | 52 | public class AreaFixedExample { 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_24_solid/interface_segregation_principle/dependency_inversion_principle/notification_example/Main.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._24_solid.interface_segregation_principle.dependency_inversion_principle.notification_example; 2 | 3 | public class Main { 4 | public static void main(String[] args) { 5 | PaymentService paymentService = new PaymentService(); 6 | paymentService.processPayment(100.0); 7 | } 8 | } -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_24_solid/interface_segregation_principle/dependency_inversion_principle/notification_example/NotificationService.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._24_solid.interface_segregation_principle.dependency_inversion_principle.notification_example; 2 | 3 | public class NotificationService { 4 | public void sendNotification(String message) { 5 | // Logic to send notification 6 | System.out.println("Notification sent: " + message); 7 | } 8 | } -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_24_solid/interface_segregation_principle/dependency_inversion_principle/notification_example/PaymentService.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._24_solid.interface_segregation_principle.dependency_inversion_principle.notification_example; 2 | 3 | public class PaymentService { 4 | private NotificationService notificationService; 5 | 6 | public PaymentService() { 7 | this.notificationService = new NotificationService(); // Direct dependency 8 | } 9 | 10 | public void processPayment(double amount) { 11 | // Logic to process payment 12 | System.out.println("Payment processed: $" + amount); 13 | notificationService.sendNotification("Payment of $" + amount + " processed successfully"); 14 | } 15 | } -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_24_solid/interface_segregation_principle/dependency_inversion_principle/notification_fixed_example/Main.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._24_solid.interface_segregation_principle.dependency_inversion_principle.notification_fixed_example; 2 | 3 | public class Main { 4 | public static void main(String[] args) { 5 | NotificationSender notificationSender = new NotificationService(); 6 | PaymentService paymentService = new PaymentService(notificationSender); 7 | paymentService.processPayment(100.0); 8 | } 9 | } -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_24_solid/interface_segregation_principle/dependency_inversion_principle/notification_fixed_example/NotificationSender.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._24_solid.interface_segregation_principle.dependency_inversion_principle.notification_fixed_example; 2 | 3 | public interface NotificationSender { 4 | void sendNotification(String message); 5 | } -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_24_solid/interface_segregation_principle/dependency_inversion_principle/notification_fixed_example/NotificationService.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._24_solid.interface_segregation_principle.dependency_inversion_principle.notification_fixed_example; 2 | 3 | public class NotificationService implements NotificationSender { 4 | @Override 5 | public void sendNotification(String message) { 6 | // Logic to send notification 7 | System.out.println("Notification sent: " + message); 8 | } 9 | } -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_24_solid/interface_segregation_principle/dependency_inversion_principle/notification_fixed_example/PaymentService.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._24_solid.interface_segregation_principle.dependency_inversion_principle.notification_fixed_example; 2 | 3 | public class PaymentService { 4 | private NotificationSender notificationSender; 5 | 6 | public PaymentService(NotificationSender notificationSender) { 7 | this.notificationSender = notificationSender; // Dependency injection via constructor 8 | } 9 | 10 | public void processPayment(double amount) { 11 | // Logic to process payment 12 | System.out.println("Payment processed: $" + amount); 13 | notificationSender.sendNotification("Payment of $" + amount + " processed successfully"); 14 | } 15 | } -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_24_solid/interface_segregation_principle/simple_example/InterfaceSegregationExample.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._24_solid.interface_segregation_principle.simple_example; 2 | 3 | interface Shape { 4 | double calculateArea(); 5 | } 6 | 7 | class Circle implements Shape { 8 | private final double radius; 9 | 10 | public Circle(double radius) { 11 | this.radius = radius; 12 | } 13 | 14 | @Override 15 | public double calculateArea() { 16 | return Math.PI * radius * radius; 17 | } 18 | } 19 | 20 | class Rectangle implements Shape { 21 | private final double width; 22 | private final double height; 23 | 24 | public Rectangle(double width, double height) { 25 | this.width = width; 26 | this.height = height; 27 | } 28 | 29 | @Override 30 | public double calculateArea() { 31 | return width * height; 32 | } 33 | } 34 | 35 | class Square implements Shape { 36 | private final double side; 37 | 38 | public Square(double side) { 39 | this.side = side; 40 | } 41 | 42 | // Not applicable for all shapes, violating the principle 43 | @Override 44 | public double calculateArea() { 45 | return side * side; 46 | } 47 | } 48 | 49 | public class InterfaceSegregationExample { 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_24_solid/liskov_substitution_principle/logger_example/LoggerExample.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._24_solid.liskov_substitution_principle.logger_example; 2 | 3 | import java.io.FileWriter; 4 | import java.io.IOException; 5 | 6 | class Logger { 7 | void log(String text) { 8 | System.out.println(text); 9 | } 10 | } 11 | 12 | class FileLogger extends Logger { 13 | private final String path; 14 | 15 | FileLogger(String path) { 16 | this.path = path; 17 | } 18 | 19 | @Override 20 | void log(String text) { 21 | try { 22 | FileWriter writer = new FileWriter(path, true); 23 | writer.write(text + "\n"); 24 | writer.close(); 25 | } catch (IOException e) { 26 | e.printStackTrace(); 27 | } 28 | } 29 | } 30 | 31 | class HttpLogger extends Logger { 32 | private final String ip; 33 | private final int port; 34 | 35 | HttpLogger(String ip, int port) { 36 | this.ip = ip; 37 | this.port = port; 38 | } 39 | 40 | @Override 41 | void log(String text) { 42 | // implementation 43 | } 44 | 45 | void openConnection() { 46 | // implementation 47 | } 48 | 49 | void closeConnection() { 50 | // implementation 51 | } 52 | } 53 | 54 | public class LoggerExample { 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_24_solid/liskov_substitution_principle/number_example/NumberExample.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._24_solid.liskov_substitution_principle.number_example; 2 | 3 | class NumberAdder { 4 | public int add(int a, int b) { 5 | return a + b; 6 | } 7 | } 8 | 9 | class ExtendedNumberAdder extends NumberAdder { 10 | @Override 11 | public int add(int a, int b) { 12 | throw new UnsupportedOperationException("This operation is not supported"); 13 | } 14 | } 15 | 16 | public class NumberExample { 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_24_solid/liskov_substitution_principle/vehicle_example/VehicleExample.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._24_solid.liskov_substitution_principle.vehicle_example; 2 | 3 | class Vehicle { 4 | void accelerate() { 5 | // implementation 6 | } 7 | 8 | void slowDown() { 9 | // implementation 10 | } 11 | 12 | void turn(int angle) { 13 | // implementation 14 | } 15 | } 16 | 17 | class Car extends Vehicle { 18 | } 19 | 20 | class Bus extends Vehicle { 21 | } 22 | 23 | // Train class 24 | class Train extends Vehicle { 25 | // Overridden method 26 | @Override 27 | void turn(int angle) { 28 | // implementation specific to trains 29 | } 30 | } 31 | 32 | public class VehicleExample { 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_24_solid/liskov_substitution_principle/vehicle_fixed_example/VehicleExampleFixed.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._24_solid.liskov_substitution_principle.vehicle_fixed_example; 2 | 3 | class Vehicle { 4 | void accelerate() { 5 | // implementation 6 | } 7 | 8 | void slowDown() { 9 | // implementation 10 | } 11 | 12 | void turn(int angle) { 13 | // implementation 14 | } 15 | } 16 | 17 | // Parent class for vehicles with free directional movement 18 | class FreeDirectionalVehicle extends Vehicle { 19 | // Methods for free directional movement 20 | void turnLeft() { 21 | // implementation 22 | } 23 | 24 | void turnRight() { 25 | // implementation 26 | } 27 | } 28 | 29 | // Parent class for vehicles with bidirectional movement 30 | class BidirectionalVehicle extends Vehicle { 31 | // Methods for bidirectional movement 32 | void moveForward() { 33 | // implementation 34 | } 35 | 36 | void moveBackward() { 37 | // implementation 38 | } 39 | } 40 | 41 | // Car class 42 | class Car extends FreeDirectionalVehicle { 43 | // Car-specific methods and properties 44 | } 45 | 46 | // Bus class 47 | class Bus extends FreeDirectionalVehicle { 48 | // Bus-specific methods and properties 49 | } 50 | 51 | // Train class 52 | class Train extends BidirectionalVehicle { 53 | // Train-specific methods and properties 54 | } 55 | 56 | public class VehicleExampleFixed { 57 | 58 | } 59 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_24_solid/open_closed_principle/pipe_line_example/Main.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._24_solid.open_closed_principle.pipe_line_example; 2 | 3 | import java.util.List; 4 | 5 | class ImageBitmap { 6 | 7 | } 8 | 9 | // Functional interface for pipe methods 10 | @FunctionalInterface 11 | interface PipeMethod { 12 | void apply(ImageBitmap bitmap); 13 | } 14 | 15 | // Pipeline class for sequential processing 16 | class Pipeline { 17 | private ImageBitmap bitmap; 18 | 19 | public Pipeline(ImageBitmap bitmap) { 20 | this.bitmap = bitmap; 21 | } 22 | 23 | public void pipe(PipeMethod method) { 24 | method.apply(this.bitmap); 25 | } 26 | 27 | public ImageBitmap getResult() { 28 | return this.bitmap; 29 | } 30 | } 31 | 32 | // ImageProcessor class to process images using pipeline 33 | class ImageProcessor { 34 | public static ImageBitmap processImage(ImageBitmap bitmap, List pipeMethods) { 35 | Pipeline pipeline = new Pipeline(bitmap); 36 | pipeMethods.forEach(method -> pipeline.pipe(method)); 37 | 38 | return pipeline.getResult(); 39 | } 40 | } 41 | 42 | // Usage example 43 | public class Main { 44 | public static void main(String[] args) { 45 | ImageBitmap scannedImage = new ImageBitmap(); 46 | List pipeMethods = List.of( 47 | Main::fixColorBalance, 48 | Main::increaseContrast, 49 | Main::fixSkew, 50 | Main::highlightLetters 51 | ); 52 | 53 | ImageBitmap result = ImageProcessor.processImage(scannedImage, pipeMethods); 54 | } 55 | 56 | // Example pipe methods 57 | private static void fixColorBalance(ImageBitmap bitmap) { 58 | // Implementation 59 | } 60 | 61 | private static void increaseContrast(ImageBitmap bitmap) { 62 | // Implementation 63 | } 64 | 65 | private static void fixSkew(ImageBitmap bitmap) { 66 | // Implementation 67 | } 68 | 69 | private static void highlightLetters(ImageBitmap bitmap) { 70 | // Implementation 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_24_solid/open_closed_principle/simple_example/Main.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._24_solid.open_closed_principle.simple_example; 2 | 3 | // Interface defining a shape 4 | interface Shape { 5 | double area(); 6 | } 7 | 8 | // Concrete implementation of Shape for a rectangle 9 | class Rectangle implements Shape { 10 | private double width; 11 | private double height; 12 | 13 | public Rectangle(double width, double height) { 14 | this.width = width; 15 | this.height = height; 16 | } 17 | 18 | @Override 19 | public double area() { 20 | return width * height; 21 | } 22 | } 23 | 24 | // Concrete implementation of Shape for a circle 25 | class Circle implements Shape { 26 | private double radius; 27 | 28 | public Circle(double radius) { 29 | this.radius = radius; 30 | } 31 | 32 | @Override 33 | public double area() { 34 | return Math.PI * radius * radius; 35 | } 36 | } 37 | 38 | // Utility class to calculate total area of shapes 39 | class AreaCalculator { 40 | public static double calculateTotalArea(Shape[] shapes) { 41 | double totalArea = 0.0; 42 | for (Shape shape : shapes) { 43 | totalArea += shape.area(); 44 | } 45 | return totalArea; 46 | } 47 | } 48 | 49 | public class Main { 50 | public static void main(String[] args) { 51 | Shape[] shapes = new Shape[] { 52 | new Rectangle(5, 4), 53 | new Circle(3) 54 | }; 55 | 56 | double totalArea = AreaCalculator.calculateTotalArea(shapes); 57 | System.out.println("Total area of shapes: " + totalArea); 58 | } 59 | } -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_24_solid/single_responsibiliy_principle/AccessManager.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._24_solid.single_responsibiliy_principle; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Date; 5 | import java.util.List; 6 | import java.util.stream.Collectors; 7 | 8 | public class AccessManager { 9 | public static boolean hasUnlimitedContentAccess(User user) { 10 | Date now = new Date(); 11 | return user.getSubscriptionType() == SubscriptionType.VIP 12 | && user.getSubscriptionExpirationDate().after(now); 13 | } 14 | 15 | public static List getBasicContent(List movies) { 16 | return movies.stream() 17 | .filter(movie -> SubscriptionType.STANDARD.equals(movie.getSubscriptionType())) 18 | .collect(Collectors.toList()); 19 | } 20 | 21 | public static List getPremiumContent(List movies) { 22 | return movies 23 | .stream() 24 | .filter(movie -> SubscriptionType.VIP.equals(movie.getSubscriptionType())) 25 | .collect(Collectors.toList()); 26 | } 27 | 28 | public static List getContentForUserWithBasicAccess(List movies) { 29 | return getBasicContent(movies); 30 | } 31 | 32 | public static List getContentForUserWithUnlimitedAccess(List movies, User user) { 33 | if (SubscriptionType.VIP.equals(user.getSubscriptionType())) { 34 | return getPremiumContent(movies); 35 | } 36 | return new ArrayList<>(); 37 | } 38 | } -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_24_solid/single_responsibiliy_principle/Movie.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._24_solid.single_responsibiliy_principle; 2 | 3 | public class Movie { 4 | private final SubscriptionType subscriptionType; 5 | 6 | public Movie(SubscriptionType subscriptionType) { 7 | this.subscriptionType = subscriptionType; 8 | } 9 | 10 | public SubscriptionType getSubscriptionType() { 11 | return subscriptionType; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_24_solid/single_responsibiliy_principle/SingleResponsibilityPrincipleExample.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._24_solid.single_responsibiliy_principle; 2 | 3 | 4 | 5 | 6 | 7 | 8 | public class SingleResponsibilityPrincipleExample { 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_24_solid/single_responsibiliy_principle/SubscriptionType.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._24_solid.single_responsibiliy_principle; 2 | 3 | public enum SubscriptionType {STANDARD,VIP} -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_24_solid/single_responsibiliy_principle/User.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._24_solid.single_responsibiliy_principle; 2 | 3 | import java.util.Date; 4 | 5 | public class User { 6 | private final String firstName; 7 | private final String lastName; 8 | private final String email; 9 | private final SubscriptionType subscriptionType; 10 | private final Date subscriptionExpirationDate; 11 | 12 | public User(String firstName, String lastName, String email, SubscriptionType subscriptionType, Date subscriptionExpirationDate) { 13 | this.firstName = firstName; 14 | this.lastName = lastName; 15 | this.email = email; 16 | this.subscriptionType = subscriptionType; 17 | this.subscriptionExpirationDate = subscriptionExpirationDate; 18 | } 19 | 20 | public String getName() { 21 | return firstName + " " + lastName; 22 | } 23 | 24 | public boolean hasExtraAccess() { 25 | Date now = new Date(); 26 | return subscriptionType == SubscriptionType.VIP && subscriptionExpirationDate.after(now); 27 | } 28 | 29 | public String getFirstName() { 30 | return firstName; 31 | } 32 | 33 | public String getLastName() { 34 | return lastName; 35 | } 36 | 37 | public String getEmail() { 38 | return email; 39 | } 40 | 41 | public SubscriptionType getSubscriptionType() { 42 | return subscriptionType; 43 | } 44 | 45 | public Date getSubscriptionExpirationDate() { 46 | return subscriptionExpirationDate; 47 | } 48 | } -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_25_global_lock/Payment.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._25_global_lock; 2 | 3 | public class Payment { 4 | } 5 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_25_global_lock/Product.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._25_global_lock; 2 | 3 | public class Product { 4 | private final String id; 5 | 6 | public Product(String id) { 7 | this.id = id; 8 | } 9 | 10 | public String getId() { 11 | return id; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_25_global_lock/ProductService.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._25_global_lock; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.jdbc.core.JdbcTemplate; 5 | import org.springframework.stereotype.Service; 6 | import org.springframework.transaction.annotation.Transactional; 7 | import org.springframework.integration.support.locks.LockRegistry; 8 | 9 | import java.util.List; 10 | import java.util.concurrent.locks.Lock; 11 | 12 | @Service 13 | public class ProductService { 14 | 15 | @Autowired 16 | private LockRegistry lockRegistry; 17 | @Autowired 18 | private JdbcTemplate jdbcTemplate; 19 | 20 | public void buyProducts1(List products, Payment userPayment) { 21 | 22 | // execute check "SELECT 1 FROM Store WHERE id = ? AND amount > 1"; 23 | // execute insert payment "INSERT INTO Payment (amount, transaction) VALUES ..."; 24 | // execute insert order "INSERT INTO ProductOrder (payment, product_id) VALUES ..." 25 | // execute store update "UPDATE Store SET amount = amount - 1 WHERE id = ?" 26 | 27 | final String checkSql = 28 | "SELECT 1 FROM Store WHERE id = ? AND amount > 1"; 29 | //jdbcTemplate... 30 | final String insertPaymentSql = 31 | "INSERT INTO Payment (amount, transaction) VALUES ..."; 32 | //jdbcTemplate... 33 | final String insertOrderSql = 34 | "INSERT INTO ProductOrder (payment, product_id) VALUES ..."; 35 | //jdbcTemplate... 36 | final String updateStoreSql = 37 | "UPDATE Store SET amount = amount - 1 WHERE id = ?"; 38 | //jdbcTemplate... 39 | } 40 | 41 | @Transactional 42 | public void buyProducts(List products, Payment userPayment) { 43 | for (Product product : products) { 44 | Lock lock = lockRegistry.obtain(product.getId()); 45 | lock.lock(); // lock.tryLock(); 46 | try { 47 | doInsertAndUpdate(product); 48 | } catch (InterruptedException e) { 49 | Thread.currentThread().interrupt(); 50 | } finally { 51 | lock.unlock(); 52 | } 53 | } 54 | } 55 | 56 | private void doInsertAndUpdate(Product product) throws InterruptedException { 57 | // Insert and update logic goes here 58 | } 59 | } -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_25_global_lock/source/classes.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_25_global_lock/source/classes.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_25_global_lock/source/sequence_diagram.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_25_global_lock/source/sequence_diagram.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_25_global_lock/source/spring.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_25_global_lock/source/spring.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_26_scheduling_async/AsyncConfig.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._26_scheduling_async; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.scheduling.annotation.EnableAsync; 6 | import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; 7 | 8 | import java.util.concurrent.Executor; 9 | 10 | @Configuration 11 | @EnableAsync 12 | public class AsyncConfig { 13 | 14 | @Bean(name = "jobExecutor") 15 | public Executor jobExecutor() { 16 | ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); 17 | executor.setCorePoolSize(10); 18 | executor.setMaxPoolSize(20); 19 | executor.setQueueCapacity(30); 20 | executor.setThreadNamePrefix("jobExecutor-"); 21 | executor.initialize(); 22 | return executor; 23 | } 24 | } -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_26_scheduling_async/MyScheduledTasks.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._26_scheduling_async; 2 | 3 | import org.springframework.scheduling.annotation.Scheduled; 4 | import org.springframework.stereotype.Component; 5 | 6 | @Component 7 | public class MyScheduledTasks { 8 | @Scheduled(cron = "*/1 * * * * *") // Execute every 1 second 9 | public void task1() { 10 | // Task logic goes here 11 | System.out.println("Task 1 executed."); 12 | } 13 | 14 | @Scheduled(cron = "*/5 * * * * *") // Execute every 5 second 15 | public void task2() throws InterruptedException { 16 | // Task logic goes here 17 | System.out.println("Task 2 executed."); 18 | Thread.sleep(3000); 19 | } 20 | } -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_26_scheduling_async/MyScheduledTasksExtended.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._26_scheduling_async; 2 | 3 | import org.springframework.scheduling.annotation.Async; 4 | import org.springframework.scheduling.annotation.Scheduled; 5 | import org.springframework.stereotype.Component; 6 | 7 | @Component 8 | public class MyScheduledTasksExtended { 9 | @Scheduled(cron = "*/1 * * * * *") // Execute every 1 second 10 | @Async // Execute in a separate thread 11 | public void task1() { 12 | // Task logic goes here 13 | System.out.println("Task 1 executed."); 14 | } 15 | 16 | @Scheduled(cron = "*/5 * * * * *") // Execute every 5 seconds 17 | @Async // Execute in a separate thread 18 | public void task2() { 19 | // Task logic goes here 20 | System.out.println("Task 2 executed."); 21 | try { 22 | Thread.sleep(3000); 23 | } catch (InterruptedException e) { 24 | // Handle interrupted exception 25 | e.printStackTrace(); 26 | } 27 | } 28 | } -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_26_scheduling_async/SchedulerConfig.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._26_scheduling_async; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.scheduling.annotation.SchedulingConfigurer; 6 | import org.springframework.scheduling.config.ScheduledTaskRegistrar; 7 | 8 | import java.util.concurrent.Executor; 9 | import java.util.concurrent.Executors; 10 | 11 | @Configuration 12 | public class SchedulerConfig implements SchedulingConfigurer { 13 | 14 | @Override 15 | public void configureTasks(ScheduledTaskRegistrar taskRegistrar) { 16 | taskRegistrar.setScheduler(taskExecutor()); 17 | } 18 | 19 | @Bean 20 | public Executor taskExecutor() { 21 | return Executors.newScheduledThreadPool(10); 22 | } 23 | 24 | public void shutdown() { 25 | 26 | } 27 | 28 | } -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_26_scheduling_async/source/spring.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_26_scheduling_async/source/spring.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_27_synchronization_java/SynchronizationExample.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._27_synchronization_java; 2 | 3 | import java.util.concurrent.locks.Lock; 4 | import java.util.concurrent.locks.ReentrantLock; 5 | 6 | public class SynchronizationExample { 7 | public synchronized void synchronizedMethod() { 8 | // Synchronized method body 9 | } 10 | 11 | public void someMethod() { 12 | // Non-synchronized code 13 | 14 | synchronized (this) { 15 | // Synchronized code block 16 | } 17 | 18 | // Non-synchronized code 19 | } 20 | 21 | private final Lock lock = new ReentrantLock(); 22 | 23 | public void synchronizedMethodWithLock() { 24 | lock.lock(); // Acquire the lock 25 | try { 26 | // Synchronized method body 27 | } finally { 28 | lock.unlock(); // Release the lock in a finally block 29 | } 30 | } 31 | 32 | public void synchronizedMethodWithLockAndWithAdditionalLogic() { 33 | // Non-synchronized code 34 | 35 | lock.lock(); // Acquire the lock 36 | try { 37 | // Synchronized code block 38 | } finally { 39 | lock.unlock(); // Release the lock in a finally block 40 | } 41 | 42 | // Non-synchronized code 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_27_synchronization_java/source/java.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_27_synchronization_java/source/java.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_28_threads_fundamentals/DiningPhilosophers.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._28_threads_fundamentals; 2 | 3 | import java.util.concurrent.Semaphore; 4 | 5 | public class DiningPhilosophers { 6 | private static final int NUM_PHILOSOPHERS = 5; 7 | private static Semaphore[] forks = new Semaphore[NUM_PHILOSOPHERS]; 8 | private static Semaphore dining = new Semaphore(NUM_PHILOSOPHERS - 1); 9 | 10 | public static void main(String[] args) { 11 | for (int i = 0; i < NUM_PHILOSOPHERS; i++) { 12 | forks[i] = new Semaphore(1); 13 | } 14 | 15 | for (int i = 0; i < NUM_PHILOSOPHERS; i++) { 16 | final int philosopherId = i; 17 | new Thread(() -> { 18 | try { 19 | while (true) { 20 | think(philosopherId); 21 | eat(philosopherId); 22 | } 23 | } catch (InterruptedException e) { 24 | e.printStackTrace(); 25 | } 26 | }).start(); 27 | } 28 | } 29 | 30 | private static void think(int philosopherId) throws InterruptedException { 31 | System.out.println("Philosopher " + philosopherId + " is thinking."); 32 | Thread.sleep((long) (Math.random() * 1000)); 33 | } 34 | 35 | private static void eat(int philosopherId) throws InterruptedException { 36 | dining.acquire(); // Limit the number of philosophers dining 37 | 38 | forks[philosopherId].acquire(); // Acquire left fork 39 | forks[(philosopherId + 1) % NUM_PHILOSOPHERS].acquire(); // Acquire right fork 40 | 41 | System.out.println("Philosopher " + philosopherId + " is eating."); 42 | Thread.sleep((long) (Math.random() * 1000)); 43 | 44 | forks[(philosopherId + 1) % NUM_PHILOSOPHERS].release(); // Release right fork 45 | forks[philosopherId].release(); // Release left fork 46 | 47 | dining.release(); // Allow another philosopher to dine 48 | } 49 | } -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_28_threads_fundamentals/ThreadState.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._28_threads_fundamentals; 2 | 3 | public class ThreadState { 4 | 5 | public static void main(String[] args) throws InterruptedException { 6 | Thread t = new Thread(new Runnable() { 7 | public void run() { 8 | Thread self = Thread.currentThread(); 9 | printThreadState(self); // Print thread state 10 | } 11 | }); 12 | 13 | printThreadState(t); // Print thread state 14 | 15 | t.start(); 16 | t.join(); 17 | 18 | if (t.getState() == Thread.State.TERMINATED) { 19 | System.out.println(t.getName() + " has terminated"); // Indicate termination 20 | } 21 | } 22 | 23 | // Method to print thread state 24 | private static void printThreadState(Thread thread) { 25 | System.out.println(thread.getName() + " is " + thread.getState()); 26 | } 27 | } -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_28_threads_fundamentals/ThreadStateExample.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._28_threads_fundamentals; 2 | 3 | public class ThreadStateExample { 4 | 5 | public static void main(String[] args) throws InterruptedException { 6 | Thread thread1 = new Thread(() -> {}); 7 | Thread thread2 = new Thread(() -> {}); 8 | Thread thread3 = new Thread(() -> {}); 9 | thread1.start(); // Start the other thread 10 | try { 11 | thread1.join(); // Wait for the other thread to complete 12 | } catch (InterruptedException e) { 13 | e.printStackTrace(); 14 | } 15 | thread2.start(); 16 | thread3.start(); 17 | 18 | 19 | Thread t = new Thread(() -> { 20 | Thread self = Thread.currentThread(); 21 | printThreadState(self, "Initial State"); // Print initial state 22 | try { 23 | 24 | Thread.sleep(1000); // Simulate some work 25 | 26 | } catch (InterruptedException e) { 27 | e.printStackTrace(); 28 | } 29 | }); 30 | printThreadState(t, "Before start"); 31 | t.start(); 32 | printThreadState(t, "After start"); 33 | t.join(); 34 | printThreadState(t, "After Joint"); 35 | } 36 | 37 | // Method to print thread state 38 | private static void printThreadState(Thread thread, String message) { 39 | 40 | System.out.println(thread.getName() + " is " + thread.getState() + " - " + message); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_28_threads_fundamentals/source/thread_cycle.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_28_threads_fundamentals/source/thread_cycle.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_28_threads_fundamentals/source/title.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_28_threads_fundamentals/source/title.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_29_threads_fundamentals_2/AtomicExample.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._29_threads_fundamentals_2; 2 | 3 | import java.util.concurrent.atomic.AtomicInteger; 4 | 5 | public class AtomicExample { 6 | public static void main(String[] args) { 7 | AtomicInteger counter = new AtomicInteger(0); 8 | 9 | // Increment the counter atomically 10 | counter.incrementAndGet(); 11 | 12 | // Decrement the counter atomically 13 | counter.decrementAndGet(); 14 | 15 | // Add a value to the counter atomically 16 | counter.addAndGet(5); 17 | 18 | // Get the current value of the counter 19 | int value = counter.get(); 20 | System.out.println("Counter value: " + value); 21 | } 22 | } -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_29_threads_fundamentals_2/CompletableFutureExample.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._29_threads_fundamentals_2; 2 | 3 | import java.util.concurrent.CompletableFuture; 4 | import java.util.concurrent.TimeUnit; 5 | 6 | public class CompletableFutureExample { 7 | public static void main(String[] args) { 8 | // Create a CompletableFuture representing an asynchronous computation 9 | CompletableFuture future = CompletableFuture.supplyAsync(() -> { 10 | try { 11 | // Simulate a long-running computation 12 | TimeUnit.SECONDS.sleep(2); 13 | } catch (InterruptedException e) { 14 | e.printStackTrace(); 15 | } 16 | return "Hello, CompletableFuture!"; 17 | }); 18 | 19 | // Attach a callback to handle the result when the computation completes 20 | future.thenAccept(result -> { 21 | System.out.println("Result: " + result); 22 | }); 23 | 24 | // Wait for the CompletableFuture to complete 25 | future.join(); 26 | } 27 | } -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_29_threads_fundamentals_2/MyCallable.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._29_threads_fundamentals_2; 2 | 3 | import java.util.concurrent.Callable; 4 | import java.util.concurrent.ExecutorService; 5 | import java.util.concurrent.Executors; 6 | import java.util.concurrent.Future; 7 | 8 | public class MyCallable implements Callable { 9 | public String call() { 10 | // Task logic goes here 11 | return "Task completed successfully"; 12 | } 13 | 14 | public static void main(String[] args) throws Exception { 15 | // Create an ExecutorService 16 | ExecutorService executor = Executors.newSingleThreadExecutor(); 17 | 18 | // Create an instance of MyCallable 19 | Callable callable = new MyCallable(); 20 | 21 | // Submit the task to the ExecutorService 22 | Future future = executor.submit(callable); 23 | 24 | // Wait for the task to complete and get the result 25 | String result = future.get(); 26 | System.out.println(result); 27 | 28 | // Shutdown the ExecutorService 29 | executor.shutdown(); 30 | } 31 | } -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_29_threads_fundamentals_2/source/title.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_29_threads_fundamentals_2/source/title.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_2_disjoint_set_data_structure/DisjointSetExample.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._2_disjoint_set_data_structure; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | public class DisjointSetExample { 7 | private Map map = new HashMap<>(); 8 | 9 | public void makeSet(int data) { 10 | Node node = new Node(data); 11 | map.put(data, node); 12 | } 13 | 14 | public int findSet(int data) { 15 | return findSet(map.get(data)).data; 16 | } 17 | 18 | private Node findSet(Node node) { 19 | if (node.parent != node) { 20 | node.parent = findSet(node.parent); 21 | } 22 | return node.parent; 23 | } 24 | 25 | public void union(int data1, int data2) { 26 | Node node1 = map.get(data1); 27 | Node node2 = map.get(data2); 28 | 29 | Node parent1 = findSet(node1); 30 | Node parent2 = findSet(node2); 31 | 32 | if (parent1 != parent2) { 33 | if (parent1.rank >= parent2.rank) { 34 | parent1.rank = (parent1.rank == parent2.rank) ? parent1.rank + 1 : parent1.rank; 35 | parent2.parent = parent1; 36 | } else { 37 | parent1.parent = parent2; 38 | } 39 | } 40 | } 41 | 42 | private static class Node { 43 | int data; 44 | Node parent; 45 | int rank; 46 | 47 | Node(int data) { 48 | this.data = data; 49 | this.parent = this; 50 | this.rank = 0; 51 | } 52 | } 53 | 54 | public static void main(String[] args) { 55 | DisjointSetExample disjointSet = new DisjointSetExample(); 56 | 57 | disjointSet.makeSet(1); 58 | disjointSet.makeSet(2); 59 | disjointSet.makeSet(3); 60 | disjointSet.makeSet(4); 61 | disjointSet.makeSet(5); 62 | disjointSet.makeSet(6); 63 | disjointSet.makeSet(7); 64 | 65 | disjointSet.union(1, 2); 66 | disjointSet.union(2, 3); 67 | disjointSet.union(4, 5); 68 | disjointSet.union(6, 7); 69 | disjointSet.union(5, 6); 70 | disjointSet.union(3, 7); 71 | 72 | System.out.println("Representative element of 1: " + disjointSet.findSet(1)); 73 | System.out.println("Representative element of 2: " + disjointSet.findSet(2)); 74 | System.out.println("Representative element of 3: " + disjointSet.findSet(3)); 75 | System.out.println("Representative element of 4: " + disjointSet.findSet(4)); 76 | System.out.println("Representative element of 5: " + disjointSet.findSet(5)); 77 | System.out.println("Representative element of 6: " + disjointSet.findSet(6)); 78 | System.out.println("Representative element of 7: " + disjointSet.findSet(7)); 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_2_disjoint_set_data_structure/disjoint_set.md: -------------------------------------------------------------------------------- 1 | # Disjoint set union data structure 2 | 3 | A disjoint set union (union find) is a data structure enabling the merging of separate sets and addressing different inquiries concerning them, such as determining if elements a and b belong to the same set and finding out the size of the set. 4 | 5 | Structure 6 | 7 | Sets of elements will be represented as trees: each tree represents a single set. The root of each tree serves as the representative or leader of the set, and we will consider the roots as their own ancestors. 8 | 9 | Let’s make an array p, in which for each element we store the number of its ancestor in the tree: 10 | 11 | ```java 12 | int[] p = new int[maxn]; 13 | 14 | for (int i = 0; i < n; i++) { 15 | p[i] = i; 16 | } 17 | ``` 18 | 19 | To inquire about the set containing the element «v» you must traverse the links to reach the root node: 20 | 21 | ```java 22 | int leader(int v) { 23 | return (p[v] == v) ? v : leader(p[v]); 24 | } 25 | ``` 26 | 27 | To combine two sets, you need to hang the root of one by the root of the other: 28 | 29 | ```java 30 | void unite(int a, int b) { 31 | a = leader(a); 32 | b = leader(b); 33 | p[a] = b; 34 | } 35 | ``` 36 | 37 | But this works in worst case on o(n), adding on and on new vertex, which becomes like linked list, which is slow. We improve this using some tricks. 38 | 39 | Path compression heuristic: We can enhance the leader function by implementing path compression. Instead of directly returning the root node, we will update the parent pointers along the path to point directly to the root node, thereby compressing the path to improve future lookups. 40 | 41 | ```java 42 | int leader(int v) { 43 | return (p[v] == v) ? v : (p[v] = leader(p[v])); 44 | } 45 | ``` 46 | 47 | Rank heuristic involves storing the rank of each vertex, which signifies the height of its subtree. When merging trees, we prioritize the root of the new tree as the one with the highest rank. This adjustment of ranks ensures that the leader’s rank increases by one if it equals the rank of another vertex. Ultimately, this heuristic aims to optimize the height of the trees. 48 | 49 | ```java 50 | void unite(int a, int b) { 51 | a = leader(a); 52 | b = leader(b); 53 | if (h[a] > h[b]) { 54 | int temp = a; 55 | a = b; 56 | b = temp; 57 | } 58 | h[b] = Math.max(h[b], h[a] + 1); 59 | p[a] = b; 60 | } 61 | ``` 62 | 63 | Weight heuristic involves tracking the sizes of subtrees for each vertex instead of using ranks. During merging, we’ll allocate the subtrees to the vertex with the larger size. And this is useful for all tasks, because we need it usually for solving some tasks, by themselves. 64 | 65 | Now our solution works O(n log n) on average. But in worst case it will be O(n). 66 | 67 | Try to practice on next leetcode tasks: 68 | 69 | https://leetcode.com/problems/lexicographically-smallest-equivalent-string/ 70 | 71 | https://leetcode.com/problems/number-of-provinces/ 72 | 73 | https://leetcode.com/problems/accounts-merge/ 74 | https://leetcode.com/problems/find-all-people-with-secret/ 75 | 76 | https://leetcode.com/problems/greatest-common-divisor-traversal/ 77 | 78 | Full example you can find on [Github](https://github.com/alxkm/articles/blob/master/src/main/java/org/alx/article/_2_disjoint_set_data_structure/DisjointSetExample.java). -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_30_java_util_concurrent_1/ConcurrentCollectionsExample.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._30_java_util_concurrent_1; 2 | 3 | import java.util.concurrent.BlockingQueue; 4 | import java.util.concurrent.ConcurrentHashMap; 5 | import java.util.concurrent.ConcurrentLinkedQueue; 6 | import java.util.concurrent.CopyOnWriteArrayList; 7 | import java.util.concurrent.LinkedBlockingQueue; 8 | 9 | public class ConcurrentCollectionsExample { 10 | static void concurrentMapSimpleExample() { 11 | ConcurrentHashMap map = new ConcurrentHashMap<>(); 12 | map.put("key", 123); 13 | int value = map.get("key"); 14 | } 15 | 16 | static void concurrentLinkedQueueSimpleExample() { 17 | ConcurrentLinkedQueue queue = new ConcurrentLinkedQueue<>(); 18 | queue.offer("element1"); 19 | String element = queue.poll(); 20 | } 21 | 22 | static void copyOnWriteArrayListSimpleExample() { 23 | CopyOnWriteArrayList list = new CopyOnWriteArrayList<>(); 24 | list.add("element1"); 25 | String element = list.get(0); 26 | } 27 | 28 | static void blockingQueueSimpleExample() throws InterruptedException { 29 | BlockingQueue queue = new LinkedBlockingQueue<>(); 30 | queue.put("element1"); // Blocking operation if queue is full 31 | String element = queue.take(); // Blocking operation if queue is empty 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_30_java_util_concurrent_1/ConditionExample.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._30_java_util_concurrent_1; 2 | 3 | import java.util.concurrent.locks.Condition; 4 | import java.util.concurrent.locks.Lock; 5 | import java.util.concurrent.locks.ReentrantLock; 6 | 7 | public class ConditionExample { 8 | private final Lock lock = new ReentrantLock(); 9 | private final Condition condition = lock.newCondition(); 10 | private boolean conditionMet = false; 11 | 12 | public void awaitCondition() { 13 | lock.lock(); 14 | try { 15 | while (!conditionMet) { 16 | condition.await(); 17 | } 18 | // Continue execution after condition is met 19 | System.out.println("Condition met, continuing execution."); 20 | } catch (InterruptedException e) { 21 | Thread.currentThread().interrupt(); // Handle interrupt appropriately 22 | } finally { 23 | lock.unlock(); 24 | } 25 | } 26 | 27 | public void signalCondition() { 28 | lock.lock(); 29 | try { 30 | conditionMet = true; 31 | condition.signal(); // Signal the waiting thread 32 | } finally { 33 | lock.unlock(); 34 | } 35 | } 36 | 37 | public static void main(String[] args) { 38 | ConditionExample example = new ConditionExample(); 39 | 40 | // Create a thread to wait for the condition 41 | Thread waitingThread = new Thread(example::awaitCondition); 42 | waitingThread.start(); 43 | 44 | // Simulate some work before signaling the condition 45 | try { 46 | Thread.sleep(2000); // Simulate work 47 | } catch (InterruptedException e) { 48 | Thread.currentThread().interrupt(); // Handle interrupt appropriately 49 | } 50 | 51 | // Signal the condition from the main thread 52 | example.signalCondition(); 53 | } 54 | } -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_30_java_util_concurrent_1/ConditionProducerConsumerExample.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._30_java_util_concurrent_1; 2 | 3 | import java.util.concurrent.locks.Condition; 4 | import java.util.concurrent.locks.Lock; 5 | import java.util.concurrent.locks.ReentrantLock; 6 | import java.util.LinkedList; 7 | import java.util.Queue; 8 | 9 | class SharedBuffer { 10 | private final Queue buffer = new LinkedList<>(); 11 | private final int capacity = 10; 12 | private final Lock lock = new ReentrantLock(); 13 | private final Condition notFull = lock.newCondition(); 14 | private final Condition notEmpty = lock.newCondition(); 15 | 16 | public void produce(int value) throws InterruptedException { 17 | lock.lock(); 18 | try { 19 | while (buffer.size() == capacity) { 20 | notFull.await(); // Wait until the buffer has space 21 | } 22 | buffer.add(value); 23 | System.out.println("Produced: " + value); 24 | notEmpty.signal(); // Signal that the buffer is not empty 25 | } finally { 26 | lock.unlock(); 27 | } 28 | } 29 | 30 | public int consume() throws InterruptedException { 31 | lock.lock(); 32 | try { 33 | while (buffer.isEmpty()) { 34 | notEmpty.await(); // Wait until the buffer is not empty 35 | } 36 | int value = buffer.poll(); 37 | System.out.println("Consumed: " + value); 38 | notFull.signal(); // Signal that the buffer has space 39 | return value; 40 | } finally { 41 | lock.unlock(); 42 | } 43 | } 44 | } 45 | 46 | class Producer implements Runnable { 47 | private final SharedBuffer buffer; 48 | 49 | public Producer(SharedBuffer buffer) { 50 | this.buffer = buffer; 51 | } 52 | 53 | @Override 54 | public void run() { 55 | int value = 0; 56 | try { 57 | while (true) { 58 | buffer.produce(value++); 59 | Thread.sleep(100); // Simulate time taken to produce an item 60 | } 61 | } catch (InterruptedException e) { 62 | Thread.currentThread().interrupt(); 63 | } 64 | } 65 | } 66 | 67 | class Consumer implements Runnable { 68 | private final SharedBuffer buffer; 69 | 70 | public Consumer(SharedBuffer buffer) { 71 | this.buffer = buffer; 72 | } 73 | 74 | @Override 75 | public void run() { 76 | try { 77 | while (true) { 78 | buffer.consume(); 79 | Thread.sleep(150); // Simulate time taken to consume an item 80 | } 81 | } catch (InterruptedException e) { 82 | Thread.currentThread().interrupt(); 83 | } 84 | } 85 | } 86 | 87 | public class ConditionProducerConsumerExample { 88 | public static void main(String[] args) { 89 | SharedBuffer buffer = new SharedBuffer(); 90 | Thread producerThread = new Thread(new Producer(buffer)); 91 | Thread consumerThread = new Thread(new Consumer(buffer)); 92 | 93 | producerThread.start(); 94 | consumerThread.start(); 95 | } 96 | } -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_30_java_util_concurrent_1/ExecutorServiceExample.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._30_java_util_concurrent_1; 2 | 3 | import java.util.concurrent.ArrayBlockingQueue; 4 | import java.util.concurrent.ExecutorService; 5 | import java.util.concurrent.Executors; 6 | import java.util.concurrent.Semaphore; 7 | import java.util.concurrent.ThreadPoolExecutor; 8 | import java.util.concurrent.TimeUnit; 9 | import java.util.concurrent.locks.Condition; 10 | import java.util.concurrent.locks.ReentrantLock; 11 | 12 | public class ExecutorServiceExample { 13 | static void simpleExecutorService() { 14 | ExecutorService executor = Executors.newFixedThreadPool(5); 15 | executor.submit(() -> { 16 | // Task logic here 17 | }); 18 | executor.shutdown(); 19 | } 20 | 21 | static void simpleThreadPoolExecutor() { 22 | ThreadPoolExecutor executor = new ThreadPoolExecutor( 23 | 5, // core pool size 24 | 10, // maximum pool size 25 | 60, // keep-alive time for idle threads 26 | TimeUnit.SECONDS, // time unit for keep-alive time 27 | new ArrayBlockingQueue<>(100) // work queue 28 | ); 29 | executor.execute(() -> { 30 | // Task logic here 31 | }); 32 | executor.shutdown(); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_30_java_util_concurrent_1/SynchronizersExample.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._30_java_util_concurrent_1; 2 | 3 | import java.util.concurrent.Semaphore; 4 | import java.util.concurrent.locks.ReentrantLock; 5 | 6 | public class SynchronizersExample { 7 | 8 | static void reentrantLockExample() { 9 | ReentrantLock lock = new ReentrantLock(); 10 | lock.lock(); 11 | try { 12 | // Critical section 13 | } finally { 14 | lock.unlock(); 15 | } 16 | } 17 | 18 | static void semaphoreExample() throws InterruptedException { 19 | Semaphore semaphore = new Semaphore(5); // permits = 5 20 | semaphore.acquire(); // Acquire a permit 21 | try { 22 | // Access shared resource 23 | } finally { 24 | semaphore.release(); // Release the permit 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_30_java_util_concurrent_1/source/concurrent.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_30_java_util_concurrent_1/source/concurrent.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_30_java_util_concurrent_1/source/concurrent_hashmap.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_30_java_util_concurrent_1/source/concurrent_hashmap.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_30_java_util_concurrent_1/source/concurrent_hierarchy1.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_30_java_util_concurrent_1/source/concurrent_hierarchy1.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_30_java_util_concurrent_1/source/concurrent_hierarchy2.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_30_java_util_concurrent_1/source/concurrent_hierarchy2.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_30_java_util_concurrent_1/source/title.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_30_java_util_concurrent_1/source/title.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_31_java_util_concurrent_2/CompletableFutureExample.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._31_java_util_concurrent_2; 2 | 3 | import java.util.concurrent.CompletableFuture; 4 | import java.util.concurrent.TimeUnit; 5 | 6 | public class CompletableFutureExample { 7 | static void completableFutureExample() { 8 | CompletableFuture future = CompletableFuture.completedFuture("value"); 9 | CompletableFuture asyncFuture = CompletableFuture.runAsync(() -> { 10 | // Asynchronous task 11 | }); 12 | CompletableFuture supplyFuture = CompletableFuture.supplyAsync(() -> { 13 | // Asynchronous computation 14 | return 42; 15 | }); 16 | } 17 | 18 | static void completableFutureApplyExample() { 19 | CompletableFuture future = CompletableFuture.supplyAsync(() -> 10) 20 | .thenApplyAsync(result -> result * 2) 21 | .thenApplyAsync(result -> result + 5); 22 | } 23 | 24 | static void completableFutureSupplyAsyncExample() { 25 | CompletableFuture future = CompletableFuture.supplyAsync(() -> { 26 | // Asynchronous computation 27 | throw new RuntimeException("error"); 28 | }).exceptionally(ex -> { 29 | System.out.println("Exception occurred: " + ex.getMessage()); 30 | return 0; 31 | }); 32 | } 33 | 34 | static void completableFutureCombineExample() { 35 | CompletableFuture future1 = CompletableFuture.supplyAsync(() -> 10); 36 | CompletableFuture future2 = CompletableFuture.supplyAsync(() -> 20); 37 | CompletableFuture combinedFuture = future1.thenCombine(future2, (result1, result2) -> result1 + result2); 38 | } 39 | 40 | static void completableFutureCancellationTimeoutExample() { 41 | CompletableFuture future = CompletableFuture.supplyAsync(() -> { 42 | // Asynchronous computation 43 | return null; 44 | }); 45 | future.cancel(true); // Cancel the CompletableFuture 46 | CompletableFuture timedFuture = future.completeOnTimeout(0, 1, TimeUnit.SECONDS); // Complete with default value after timeout 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_31_java_util_concurrent_2/CountdownLatchExample.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._31_java_util_concurrent_2; 2 | 3 | import java.util.concurrent.CountDownLatch; 4 | import java.util.concurrent.Phaser; 5 | 6 | public class CountdownLatchExample { 7 | static void countdownLatchExample() throws InterruptedException { 8 | CountDownLatch latch = new CountDownLatch(3); // Initialize with count 3 9 | // In each thread: 10 | latch.countDown(); // Decrement latch count when task completes 11 | latch.await(); // Block until all tasks complete 12 | } 13 | 14 | static void phaserExample() throws InterruptedException { 15 | Phaser phaser = new Phaser(); 16 | phaser.register(); // Register the current thread 17 | // Perform some work 18 | phaser.arriveAndAwaitAdvance(); // Synchronize at the barrier 19 | // Continue execution after synchronization 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_31_java_util_concurrent_2/ForkJoinPoolExample.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._31_java_util_concurrent_2; 2 | 3 | import java.util.concurrent.ForkJoinPool; 4 | import java.util.concurrent.RecursiveTask; 5 | 6 | class MyTask extends RecursiveTask { 7 | protected Integer compute() { 8 | // Task execution logic 9 | return 42; 10 | } 11 | } 12 | 13 | public class ForkJoinPoolExample { 14 | static void forkJoinPoolExample() { 15 | ForkJoinPool pool = new ForkJoinPool(); 16 | Integer result = pool.invoke(new MyTask()); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_31_java_util_concurrent_2/source/future.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_31_java_util_concurrent_2/source/future.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_31_java_util_concurrent_2/source/java_util_concurrent.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_31_java_util_concurrent_2/source/java_util_concurrent.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_31_java_util_concurrent_2/source/title.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_31_java_util_concurrent_2/source/title.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_32_java_concurrency_best_practices/AsynchronousFileIOExample.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._32_java_concurrency_best_practices; 2 | 3 | import java.nio.ByteBuffer; 4 | import java.nio.channels.AsynchronousFileChannel; 5 | import java.nio.file.Path; 6 | import java.nio.file.Paths; 7 | import java.nio.file.StandardOpenOption; 8 | import java.util.concurrent.Future; 9 | 10 | public class AsynchronousFileIOExample { 11 | 12 | public static void main(String[] args) { 13 | Path path = Paths.get("example.txt"); 14 | 15 | try { 16 | AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open( 17 | path, StandardOpenOption.READ); 18 | 19 | ByteBuffer buffer = ByteBuffer.allocate(1024); 20 | long position = 0; // Start reading from the beginning of the file 21 | 22 | Future readFuture = fileChannel.read(buffer, position); 23 | 24 | while (!readFuture.isDone()) { 25 | // Perform other tasks while waiting for the read operation to complete 26 | System.out.println("Performing other tasks..."); 27 | } 28 | 29 | int bytesRead = readFuture.get(); // Get the number of bytes read 30 | buffer.flip(); // Flip the buffer for reading 31 | 32 | byte[] data = new byte[bytesRead]; 33 | buffer.get(data); // Read data from the buffer 34 | System.out.println("Read data: " + new String(data)); 35 | 36 | fileChannel.close(); // Close the file channel 37 | } catch (Exception e) { 38 | e.printStackTrace(); 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_32_java_concurrency_best_practices/AsynchronousHttpClientExample.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._32_java_concurrency_best_practices; 2 | 3 | import java.net.URI; 4 | import java.net.http.HttpClient; 5 | import java.net.http.HttpRequest; 6 | import java.net.http.HttpResponse; 7 | import java.util.concurrent.CompletableFuture; 8 | 9 | public class AsynchronousHttpClientExample { 10 | 11 | public static void main(String[] args) { 12 | HttpClient httpClient = HttpClient.newHttpClient(); 13 | HttpRequest httpRequest = HttpRequest.newBuilder() 14 | .uri(URI.create("https://jsonplaceholder.typicode.com/posts/1")) 15 | .build(); 16 | 17 | CompletableFuture> responseFuture = httpClient.sendAsync( 18 | httpRequest, HttpResponse.BodyHandlers.ofString()); 19 | 20 | responseFuture.thenAccept(response -> { 21 | int statusCode = response.statusCode(); 22 | String responseBody = response.body(); 23 | System.out.println("Status Code: " + statusCode); 24 | System.out.println("Response Body: " + responseBody); 25 | }).exceptionally(throwable -> { 26 | System.err.println("Error occurred: " + throwable); 27 | return null; 28 | }); 29 | 30 | // Perform other tasks while waiting for the HTTP response 31 | System.out.println("Performing other tasks..."); 32 | } 33 | } -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_32_java_concurrency_best_practices/ConcurrentHashMapExample.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._32_java_concurrency_best_practices; 2 | 3 | import java.util.Map; 4 | import java.util.concurrent.ConcurrentHashMap; 5 | 6 | public class ConcurrentHashMapExample { 7 | static void concurrentHashMapExample(K key1, V value1, K key2, V value2, V newValue, int initialCapacity, int loadFactor) { 8 | // Initialization 9 | ConcurrentHashMap map = new ConcurrentHashMap<>(); 10 | 11 | // Adding and Updating Elements 12 | map.put(key1, value1); 13 | map.put(key2, value2); 14 | 15 | // Retrieving Elements 16 | V value = map.get(key1); 17 | 18 | // Removing Elements 19 | V removedValue = map.remove(key1); 20 | 21 | // Iterating over Elements 22 | for (Map.Entry entry : map.entrySet()) { 23 | // Process each key-value pair 24 | } 25 | 26 | // Atomic Operations 27 | map.putIfAbsent(key1, value); // Adds if absent 28 | map.replace(key1, newValue); // Replaces value 29 | 30 | // Specifying Concurrency Level 31 | int concurrencyLevel = 16; 32 | ConcurrentHashMap newMap = new ConcurrentHashMap<>(initialCapacity, loadFactor, concurrencyLevel); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_32_java_concurrency_best_practices/ExceptionHandlerExample.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._32_java_concurrency_best_practices; 2 | 3 | import java.util.concurrent.CompletableFuture; 4 | import java.util.concurrent.ExecutionException; 5 | import java.util.concurrent.ExecutorService; 6 | import java.util.concurrent.Executors; 7 | import java.util.concurrent.Future; 8 | import java.util.concurrent.TimeUnit; 9 | 10 | public class ExceptionHandlerExample { 11 | static void setDefaultUncaughtExceptionHandlerExample() { 12 | Thread.setDefaultUncaughtExceptionHandler((thread, throwable) -> { 13 | System.err.println("Uncaught exception in thread: " + thread.getName()); 14 | throwable.printStackTrace(); 15 | }); 16 | } 17 | 18 | static void setDefaultUncaughtExceptionHandlerExecutorExample() { 19 | ExecutorService executorService = Executors.newCachedThreadPool(); 20 | Future future = executorService.submit(() -> { 21 | // Task code that may throw an exception 22 | }); 23 | try { 24 | future.get(); // Waits for the task to complete and retrieves the result 25 | } catch (ExecutionException e) { 26 | Throwable cause = e.getCause(); 27 | // Handle the exception 28 | } catch (InterruptedException e) { 29 | throw new RuntimeException(e); 30 | } 31 | } 32 | 33 | static void completableFutureExceptionHandleExample() { 34 | CompletableFuture future = CompletableFuture.supplyAsync(() -> { 35 | // Task code that may throw an exception 36 | return 42; 37 | }).thenApply(result -> { 38 | // Task dependent on the previous result 39 | // Handle exceptions thrown by the previous task 40 | return result * 2; 41 | }).exceptionally(throwable -> { 42 | // Handle exceptions from the preceding tasks 43 | return -1; // Default value or error handling logic 44 | }); 45 | } 46 | 47 | static void executorServiceShutdownExample() { 48 | ExecutorService executorService = Executors.newCachedThreadPool(); 49 | try { 50 | // Submit tasks to the executor service 51 | } finally { 52 | executorService.shutdown(); // Shutdown the executor service 53 | try { 54 | executorService.awaitTermination(1, TimeUnit.MINUTES); // Wait for tasks to complete 55 | } catch (InterruptedException e) { 56 | Thread.currentThread().interrupt(); // Restore interrupted status 57 | } 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_32_java_concurrency_best_practices/ParallelComputationExample.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._32_java_concurrency_best_practices; 2 | 3 | import java.util.Arrays; 4 | import java.util.concurrent.ForkJoinPool; 5 | import java.util.concurrent.RecursiveTask; 6 | 7 | public class ParallelComputationExample { 8 | 9 | // RecursiveTask to compute sum of an array using ForkJoinPool 10 | static class SumTask extends RecursiveTask { 11 | private static final int THRESHOLD = 1000; 12 | private final long[] array; 13 | private final int start; 14 | private final int end; 15 | 16 | SumTask(long[] array, int start, int end) { 17 | this.array = array; 18 | this.start = start; 19 | this.end = end; 20 | } 21 | 22 | @Override 23 | protected Long compute() { 24 | if (end - start <= THRESHOLD) { 25 | // Compute sum directly if array size is small 26 | long sum = 0; 27 | for (int i = start; i < end; i++) { 28 | sum += array[i]; 29 | } 30 | return sum; 31 | } else { 32 | // Split task into subtasks for parallel processing 33 | int mid = (start + end) / 2; 34 | SumTask leftTask = new SumTask(array, start, mid); 35 | SumTask rightTask = new SumTask(array, mid, end); 36 | leftTask.fork(); 37 | return rightTask.compute() + leftTask.join(); 38 | } 39 | } 40 | } 41 | 42 | public static void main(String[] args) { 43 | // Example array for computation 44 | long[] array = new long[1_000_000]; 45 | Arrays.fill(array, 1); // Fill array with 1s 46 | 47 | // Using ForkJoinPool for parallel computation 48 | ForkJoinPool forkJoinPool = new ForkJoinPool(); 49 | long sum = forkJoinPool.invoke(new SumTask(array, 0, array.length)); 50 | System.out.println("Sum using ForkJoinPool: " + sum); 51 | 52 | // Using parallel stream for parallel computation 53 | sum = Arrays.stream(array).parallel().sum(); 54 | System.out.println("Sum using parallel stream: " + sum); 55 | } 56 | } -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_32_java_concurrency_best_practices/source/title.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_32_java_concurrency_best_practices/source/title.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_33_grasp/controller/UserController.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._33_grasp.controller; 2 | 3 | public class UserController { 4 | 5 | private UserService userService; 6 | 7 | public UserController(UserService userService) { 8 | this.userService = userService; 9 | } 10 | 11 | public void handleUserRegistration(String username, String password) { 12 | try { 13 | // Validate user input 14 | if (isValidUsername(username) && isValidPassword(password)) { 15 | // Delegate registration to UserService 16 | userService.registerUser(username, password); 17 | System.out.println("User registered successfully!"); 18 | } else { 19 | System.out.println("Invalid username or password."); 20 | } 21 | } catch (Exception e) { 22 | System.out.println("Error registering user: " + e.getMessage()); 23 | } 24 | } 25 | 26 | private boolean isValidUsername(String username) { 27 | // Validation logic for username 28 | return !username.isEmpty(); 29 | } 30 | 31 | private boolean isValidPassword(String password) { 32 | // Validation logic for password 33 | return password.length() >= 8; 34 | } 35 | } -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_33_grasp/controller/UserService.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._33_grasp.controller; 2 | 3 | public class UserService { 4 | public void registerUser(String username, String password) { 5 | //some logic 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_33_grasp/creator/Customer.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._33_grasp.creator; 2 | 3 | public class Customer { 4 | } 5 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_33_grasp/creator/Order.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._33_grasp.creator; 2 | 3 | import java.util.List; 4 | 5 | public class Order { 6 | private final Customer customer; 7 | private final List products; 8 | 9 | public Order(Customer customer, List products) { 10 | this.customer = customer; 11 | this.products = products; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_33_grasp/creator/OrderRepository.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._33_grasp.creator; 2 | 3 | public class OrderRepository { 4 | public void saveOrder(Order order) { 5 | //some logic 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_33_grasp/creator/OrderService.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._33_grasp.creator; 2 | 3 | import java.util.List; 4 | 5 | public class OrderService { 6 | private final OrderRepository orderRepository; 7 | 8 | public OrderService(OrderRepository orderRepository) { 9 | this.orderRepository = orderRepository; 10 | } 11 | 12 | public void createOrder(Customer customer, List products) { 13 | // Create a new order object 14 | Order order = new Order(customer, products); 15 | 16 | // Save the order to the repository 17 | orderRepository.saveOrder(order); 18 | } 19 | } -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_33_grasp/creator/Product.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._33_grasp.creator; 2 | 3 | public class Product { 4 | } 5 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_33_grasp/indirection/PaymentGateway.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._33_grasp.indirection; 2 | 3 | public class PaymentGateway { 4 | private PaymentProcessor paymentProcessor; 5 | 6 | public PaymentGateway(PaymentProcessor paymentProcessor) { 7 | this.paymentProcessor = paymentProcessor; 8 | } 9 | 10 | public void processPayment(PaymentRequest paymentRequest) { 11 | // Validate payment request 12 | if (isValidPaymentRequest(paymentRequest)) { 13 | // Delegate payment processing to PaymentProcessor 14 | paymentProcessor.processPayment(paymentRequest); 15 | } else { 16 | throw new IllegalArgumentException("Invalid payment request"); 17 | } 18 | } 19 | 20 | private boolean isValidPaymentRequest(PaymentRequest paymentRequest) { 21 | // Validation logic for payment request 22 | return paymentRequest != null && paymentRequest.getAmount() > 0; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_33_grasp/indirection/PaymentProcessor.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._33_grasp.indirection; 2 | 3 | public class PaymentProcessor { 4 | public void processPayment(PaymentRequest paymentRequest) { 5 | // some logic 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_33_grasp/indirection/PaymentRequest.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._33_grasp.indirection; 2 | 3 | public class PaymentRequest { 4 | private final int amount; 5 | 6 | public PaymentRequest(int amount) { 7 | this.amount = amount; 8 | } 9 | 10 | public int getAmount() { 11 | return amount; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_33_grasp/information_expert/Item.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._33_grasp.information_expert; 2 | 3 | public class Item { 4 | private final String name; 5 | private final double price; 6 | 7 | public Item(String name, double price) { 8 | this.name = name; 9 | this.price = price; 10 | } 11 | 12 | public double getPrice() { 13 | return price; 14 | } 15 | 16 | public String getName() { 17 | return name; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_33_grasp/information_expert/ShoppingCart.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._33_grasp.information_expert; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class ShoppingCart { 7 | private List items = new ArrayList<>(); 8 | 9 | public void addItem(Item item) { 10 | items.add(item); 11 | } 12 | 13 | public double calculateTotalPrice() { 14 | double totalPrice = 0; 15 | for (Item item : items) { 16 | totalPrice += item.getPrice(); 17 | } 18 | return totalPrice; 19 | } 20 | } -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_33_grasp/source/grasp.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_33_grasp/source/grasp.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_33_grasp/source/title.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_33_grasp/source/title.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_33_grasp/source/title1.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_33_grasp/source/title1.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_34_dry_kiss_yagni/source/dry.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_34_dry_kiss_yagni/source/dry.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_34_dry_kiss_yagni/source/kiss.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_34_dry_kiss_yagni/source/kiss.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_34_dry_kiss_yagni/source/princeples.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_34_dry_kiss_yagni/source/princeples.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_34_dry_kiss_yagni/source/title.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_34_dry_kiss_yagni/source/title.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_34_dry_kiss_yagni/source/yagni.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_34_dry_kiss_yagni/source/yagni.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_35_abstraction_extensibility_cohesion/abstraction/AbstractClassesExample.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._35_abstraction_extensibility_cohesion.abstraction; 2 | 3 | public class AbstractClassesExample { 4 | abstract class Shape { 5 | abstract double area(); // Abstract method 6 | abstract double perimeter(); // Abstract method 7 | } 8 | 9 | class Circle extends Shape { 10 | double radius; 11 | 12 | Circle(double radius) { 13 | this.radius = radius; 14 | } 15 | 16 | @Override 17 | double area() { 18 | return Math.PI * radius * radius; 19 | } 20 | 21 | @Override 22 | double perimeter() { 23 | return 2 * Math.PI * radius; 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_35_abstraction_extensibility_cohesion/abstraction/InterfacesExample.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._35_abstraction_extensibility_cohesion.abstraction; 2 | 3 | public class InterfacesExample { 4 | interface Printable { 5 | void print(); 6 | } 7 | 8 | class Document implements Printable { 9 | @Override 10 | public void print() { 11 | System.out.println("Printing document..."); 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_35_abstraction_extensibility_cohesion/cohesion/DataProcessor.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._35_abstraction_extensibility_cohesion.cohesion; 2 | 3 | import java.util.List; 4 | 5 | public class DataProcessor { 6 | private List data; 7 | 8 | public void processData() { 9 | // Process data stored in the 'data' list 10 | } 11 | 12 | public void displayData() { 13 | // Display processed data 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_35_abstraction_extensibility_cohesion/cohesion/DatabaseAccessLayer.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._35_abstraction_extensibility_cohesion.cohesion; 2 | 3 | public class DatabaseAccessLayer { 4 | public void queryData() { 5 | // Method to query data from the database 6 | } 7 | 8 | public void updateRecord() { 9 | // Method to update records in the database 10 | } 11 | 12 | public void deleteEntry() { 13 | // Method to delete entries from the database 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_35_abstraction_extensibility_cohesion/cohesion/SequentialProcess.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._35_abstraction_extensibility_cohesion.cohesion; 2 | 3 | public class SequentialProcess { 4 | public void stepOne() { 5 | // Perform step one of the process 6 | } 7 | 8 | public void stepTwo() { 9 | // Perform step two of the process using the output of step one 10 | } 11 | 12 | public void stepThree() { 13 | // Perform step three of the process using the output of step two 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_35_abstraction_extensibility_cohesion/extensibility/AbstractClassesExample.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._35_abstraction_extensibility_cohesion.extensibility; 2 | 3 | public class AbstractClassesExample { 4 | abstract class Animal { 5 | abstract void makeSound(); 6 | } 7 | 8 | class Dog extends Animal { 9 | void makeSound() { 10 | // Implementation for Dog's sound 11 | } 12 | } 13 | 14 | class Cat extends Animal { 15 | void makeSound() { 16 | // Implementation for Cat's sound 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_35_abstraction_extensibility_cohesion/extensibility/DesignPatternsExample.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._35_abstraction_extensibility_cohesion.extensibility; 2 | 3 | public class DesignPatternsExample { 4 | // Factory Pattern 5 | interface Shape { 6 | void draw(); 7 | } 8 | 9 | class Circle implements Shape { 10 | public void draw() { 11 | // Draw a circle 12 | } 13 | } 14 | 15 | class Rectangle implements Shape { 16 | public void draw() { 17 | // Draw a rectangle 18 | } 19 | } 20 | 21 | class ShapeFactory { 22 | Shape createShape(String type) { 23 | if (type.equals("circle")) { 24 | return new Circle(); 25 | } else if (type.equals("rectangle")) { 26 | return new Rectangle(); 27 | } 28 | return null; 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_35_abstraction_extensibility_cohesion/extensibility/InterfacesAndPolymorphismExample.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._35_abstraction_extensibility_cohesion.extensibility; 2 | 3 | public class InterfacesAndPolymorphismExample { 4 | class Shape { 5 | void draw() { 6 | // Base implementation 7 | } 8 | } 9 | 10 | class Circle extends Shape { 11 | void draw() { 12 | // Custom implementation for Circle 13 | } 14 | } 15 | 16 | class Rectangle extends Shape { 17 | void draw() { 18 | // Custom implementation for Rectangle 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_35_abstraction_extensibility_cohesion/extensibility/InterfacesExample.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._35_abstraction_extensibility_cohesion.extensibility; 2 | 3 | public class InterfacesExample { 4 | interface Printable { 5 | void print(); 6 | } 7 | 8 | class Document implements Printable { 9 | public void print() { 10 | // Implementation for printing Document 11 | } 12 | } 13 | 14 | class Report implements Printable { 15 | public void print() { 16 | // Implementation for printing Report 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_35_abstraction_extensibility_cohesion/source/title1.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_35_abstraction_extensibility_cohesion/source/title1.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_35_abstraction_extensibility_cohesion/source/title2.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_35_abstraction_extensibility_cohesion/source/title2.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_35_abstraction_extensibility_cohesion/source/title3.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_35_abstraction_extensibility_cohesion/source/title3.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_36_new_switch_case_java/source/title.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_36_new_switch_case_java/source/title.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_37_spring_beans/EmailNotificationService.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._37_spring_beans; 2 | 3 | public class EmailNotificationService { 4 | private final Sender sender; 5 | 6 | public EmailNotificationService(Sender sender) { 7 | this.sender = sender; 8 | } 9 | 10 | public void send(String message, String email) { 11 | sender.send(message, email); 12 | } 13 | } -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_37_spring_beans/EmailSender.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._37_spring_beans; 2 | 3 | public class EmailSender implements Sender { 4 | @Override 5 | public void send(String message, String address) { 6 | System.out.println("Email sent to " + address); 7 | } 8 | 9 | public void init() { 10 | } 11 | 12 | public void destroy() { 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_37_spring_beans/Sender.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._37_spring_beans; 2 | 3 | @FunctionalInterface 4 | public interface Sender { 5 | void send(String message, String address); 6 | } 7 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_37_spring_beans/applicationContext.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 10 | 11 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_37_spring_beans/source/bean_cycle.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_37_spring_beans/source/bean_cycle.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_37_spring_beans/source/spring.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_37_spring_beans/source/spring.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_37_spring_beans/source/title.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_37_spring_beans/source/title.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_38_builder/User.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._38_builder; 2 | 3 | public class User { 4 | private final String userId; 5 | private final String name; 6 | 7 | public User(String userId, String name) { 8 | this.userId = userId; 9 | this.name = name; 10 | } 11 | 12 | public String getUserId() { 13 | return userId; 14 | } 15 | 16 | public String getName() { 17 | return name; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_38_builder/source/title.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_38_builder/source/title.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_38_builder/user_builder/User.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._38_builder.user_builder; 2 | 3 | public class User { 4 | private String userId; 5 | private String name; 6 | 7 | private User() { 8 | } 9 | 10 | public String getUserId() { 11 | return userId; 12 | } 13 | 14 | public String getName() { 15 | return name; 16 | } 17 | 18 | public static Builder newBuilder() { 19 | return new User().new Builder(); 20 | } 21 | 22 | public class Builder { 23 | 24 | private Builder() { 25 | } 26 | 27 | public Builder setUserId(String userId) { 28 | User.this.userId = userId; 29 | 30 | return this; 31 | } 32 | 33 | public Builder setName(String name) { 34 | User.this.name = name; 35 | 36 | return this; 37 | } 38 | 39 | public User build() { 40 | return User.this; 41 | } 42 | 43 | } 44 | 45 | public static void main(String[] args) { 46 | User user = User.newBuilder().setUserId("123").setName("John").build(); 47 | } 48 | } -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_38_builder/user_builder_extra/User.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._38_builder.user_builder_extra; 2 | 3 | public class User { 4 | private String userId; 5 | private String lastName; 6 | private String firstName; 7 | private String middleName; 8 | private String streetAddress; 9 | private String city; 10 | private String state; 11 | 12 | public User(String userId, String lastName, String firstName, 13 | String middleName, String streetAddress, String city, String state) { 14 | this.userId = userId; 15 | this.lastName = lastName; 16 | this.firstName = firstName; 17 | this.middleName = middleName; 18 | this.streetAddress = streetAddress; 19 | this.city = city; 20 | this.state = state; 21 | } 22 | 23 | public User() { 24 | } 25 | 26 | public User userId(String userId) { 27 | this.userId = userId; 28 | return this; 29 | } 30 | 31 | public User lastName(String lastName) { 32 | this.lastName = lastName; 33 | return this; 34 | } 35 | 36 | public User firstName(String firstName) { 37 | this.firstName = firstName; 38 | return this; 39 | } 40 | 41 | public User middleName(String middleName) { 42 | this.middleName = middleName; 43 | return this; 44 | } 45 | 46 | public User streetAddress(String streetAddress) { 47 | this.streetAddress = streetAddress; 48 | return this; 49 | } 50 | 51 | public User city(String city) { 52 | this.city = city; 53 | return this; 54 | } 55 | 56 | public User state(String state) { 57 | this.state = state; 58 | return this; 59 | } 60 | 61 | public User build() { 62 | return new User(userId, lastName, firstName, middleName, streetAddress, city, state); 63 | } 64 | 65 | public static void main(String[] args) { 66 | User user = new User() 67 | .userId("123") 68 | .lastName("Doe") 69 | .firstName("John") 70 | .middleName("Robert") 71 | .streetAddress("123 Main St") 72 | .city("Anytown") 73 | .state("NY") 74 | .build(); 75 | } 76 | } -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_39_java_architecture_blueprint/source/cache.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_39_java_architecture_blueprint/source/cache.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_39_java_architecture_blueprint/source/documentation.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_39_java_architecture_blueprint/source/documentation.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_39_java_architecture_blueprint/source/layered_architecture.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_39_java_architecture_blueprint/source/layered_architecture.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_39_java_architecture_blueprint/source/test_pyramid.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_39_java_architecture_blueprint/source/test_pyramid.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_39_java_architecture_blueprint/source/title.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_39_java_architecture_blueprint/source/title.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_3_knapsack/Item.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._3_knapsack; 2 | 3 | class Item { 4 | int weight; 5 | int value; 6 | 7 | public Item(int weight, int value) { 8 | this.weight = weight; 9 | this.value = value; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_3_knapsack/KnapsackBruteForce.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._3_knapsack; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class KnapsackBruteForce { 7 | public static List knapsack(int W, List items) { 8 | int n = items.size(); 9 | int maxVal = 0; 10 | int maxWeight = 0; 11 | List result = new ArrayList<>(); 12 | 13 | for (int i = 0; i < (1 << n); i++) { 14 | int totalWeight = 0; 15 | int totalValue = 0; 16 | List currentItems = new ArrayList<>(); 17 | 18 | for (int j = 0; j < n; j++) { 19 | if ((i & (1 << j)) > 0) { 20 | totalWeight += items.get(j).weight; 21 | totalValue += items.get(j).value; 22 | currentItems.add(items.get(j)); 23 | } 24 | } 25 | 26 | if (totalWeight <= W && totalValue > maxVal) { 27 | maxVal = totalValue; 28 | maxWeight = totalWeight; 29 | result = new ArrayList<>(currentItems); 30 | } 31 | } 32 | 33 | System.out.println("Maximum value: " + maxVal); 34 | System.out.println("Total weight: " + maxWeight); 35 | return result; 36 | } 37 | 38 | public static void main(String[] args) { 39 | List items = new ArrayList<>(); 40 | items.add(new Item(2, 12)); 41 | items.add(new Item(1, 10)); 42 | items.add(new Item(3, 20)); 43 | items.add(new Item(2, 15)); 44 | items.add(new Item(4, 25)); 45 | 46 | // Knapsack capacity 47 | int W = 8; 48 | List selectedItems = knapsack(W, items); 49 | 50 | System.out.println("Selected items:"); 51 | for (Item item : selectedItems) { 52 | System.out.println("Weight: " + item.weight + ", Value: " + item.value); 53 | } 54 | } 55 | } -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_3_knapsack/KnapsackDP.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._3_knapsack; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class KnapsackDP { 7 | public static List knapsack(int W, List items) { 8 | int n = items.size(); 9 | int[][] dp = new int[n + 1][W + 1]; 10 | 11 | // Initialize the dp table 12 | for (int i = 0; i <= n; i++) { 13 | for (int j = 0; j <= W; j++) { 14 | if (i == 0 || j == 0) { 15 | dp[i][j] = 0; 16 | } else if (items.get(i - 1).weight <= j) { 17 | dp[i][j] = Math.max(dp[i - 1][j], dp[i - 1][j - items.get(i - 1).weight] + items.get(i - 1).value); 18 | } else { 19 | dp[i][j] = dp[i - 1][j]; 20 | } 21 | } 22 | } 23 | 24 | // Retrieve selected items 25 | List selectedItems = new ArrayList<>(); 26 | int i = n, j = W; 27 | while (i > 0 && j > 0) { 28 | if (dp[i][j] != dp[i - 1][j]) { 29 | selectedItems.add(items.get(i - 1)); 30 | j -= items.get(i - 1).weight; 31 | } 32 | i--; 33 | } 34 | 35 | return selectedItems; 36 | } 37 | 38 | public static void main(String[] args) { 39 | List items = new ArrayList<>(); 40 | items.add(new Item(2, 12)); 41 | items.add(new Item(1, 10)); 42 | items.add(new Item(3, 20)); 43 | items.add(new Item(2, 15)); 44 | items.add(new Item(4, 25)); 45 | 46 | // Knapsack capacity 47 | int W = 8; 48 | List selectedItems = knapsack(W, items); 49 | 50 | System.out.println("Selected items:"); 51 | for (Item item : selectedItems) { 52 | System.out.println("Weight: " + item.weight + ", Value: " + item.value); 53 | } 54 | } 55 | } -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_3_knapsack/source/knapsack_title_logo.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_3_knapsack/source/knapsack_title_logo.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_40_decorator/Coffee.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._40_decorator; 2 | 3 | public interface Coffee { 4 | double cost(); 5 | String getDescription(); 6 | } -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_40_decorator/CoffeeDecorator.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._40_decorator; 2 | 3 | public abstract class CoffeeDecorator implements Coffee { 4 | protected Coffee decoratedCoffee; 5 | 6 | public CoffeeDecorator(Coffee decoratedCoffee) { 7 | this.decoratedCoffee = decoratedCoffee; 8 | } 9 | 10 | @Override 11 | public double cost() { 12 | return decoratedCoffee.cost(); 13 | } 14 | 15 | @Override 16 | public String getDescription() { 17 | return decoratedCoffee.getDescription(); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_40_decorator/Main.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._40_decorator; 2 | 3 | public class Main { 4 | public static void main(String[] args) { 5 | Coffee simpleCoffee = new SimpleCoffee(); 6 | System.out.println("Cost: $" + simpleCoffee.cost()); 7 | System.out.println("Description: " + simpleCoffee.getDescription()); 8 | 9 | // Decorate with milk 10 | Coffee milkCoffee = new MilkDecorator(simpleCoffee); 11 | System.out.println("Cost: $" + milkCoffee.cost()); 12 | System.out.println("Description: " + milkCoffee.getDescription()); 13 | 14 | // Decorate with milk and sugar 15 | Coffee milkAndSugarCoffee = new SugarDecorator(new MilkDecorator(simpleCoffee)); 16 | System.out.println("Cost: $" + milkAndSugarCoffee.cost()); 17 | System.out.println("Description: " + milkAndSugarCoffee.getDescription()); 18 | } 19 | } -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_40_decorator/MilkDecorator.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._40_decorator; 2 | 3 | public class MilkDecorator extends CoffeeDecorator { 4 | 5 | public MilkDecorator(Coffee decoratedCoffee) { 6 | super(decoratedCoffee); 7 | } 8 | 9 | @Override 10 | public double cost() { 11 | return super.cost() + 0.5; // $0.5 for milk 12 | } 13 | 14 | @Override 15 | public String getDescription() { 16 | return super.getDescription() + ", Milk"; 17 | } 18 | } -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_40_decorator/SimpleCoffee.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._40_decorator; 2 | 3 | public class SimpleCoffee implements Coffee { 4 | 5 | @Override 6 | public double cost() { 7 | return 1.0; // $1 for a simple coffee 8 | } 9 | 10 | @Override 11 | public String getDescription() { 12 | return "Simple Coffee"; 13 | } 14 | } -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_40_decorator/SugarDecorator.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._40_decorator; 2 | 3 | public class SugarDecorator extends CoffeeDecorator { 4 | public SugarDecorator(Coffee decoratedCoffee) { 5 | super(decoratedCoffee); 6 | } 7 | 8 | @Override 9 | public double cost() { 10 | return super.cost() + 0.5; // $0.5 for sugar 11 | } 12 | 13 | @Override 14 | public String getDescription() { 15 | return super.getDescription() + ", Sugar"; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_40_decorator/source/decorator_diagram.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_40_decorator/source/decorator_diagram.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_40_decorator/source/title.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_40_decorator/source/title.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_41_thread_local/MyService.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._41_thread_local; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.slf4j.MDC; 6 | import java.util.UUID; 7 | 8 | public class MyService { 9 | private static final Logger logger = LoggerFactory.getLogger(MyService.class); 10 | private static final ThreadLocal requestId = new ThreadLocal<>(); 11 | 12 | public void processRequest() { 13 | // Set request ID in the MDC context 14 | requestId.set(generateRequestId()); 15 | MDC.put("requestId", requestId.get()); 16 | 17 | // Perform some processing 18 | logger.info("Processing request..."); 19 | 20 | // Clear the MDC context after processing 21 | requestId.remove(); 22 | MDC.clear(); 23 | } 24 | 25 | private String generateRequestId() { 26 | // Generate a unique request ID 27 | return UUID.randomUUID().toString(); 28 | } 29 | } -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_41_thread_local/MyThreadLocalExample.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._41_thread_local; 2 | 3 | public class MyThreadLocalExample { 4 | // Define a ThreadLocal variable 5 | private static ThreadLocal threadLocalValue = new ThreadLocal() { 6 | @Override 7 | protected Integer initialValue() { 8 | return 0; // Default value for each thread 9 | } 10 | }; 11 | 12 | public static void main(String[] args) { 13 | // Set the value of the thread-local variable for the main thread 14 | threadLocalValue.set(10); 15 | 16 | // Create and start a new thread 17 | Thread newThread = new Thread(() -> { 18 | // Get the value of the thread-local variable for this thread 19 | int value = threadLocalValue.get(); 20 | System.out.println("Thread-local value in newThread: " + value); 21 | }); 22 | newThread.start(); 23 | 24 | // Get the value of the thread-local variable for the main thread 25 | int mainThreadValue = threadLocalValue.get(); 26 | System.out.println("Thread-local value in main thread: " + mainThreadValue); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_41_thread_local/ThreadLocalExample.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._41_thread_local; 2 | 3 | public class ThreadLocalExample { 4 | private static final ThreadLocal threadLocalValue = ThreadLocal.withInitial(() -> 0); 5 | 6 | public static void main(String[] args) { 7 | Runnable task = () -> { 8 | int value = threadLocalValue.get(); 9 | value += 1; 10 | threadLocalValue.set(value); 11 | System.out.println(Thread.currentThread().getName() + ": " + threadLocalValue.get()); 12 | }; 13 | 14 | Thread thread1 = new Thread(task, "Thread 1"); 15 | Thread thread2 = new Thread(task, "Thread 2"); 16 | 17 | thread1.start(); 18 | thread2.start(); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_41_thread_local/ThreadLocalSimpleExample.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._41_thread_local; 2 | 3 | public class ThreadLocalSimpleExample { 4 | private static final ThreadLocal threadLocal = ThreadLocal.withInitial(Object::new); 5 | 6 | public static void main(String[] args) { 7 | try { 8 | Object obj = threadLocal.get(); 9 | // Use obj 10 | } finally { 11 | threadLocal.remove(); 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_41_thread_local/source/thread_local.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_41_thread_local/source/thread_local.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_41_thread_local/source/title.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_41_thread_local/source/title.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_42_choosing_the_right_collection_in_java/CustomComparator.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._42_choosing_the_right_collection_in_java; 2 | 3 | import java.util.Comparator; 4 | import java.util.Map; 5 | 6 | // Custom comparator for sorting keys based on values 7 | class CustomComparator implements Comparator { 8 | private Map map; 9 | 10 | // Constructor to initialize map reference 11 | public CustomComparator(Map map) { 12 | this.map = map; 13 | } 14 | 15 | // Compare method to compare keys based on values in the map 16 | @Override 17 | public int compare(String key1, String key2) { 18 | // Compare values associated with the keys 19 | int valueCompare = map.get(key1).compareTo(map.get(key2)); 20 | 21 | // If values are equal, compare keys lexicographically 22 | if (valueCompare == 0) { 23 | return key1.compareTo(key2); 24 | } 25 | return valueCompare; // Return comparison result 26 | } 27 | } -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_42_choosing_the_right_collection_in_java/Main.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._42_choosing_the_right_collection_in_java; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | import java.util.TreeMap; 6 | 7 | public class Main { 8 | public static void main(String[] args) { 9 | // Create a TreeMap with custom comparator 10 | Map map = new HashMap<>(); 11 | map.put("John", 30); 12 | map.put("Alice", 25); 13 | map.put("Bob", 35); 14 | 15 | // Instantiate TreeMap with custom comparator 16 | Map customSortedMap = new TreeMap<>(new CustomComparator(map)); 17 | 18 | // Add all elements from original map to custom sorted map 19 | customSortedMap.putAll(map); 20 | 21 | // Print the custom sorted map 22 | for (Map.Entry entry : customSortedMap.entrySet()) { 23 | System.out.println(entry.getKey() + ": " + entry.getValue()); 24 | } 25 | } 26 | } -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_42_choosing_the_right_collection_in_java/source/title.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_42_choosing_the_right_collection_in_java/source/title.jpg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_43_thread_local_vs_scoped_value/ScopedValueExample.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._43_thread_local_vs_scoped_value; 2 | 3 | import java.util.concurrent.ExecutorService; 4 | import java.util.concurrent.Executors; 5 | 6 | public class ScopedValueExample { 7 | private static final ScopedValue scopedValue = ScopedValue.newInstance(); 8 | 9 | public static void main(String[] args) { 10 | ExecutorService executor = Executors.newFixedThreadPool(2); 11 | 12 | Runnable task = () -> { 13 | ScopedValue.where(scopedValue, "Value in " + Thread.currentThread().getName()).run(() -> { 14 | System.out.println(Thread.currentThread().getName() + " initial value: " + scopedValue.get()); 15 | 16 | try { 17 | Thread.sleep(100); 18 | } catch (InterruptedException e) { 19 | e.printStackTrace(); 20 | } 21 | 22 | System.out.println(Thread.currentThread().getName() + " final value: " + scopedValue.get()); 23 | }); 24 | }; 25 | 26 | executor.submit(task); 27 | executor.submit(task); 28 | 29 | executor.shutdown(); 30 | } 31 | } -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_43_thread_local_vs_scoped_value/ScopedValueSimpleExample.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._43_thread_local_vs_scoped_value; 2 | 3 | public class ScopedValueSimpleExample { 4 | private static final ScopedValue scopedValue = ScopedValue.newInstance(); 5 | 6 | public static void main(String[] args) { 7 | ScopedValue.where(scopedValue, "Scoped Value Example").run(() -> { 8 | String value = scopedValue.get(); // Retrieves "Scoped Value Example" within this scope 9 | System.out.println(value); 10 | }); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_43_thread_local_vs_scoped_value/ThreadLocalExample.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._43_thread_local_vs_scoped_value; 2 | 3 | import java.util.concurrent.ExecutorService; 4 | import java.util.concurrent.Executors; 5 | 6 | public class ThreadLocalExample { 7 | private static ThreadLocal threadLocalValue = ThreadLocal.withInitial(() -> 0); 8 | 9 | public static void main(String[] args) { 10 | ExecutorService executor = Executors.newFixedThreadPool(2); 11 | 12 | Runnable task = () -> { 13 | int value = threadLocalValue.get(); 14 | value += (int) (Math.random() * 100); 15 | threadLocalValue.set(value); 16 | System.out.println(Thread.currentThread().getName() + " initial value: " + value); 17 | 18 | try { 19 | Thread.sleep(100); 20 | } catch (InterruptedException e) { 21 | e.printStackTrace(); 22 | } 23 | 24 | System.out.println(Thread.currentThread().getName() + " final value: " + threadLocalValue.get()); 25 | }; 26 | 27 | executor.submit(task); 28 | executor.submit(task); 29 | 30 | executor.shutdown(); 31 | } 32 | } -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_43_thread_local_vs_scoped_value/ThreadLocalSimpleExample.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._43_thread_local_vs_scoped_value; 2 | 3 | public class ThreadLocalSimpleExample { 4 | private static ThreadLocal threadLocalValue = ThreadLocal.withInitial(() -> 0); 5 | 6 | public static void main(String[] args) { 7 | threadLocalValue.set(123); 8 | Integer value = threadLocalValue.get(); // Retrieves 123 for the current thread 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_43_thread_local_vs_scoped_value/source/thread_local.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_43_thread_local_vs_scoped_value/source/thread_local.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_43_thread_local_vs_scoped_value/source/title.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_43_thread_local_vs_scoped_value/source/title.jpg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_46_java_recursive_generics_example/Person.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._46_java_recursive_generics_example; 2 | 3 | public class Person { 4 | private final String firstName; 5 | private final String lastName; 6 | private final int age; 7 | 8 | private Person(Builder builder) { 9 | this.firstName = builder.firstName; 10 | this.lastName = builder.lastName; 11 | this.age = builder.age; 12 | } 13 | 14 | public static Builder builder() { 15 | return new PersonBuilder(); 16 | } 17 | 18 | @Override 19 | public String toString() { 20 | return "Person{" + 21 | "firstName='" + firstName + '\'' + 22 | ", lastName='" + lastName + '\'' + 23 | ", age=" + age + 24 | '}'; 25 | } 26 | 27 | public static class Builder> { 28 | private String firstName; 29 | private String lastName; 30 | private int age; 31 | 32 | public T firstName(String firstName) { 33 | this.firstName = firstName; 34 | return self(); 35 | } 36 | 37 | public T lastName(String lastName) { 38 | this.lastName = lastName; 39 | return self(); 40 | } 41 | 42 | public T age(int age) { 43 | this.age = age; 44 | return self(); 45 | } 46 | 47 | protected T self() { 48 | return (T) this; 49 | } 50 | 51 | public Person build() { 52 | return new Person(this); 53 | } 54 | } 55 | 56 | private static class PersonBuilder extends Builder { 57 | @Override 58 | protected PersonBuilder self() { 59 | return this; 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_46_java_recursive_generics_example/QueryBuilder.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._46_java_recursive_generics_example; 2 | 3 | public class QueryBuilder { 4 | 5 | public static SelectBuilder select(String... columns) { 6 | return new SelectBuilder(columns); 7 | } 8 | 9 | public static class SelectBuilder { 10 | private final String[] columns; 11 | 12 | private SelectBuilder(String[] columns) { 13 | this.columns = columns; 14 | } 15 | 16 | public FromBuilder from(String table) { 17 | return new FromBuilder(this, table); 18 | } 19 | 20 | public String[] getColumns() { 21 | return columns; 22 | } 23 | } 24 | 25 | public static class FromBuilder { 26 | private final SelectBuilder selectBuilder; 27 | private final String table; 28 | 29 | private FromBuilder(SelectBuilder selectBuilder, String table) { 30 | this.selectBuilder = selectBuilder; 31 | this.table = table; 32 | } 33 | 34 | public WhereBuilder where(String condition) { 35 | return new WhereBuilder(this, condition); 36 | } 37 | 38 | public OrderByBuilder orderBy(String... columns) { 39 | return new OrderByBuilder(this, columns); 40 | } 41 | 42 | public String getTable() { 43 | return table; 44 | } 45 | 46 | public SelectBuilder getSelectBuilder() { 47 | return selectBuilder; 48 | } 49 | } 50 | 51 | public static class WhereBuilder { 52 | private final FromBuilder fromBuilder; 53 | private final String condition; 54 | 55 | private WhereBuilder(FromBuilder fromBuilder, String condition) { 56 | this.fromBuilder = fromBuilder; 57 | this.condition = condition; 58 | } 59 | 60 | public OrderByBuilder orderBy(String... columns) { 61 | return new OrderByBuilder(fromBuilder, columns); 62 | } 63 | 64 | public String getCondition() { 65 | return condition; 66 | } 67 | 68 | public FromBuilder getFromBuilder() { 69 | return fromBuilder; 70 | } 71 | } 72 | 73 | public static class OrderByBuilder { 74 | private final FromBuilder fromBuilder; 75 | private final WhereBuilder whereBuilder; 76 | private final String[] columns; 77 | 78 | private OrderByBuilder(FromBuilder fromBuilder, String[] columns) { 79 | this.fromBuilder = fromBuilder; 80 | this.whereBuilder = null; 81 | this.columns = columns; 82 | } 83 | 84 | private OrderByBuilder(WhereBuilder whereBuilder, String[] columns) { 85 | this.fromBuilder = whereBuilder.getFromBuilder(); 86 | this.whereBuilder = whereBuilder; 87 | this.columns = columns; 88 | } 89 | 90 | public String build() { 91 | StringBuilder query = new StringBuilder("SELECT "); 92 | 93 | String[] selectColumns = fromBuilder.getSelectBuilder().getColumns(); 94 | query.append(String.join(", ", selectColumns)); 95 | query.append(" FROM ").append(fromBuilder.getTable()); 96 | 97 | if (whereBuilder != null) { 98 | query.append(" WHERE ").append(whereBuilder.getCondition()); 99 | } 100 | 101 | if (columns.length > 0) { 102 | query.append(" ORDER BY ").append(String.join(", ", columns)); 103 | } 104 | 105 | return query.toString(); 106 | } 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_46_java_recursive_generics_example/QueryBuilderExample.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._46_java_recursive_generics_example; 2 | 3 | public class QueryBuilderExample { 4 | public static void main(String[] args) { 5 | String query = QueryBuilder.select("id", "name", "age") 6 | .from("users") 7 | .where("age > 18") 8 | .orderBy("name", "age") 9 | .build(); 10 | 11 | System.out.println(query); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_46_java_recursive_generics_example/RecursiveGenericsExample.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._46_java_recursive_generics_example; 2 | 3 | public class RecursiveGenericsExample { 4 | public static void main(String[] args) { 5 | Person person = Person.builder() 6 | .firstName("John") 7 | .lastName("Doe") 8 | .age(30) 9 | .build(); 10 | 11 | System.out.println(person); 12 | } 13 | } -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_46_java_recursive_generics_example/source/title.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_46_java_recursive_generics_example/source/title.jpg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_47_chain_of_responsibility/ChainOfResponsibilityExample.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._47_chain_of_responsibility; 2 | 3 | // Define the base interface for request handlers 4 | interface PurchaseApprover { 5 | void setNextApprover(PurchaseApprover nextApprover); 6 | void processRequest(PurchaseRequest request); 7 | } 8 | 9 | // Concrete implementation of PurchaseApprover 10 | class Manager implements PurchaseApprover { 11 | private double purchasingLimit; 12 | private PurchaseApprover nextApprover; 13 | 14 | public Manager(double purchasingLimit) { 15 | this.purchasingLimit = purchasingLimit; 16 | } 17 | 18 | @Override 19 | public void setNextApprover(PurchaseApprover nextApprover) { 20 | this.nextApprover = nextApprover; 21 | } 22 | 23 | @Override 24 | public void processRequest(PurchaseRequest request) { 25 | if (request.getAmount() <= purchasingLimit) { 26 | System.out.println("Manager approved purchase of $" + request.getAmount()); 27 | } else if (nextApprover != null) { 28 | nextApprover.processRequest(request); 29 | } else { 30 | System.out.println("Purchase request for $" + request.getAmount() + " exceeds approval limit."); 31 | } 32 | } 33 | } 34 | 35 | // Purchase request class 36 | class PurchaseRequest { 37 | private double amount; 38 | 39 | public PurchaseRequest(double amount) { 40 | this.amount = amount; 41 | } 42 | 43 | public double getAmount() { 44 | return amount; 45 | } 46 | } 47 | 48 | public class ChainOfResponsibilityExample { 49 | public static void main(String[] args) { 50 | // Create chain of approvers 51 | PurchaseApprover manager = new Manager(1000); 52 | PurchaseApprover director = new Manager(5000); 53 | PurchaseApprover vp = new Manager(10000); 54 | 55 | // Set up the chain of responsibility 56 | manager.setNextApprover(director); 57 | director.setNextApprover(vp); 58 | 59 | // Process purchase requests 60 | manager.processRequest(new PurchaseRequest(500)); 61 | manager.processRequest(new PurchaseRequest(2500)); 62 | manager.processRequest(new PurchaseRequest(7500)); 63 | manager.processRequest(new PurchaseRequest(15000)); 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_47_chain_of_responsibility/DataConversionPipeline.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._47_chain_of_responsibility; 2 | 3 | // Define the base interface for data converters 4 | interface DataConverter { 5 | void setNextConverter(DataConverter nextConverter); 6 | String convert(String data); 7 | } 8 | 9 | // Concrete implementation of DataConverter for JSON to XML conversion 10 | class JsonToXmlConverter implements DataConverter { 11 | private DataConverter nextConverter; 12 | 13 | @Override 14 | public void setNextConverter(DataConverter nextConverter) { 15 | this.nextConverter = nextConverter; 16 | } 17 | 18 | @Override 19 | public String convert(String data) { 20 | // Perform JSON to XML conversion 21 | return "" + data + ""; 22 | } 23 | } 24 | 25 | // Concrete implementation of DataConverter for XML to CSV conversion 26 | class XmlToCsvConverter implements DataConverter { 27 | private DataConverter nextConverter; 28 | 29 | @Override 30 | public void setNextConverter(DataConverter nextConverter) { 31 | this.nextConverter = nextConverter; 32 | } 33 | 34 | @Override 35 | public String convert(String data) { 36 | // Perform XML to CSV conversion 37 | return data.replaceAll("<", ",").replaceAll(">", ""); 38 | } 39 | } 40 | 41 | // Concrete implementation of DataConverter for CSV to JSON conversion 42 | class CsvToJsonConverter implements DataConverter { 43 | private DataConverter nextConverter; 44 | 45 | @Override 46 | public void setNextConverter(DataConverter nextConverter) { 47 | this.nextConverter = nextConverter; 48 | } 49 | 50 | @Override 51 | public String convert(String data) { 52 | // Perform CSV to JSON conversion 53 | return "{\"json\": \"" + data + "\"}"; 54 | } 55 | } 56 | 57 | public class DataConversionPipeline { 58 | public static void main(String[] args) { 59 | // Create instances of converters 60 | DataConverter jsonToXmlConverter = new JsonToXmlConverter(); 61 | DataConverter xmlToCsvConverter = new XmlToCsvConverter(); 62 | DataConverter csvToJsonConverter = new CsvToJsonConverter(); 63 | 64 | // Set up the pipeline 65 | jsonToXmlConverter.setNextConverter(xmlToCsvConverter); 66 | xmlToCsvConverter.setNextConverter(csvToJsonConverter); 67 | 68 | // Input data in JSON format 69 | String jsonData = "{ \"key\": \"value\" }"; 70 | 71 | // Process data through the pipeline 72 | String result = jsonToXmlConverter.convert(jsonData); 73 | 74 | // Output the result 75 | System.out.println("Result: " + result); 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_47_chain_of_responsibility/source/chain_of_responsibility_diagram.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_47_chain_of_responsibility/source/chain_of_responsibility_diagram.jpg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_47_chain_of_responsibility/source/handling_chain.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_47_chain_of_responsibility/source/handling_chain.jpg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_47_chain_of_responsibility/source/title.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_47_chain_of_responsibility/source/title.jpg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_48_java_rest_clients/appache_http_client/PostRequestWithJson.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._48_java_rest_clients.appache_http_client; 2 | 3 | import org.apache.http.client.methods.CloseableHttpResponse; 4 | import org.apache.http.client.methods.HttpPost; 5 | import org.apache.http.entity.StringEntity; 6 | import org.apache.http.impl.client.CloseableHttpClient; 7 | import org.apache.http.impl.client.HttpClients; 8 | import org.apache.http.util.EntityUtils; 9 | 10 | import java.io.IOException; 11 | 12 | public class PostRequestWithJson { 13 | public static void main(String[] args) { 14 | // Create a CloseableHttpClient instance 15 | try (CloseableHttpClient httpClient = HttpClients.createDefault()) { 16 | // Create an HttpPost request 17 | HttpPost post = new HttpPost("https://jsonplaceholder.typicode.com/posts"); 18 | 19 | // Set the request headers 20 | post.setHeader("Content-Type", "application/json"); 21 | 22 | // Set the request payload 23 | String json = "{\"title\":\"foo\",\"body\":\"bar\",\"userId\":1}"; 24 | post.setEntity(new StringEntity(json)); 25 | 26 | // Execute the request and get the response 27 | try (CloseableHttpResponse response = httpClient.execute(post)) { 28 | // Print the response status and body 29 | System.out.println("Status code: " + response.getStatusLine().getStatusCode()); 30 | System.out.println("Response body: " + EntityUtils.toString(response.getEntity())); 31 | } 32 | } catch (IOException e) { 33 | e.printStackTrace(); 34 | } 35 | } 36 | } -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_48_java_rest_clients/appache_http_client/SimpleGetRequest.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._48_java_rest_clients.appache_http_client; 2 | 3 | import org.apache.http.HttpEntity; 4 | import org.apache.http.client.methods.CloseableHttpResponse; 5 | import org.apache.http.client.methods.HttpGet; 6 | import org.apache.http.impl.client.CloseableHttpClient; 7 | import org.apache.http.impl.client.HttpClients; 8 | import org.apache.http.util.EntityUtils; 9 | 10 | import java.io.IOException; 11 | 12 | public class SimpleGetRequest { 13 | public static void main(String[] args) { 14 | // Create a CloseableHttpClient instance 15 | try (CloseableHttpClient httpClient = HttpClients.createDefault()) { 16 | // Create an HttpGet request 17 | HttpGet request = new HttpGet("https://api.github.com"); 18 | 19 | // Execute the request and get the response 20 | try (CloseableHttpResponse response = httpClient.execute(request)) { 21 | // Get the response entity 22 | HttpEntity entity = response.getEntity(); 23 | 24 | // Print the response status and body 25 | System.out.println("Status code: " + response.getStatusLine().getStatusCode()); 26 | if (entity != null) { 27 | System.out.println("Response body: " + EntityUtils.toString(entity)); 28 | } 29 | } 30 | } catch (IOException e) { 31 | e.printStackTrace(); 32 | } 33 | } 34 | } -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_48_java_rest_clients/native_client/AsyncPostRequest.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._48_java_rest_clients.native_client; 2 | 3 | import java.net.URI; 4 | import java.net.http.HttpClient; 5 | import java.net.http.HttpRequest; 6 | import java.net.http.HttpResponse; 7 | import java.net.http.HttpRequest.BodyPublishers; 8 | import java.util.concurrent.CompletableFuture; 9 | 10 | public class AsyncPostRequest { 11 | public static void main(String[] args) { 12 | // Create an HttpClient instance 13 | HttpClient client = HttpClient.newHttpClient(); 14 | 15 | // Create a HttpRequest 16 | HttpRequest request = HttpRequest.newBuilder() 17 | .uri(URI.create("https://jsonplaceholder.typicode.com/posts")) 18 | .header("Content-Type", "application/json") 19 | .POST(BodyPublishers.ofString("{\"title\":\"foo\",\"body\":\"bar\",\"userId\":1}")) 20 | .build(); 21 | 22 | // Send the request asynchronously 23 | CompletableFuture> responseFuture = client.sendAsync(request, HttpResponse.BodyHandlers.ofString()); 24 | 25 | // Handle the response 26 | responseFuture.thenApply(HttpResponse::body) 27 | .thenAccept(System.out::println) 28 | .join(); // Wait for the response 29 | } 30 | } -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_48_java_rest_clients/native_client/SimpleGetRequest.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._48_java_rest_clients.native_client; 2 | 3 | import java.net.URI; 4 | import java.net.http.HttpClient; 5 | import java.net.http.HttpRequest; 6 | import java.net.http.HttpResponse; 7 | import java.io.IOException; 8 | 9 | public class SimpleGetRequest { 10 | public static void main(String[] args) { 11 | // Create an HttpClient instance 12 | HttpClient client = HttpClient.newHttpClient(); 13 | 14 | // Create a HttpRequest 15 | HttpRequest request = HttpRequest.newBuilder() 16 | .uri(URI.create("https://api.github.com")) 17 | .GET() 18 | .build(); 19 | 20 | try { 21 | // Send the request and get the response 22 | HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); 23 | 24 | // Print the response status code and body 25 | System.out.println("Status code: " + response.statusCode()); 26 | System.out.println("Response body: " + response.body()); 27 | } catch (IOException | InterruptedException e) { 28 | e.printStackTrace(); 29 | } 30 | } 31 | } -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_48_java_rest_clients/okhttp/AsyncPostRequest.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._48_java_rest_clients.okhttp; 2 | 3 | import okhttp3.*; 4 | 5 | import java.io.IOException; 6 | 7 | public class AsyncPostRequest { 8 | public static void main(String[] args) { 9 | // Create an OkHttpClient instance 10 | OkHttpClient client = new OkHttpClient(); 11 | 12 | // Define the request payload 13 | String json = "{\"title\":\"foo\",\"body\":\"bar\",\"userId\":1}"; 14 | 15 | // Create a request body 16 | RequestBody body = RequestBody.create(json, MediaType.get("application/json; charset=utf-8")); 17 | 18 | // Create a request 19 | Request request = new Request.Builder() 20 | .url("https://jsonplaceholder.typicode.com/posts") 21 | .post(body) 22 | .build(); 23 | 24 | // Execute the request asynchronously 25 | client.newCall(request).enqueue(new Callback() { 26 | @Override 27 | public void onFailure(Call call, IOException e) { 28 | e.printStackTrace(); 29 | } 30 | 31 | @Override 32 | public void onResponse(Call call, Response response) throws IOException { 33 | // Print the response status code and body 34 | System.out.println("Status code: " + response.code()); 35 | System.out.println("Response body: " + response.body().string()); 36 | } 37 | }); 38 | } 39 | } -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_48_java_rest_clients/okhttp/SimpleGetRequest.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._48_java_rest_clients.okhttp; 2 | 3 | import okhttp3.OkHttpClient; 4 | import okhttp3.Request; 5 | import okhttp3.Response; 6 | 7 | import java.io.IOException; 8 | 9 | public class SimpleGetRequest { 10 | public static void main(String[] args) { 11 | // Create an OkHttpClient instance 12 | OkHttpClient client = new OkHttpClient(); 13 | 14 | // Create a request 15 | Request request = new Request.Builder() 16 | .url("https://api.github.com") 17 | .build(); 18 | 19 | // Execute the request and get the response 20 | try (Response response = client.newCall(request).execute()) { 21 | // Print the response status code and body 22 | System.out.println("Status code: " + response.code()); 23 | System.out.println("Response body: " + response.body().string()); 24 | } catch (IOException e) { 25 | e.printStackTrace(); 26 | } 27 | } 28 | } -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_48_java_rest_clients/spring_rest_template/PostRequestWithJson.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._48_java_rest_clients.spring_rest_template; 2 | 3 | import org.springframework.web.client.RestTemplate; 4 | import org.springframework.http.HttpEntity; 5 | import org.springframework.http.HttpHeaders; 6 | import org.springframework.http.MediaType; 7 | import org.springframework.http.ResponseEntity; 8 | 9 | import java.util.HashMap; 10 | import java.util.Map; 11 | 12 | public class PostRequestWithJson { 13 | public static void main(String[] args) { 14 | // Create a RestTemplate instance 15 | RestTemplate restTemplate = new RestTemplate(); 16 | 17 | // Define the URL 18 | String url = "https://jsonplaceholder.typicode.com/posts"; 19 | 20 | // Create the request headers 21 | HttpHeaders headers = new HttpHeaders(); 22 | headers.setContentType(MediaType.APPLICATION_JSON); 23 | 24 | // Create the request payload 25 | Map requestBody = new HashMap<>(); 26 | requestBody.put("title", "foo"); 27 | requestBody.put("body", "bar"); 28 | requestBody.put("userId", 1); 29 | 30 | // Wrap the payload in an HttpEntity 31 | HttpEntity> requestEntity = new HttpEntity<>(requestBody, headers); 32 | 33 | // Make the POST request and get the response 34 | ResponseEntity response = restTemplate.postForEntity(url, requestEntity, String.class); 35 | 36 | // Print the response status code and body 37 | System.out.println("Status code: " + response.getStatusCode()); 38 | System.out.println("Response body: " + response.getBody()); 39 | } 40 | } -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_48_java_rest_clients/spring_rest_template/SimpleGetRequest.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._48_java_rest_clients.spring_rest_template; 2 | 3 | import org.springframework.web.client.RestTemplate; 4 | import org.springframework.http.ResponseEntity; 5 | 6 | public class SimpleGetRequest { 7 | public static void main(String[] args) { 8 | // Create a RestTemplate instance 9 | RestTemplate restTemplate = new RestTemplate(); 10 | 11 | // Define the URL 12 | String url = "https://api.github.com"; 13 | 14 | // Make the GET request and get the response 15 | ResponseEntity response = restTemplate.getForEntity(url, String.class); 16 | 17 | // Print the response status code and body 18 | System.out.println("Status code: " + response.getStatusCode()); 19 | System.out.println("Response body: " + response.getBody()); 20 | } 21 | } -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_48_java_rest_clients/spring_web_flux/PostRequestWithJson.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._48_java_rest_clients.spring_web_flux; 2 | 3 | import org.springframework.web.reactive.function.client.WebClient; 4 | import org.springframework.http.MediaType; 5 | import reactor.core.publisher.Mono; 6 | 7 | public class PostRequestWithJson { 8 | public static void main(String[] args) { 9 | // Create a WebClient instance 10 | WebClient webClient = WebClient.create("https://jsonplaceholder.typicode.com"); 11 | 12 | // Define the request payload 13 | String requestBody = "{\"title\":\"foo\",\"body\":\"bar\",\"userId\":1}"; 14 | 15 | // Make the POST request and get the response 16 | Mono response = webClient.post() 17 | .uri("/posts") 18 | .contentType(MediaType.APPLICATION_JSON) 19 | .bodyValue(requestBody) 20 | .retrieve() 21 | .bodyToMono(String.class); 22 | 23 | // Subscribe to the response and print the body 24 | response.subscribe(System.out::println); 25 | } 26 | } -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_48_java_rest_clients/spring_web_flux/SimpleGetRequest.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._48_java_rest_clients.spring_web_flux; 2 | 3 | import org.springframework.web.reactive.function.client.WebClient; 4 | import reactor.core.publisher.Mono; 5 | 6 | public class SimpleGetRequest { 7 | public static void main(String[] args) { 8 | // Create a WebClient instance 9 | WebClient webClient = WebClient.create("https://api.github.com"); 10 | 11 | // Make the GET request and get the response 12 | Mono response = webClient.get() 13 | .retrieve() 14 | .bodyToMono(String.class); 15 | 16 | // Subscribe to the response and print the body 17 | response.subscribe(System.out::println); 18 | } 19 | } -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_49_resilience4j/source/resilience4j.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_49_resilience4j/source/resilience4j.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_49_resilience4j/source/title.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_49_resilience4j/source/title.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_4_radix_sort/RadixSort.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._4_radix_sort; 2 | 3 | import java.util.Arrays; 4 | 5 | public class RadixSort { 6 | static void countingSort(int[] arr, int exp) { 7 | int n = arr.length; 8 | int[] output = new int[n]; 9 | int[] count = new int[10]; 10 | Arrays.fill(count, 0); 11 | 12 | // count of occurrences in count[] 13 | for (int j : arr) { 14 | count[(j / exp) % 10]++; 15 | } 16 | 17 | // change count[i] so that count[i] now contains 18 | // actual position of this digit in output[] 19 | for (int i = 1; i < 10; i++) { 20 | count[i] += count[i - 1]; 21 | } 22 | 23 | for (int i = n - 1; i >= 0; i--) { 24 | output[count[(arr[i] / exp) % 10] - 1] = arr[i]; 25 | count[(arr[i] / exp) % 10]--; 26 | } 27 | 28 | System.arraycopy(output, 0, arr, 0, n); 29 | } 30 | 31 | static void radixSort(int[] arr) { 32 | // find the maximum number to know the number of digits 33 | int max = Arrays.stream(arr).max().getAsInt(); 34 | 35 | // do counting sort for every digit. Note that 36 | // instead of passing digit number, exp is passed. 37 | // exp is 10^i where i is the current digit number 38 | for (int exp = 1; max / exp > 0; exp *= 10) { 39 | countingSort(arr, exp); 40 | } 41 | } 42 | 43 | public static void main(String[] args) { 44 | int[] arr = {100, 1, 101, 111, 59, 89, 97}; 45 | radixSort(arr); 46 | System.out.println("Sorted array:"); 47 | for (int j : arr) { 48 | System.out.print(j + " "); 49 | } 50 | System.out.println(); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_4_radix_sort/source/radix_sort_title_logo.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_4_radix_sort/source/radix_sort_title_logo.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_53_fork_join_pool/ForkJoinMergeSort.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._53_fork_join_pool; 2 | 3 | import java.util.concurrent.ForkJoinPool; 4 | import java.util.concurrent.RecursiveAction; 5 | 6 | public class ForkJoinMergeSort { 7 | 8 | public static void main(String[] args) { 9 | int[] array = {38, 27, 43, 3, 9, 82, 10}; 10 | ForkJoinPool pool = new ForkJoinPool(); 11 | pool.invoke(new MergeSortTask(array, 0, array.length - 1)); 12 | 13 | for (int i : array) { 14 | System.out.print(i + " "); 15 | } 16 | } 17 | 18 | static class MergeSortTask extends RecursiveAction { 19 | private int[] array; 20 | private int left; 21 | private int right; 22 | 23 | MergeSortTask(int[] array, int left, int right) { 24 | this.array = array; 25 | this.left = left; 26 | this.right = right; 27 | } 28 | 29 | @Override 30 | protected void compute() { 31 | if (left < right) { 32 | int mid = (left + right) / 2; 33 | 34 | MergeSortTask leftTask = new MergeSortTask(array, left, mid); 35 | MergeSortTask rightTask = new MergeSortTask(array, mid + 1, right); 36 | 37 | invokeAll(leftTask, rightTask); 38 | 39 | merge(array, left, mid, right); 40 | } 41 | } 42 | 43 | private void merge(int[] array, int left, int mid, int right) { 44 | int n1 = mid - left + 1; 45 | int n2 = right - mid; 46 | 47 | int[] L = new int[n1]; 48 | int[] R = new int[n2]; 49 | 50 | System.arraycopy(array, left, L, 0, n1); 51 | System.arraycopy(array, mid + 1, R, 0, n2); 52 | 53 | int i = 0, j = 0, k = left; 54 | while (i < n1 && j < n2) { 55 | if (L[i] <= R[j]) { 56 | array[k] = L[i]; 57 | i++; 58 | } else { 59 | array[k] = R[j]; 60 | j++; 61 | } 62 | k++; 63 | } 64 | 65 | while (i < n1) { 66 | array[k] = L[i]; 67 | i++; 68 | k++; 69 | } 70 | 71 | while (j < n2) { 72 | array[k] = R[j]; 73 | j++; 74 | k++; 75 | } 76 | } 77 | } 78 | } -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_53_fork_join_pool/ForkJoinPoolExample.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._53_fork_join_pool; 2 | 3 | import java.util.concurrent.ForkJoinPool; 4 | import java.util.concurrent.RecursiveTask; 5 | 6 | public class ForkJoinPoolExample { 7 | 8 | public static void main(String[] args) { 9 | ForkJoinPool forkJoinPool = new ForkJoinPool(4); // 4 parallel threads 10 | MyRecursiveTask task = new MyRecursiveTask(100); 11 | Integer result = forkJoinPool.invoke(task); 12 | System.out.println("Result: " + result); 13 | } 14 | } 15 | 16 | class MyRecursiveTask extends RecursiveTask { 17 | private int workload; 18 | 19 | MyRecursiveTask(int workload) { 20 | this.workload = workload; 21 | } 22 | 23 | @Override 24 | protected Integer compute() { 25 | if (workload > 16) { 26 | MyRecursiveTask subtask1 = new MyRecursiveTask(workload / 2); 27 | MyRecursiveTask subtask2 = new MyRecursiveTask(workload / 2); 28 | 29 | subtask1.fork(); 30 | subtask2.fork(); 31 | 32 | int result = subtask1.join() + subtask2.join(); 33 | return result; 34 | } else { 35 | return workload * workload; 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_53_fork_join_pool/source/ForkJoinPool.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_53_fork_join_pool/source/ForkJoinPool.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_54_garbage_collection/source/gc.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_54_garbage_collection/source/gc.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_55_java_comilation/source/jvm_compiller.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_55_java_comilation/source/jvm_compiller.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_57_merging_two_maps/ApacheCollectionUtils.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._57_merging_two_maps; 2 | 3 | import java.util.HashMap; 4 | import java.util.List; 5 | import java.util.Map; 6 | import org.apache.commons.collections4.MapUtils; 7 | 8 | public class ApacheCollectionUtils { 9 | public static void main(String[] args) { 10 | Map map1 = new HashMap<>(); 11 | map1.put(1, new Person(1, "Alice")); 12 | map1.put(2, new Person(2, "Bob")); 13 | 14 | Map map2 = new HashMap<>(); 15 | map2.put(3, new Person(3, "Charlie")); 16 | map2.put(4, new Person(4, "David")); 17 | 18 | Object[] array = new Object[map2.size() * 2]; 19 | List personList = map2.values().stream().toList(); 20 | for (int i = 0, j = 0; i < map2.size(); i++) { 21 | array[j++] = personList.get(i).getId(); 22 | array[j++] = personList.get(i); 23 | 24 | } 25 | 26 | // Merge maps using Apache Commons Collections 27 | Map mergedMap = MapUtils.putAll(new HashMap<>(map1), array); 28 | System.out.println("Merged map: " + mergedMap); 29 | } 30 | } -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_57_merging_two_maps/MapMergeMethod.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._57_merging_two_maps; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | public class MapMergeMethod { 7 | public static void main(String[] args) { 8 | Map map1 = new HashMap<>(); 9 | map1.put(1, new Person(1, "Alice")); 10 | map1.put(2, new Person(2, "Bob")); 11 | 12 | Map map2 = new HashMap<>(); 13 | map2.put(3, new Person(3, "Charlie")); 14 | map2.put(4, new Person(4, "David")); 15 | map2.put(2, new Person(2, "John")); 16 | 17 | Map mergedMap = new HashMap<>(map1); 18 | 19 | map2.forEach((key, value) -> 20 | mergedMap.merge(key, value, (existingValue, newValue) -> 21 | new Person(existingValue.getId(), existingValue.getName() + " & " + newValue.getName()) 22 | ) 23 | ); 24 | 25 | // Print the merged map 26 | mergedMap.forEach((key, value) -> System.out.println(key + ": " + value)); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_57_merging_two_maps/MapPutAll.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._57_merging_two_maps; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | public class MapPutAll { 7 | public static void main(String[] args) { 8 | Map map1 = new HashMap<>(); 9 | map1.put(1, new Person(1, "Alice")); 10 | map1.put(2, new Person(2, "Bob")); 11 | 12 | Map map2 = new HashMap<>(); 13 | map2.put(3, new Person(1, "Charlie")); 14 | map2.put(4, new Person(4, "David")); 15 | 16 | // Merge maps 17 | Map mergedMap = new HashMap<>(map1); 18 | mergedMap.putAll(map2); 19 | 20 | System.out.println("Merged map: " + mergedMap); 21 | } 22 | } 23 | 24 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_57_merging_two_maps/MapPutIfAbsent.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._57_merging_two_maps; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | public class MapPutIfAbsent { 7 | public static void main(String[] args) { 8 | Map map1 = new HashMap<>(); 9 | map1.put(1, new Person(1, "Alice")); 10 | map1.put(2, new Person(2, "Bob")); 11 | 12 | Map map2 = new HashMap<>(); 13 | map2.put(3, new Person(3, "Charlie")); 14 | map2.put(4, new Person(4, "David")); 15 | 16 | // Merge maps using putIfAbsent method 17 | Map mergedMap = new HashMap<>(map1); 18 | map2.forEach((key, value) -> mergedMap.putIfAbsent(key, value)); 19 | 20 | System.out.println("Merged map: " + mergedMap); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_57_merging_two_maps/Person.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._57_merging_two_maps; 2 | 3 | import java.util.Objects; 4 | 5 | public class Person { 6 | private final int id; 7 | private final String name; 8 | 9 | public int getId() { 10 | return id; 11 | } 12 | 13 | public String getName() { 14 | return name; 15 | } 16 | 17 | public Person(int id, String name) { 18 | this.id = id; 19 | this.name = name; 20 | } 21 | 22 | @Override 23 | public String toString() { 24 | return "Person{id=" + id + ", name='" + name + '\'' + '}'; 25 | } 26 | 27 | @Override 28 | public boolean equals(Object o) { 29 | if (this == o) return true; 30 | if (o == null || getClass() != o.getClass()) return false; 31 | Person person = (Person) o; 32 | return id == person.id && Objects.equals(name, person.name); 33 | } 34 | 35 | @Override 36 | public int hashCode() { 37 | return Objects.hash(id, name); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_57_merging_two_maps/StreamConcat.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._57_merging_two_maps; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | import java.util.stream.Collectors; 6 | import java.util.stream.Stream; 7 | 8 | public class StreamConcat { 9 | public static void main(String[] args) { 10 | Map map1 = new HashMap<>(); 11 | map1.put(1, new Person(1, "Alice")); 12 | map1.put(2, new Person(2, "Bob")); 13 | 14 | Map map2 = new HashMap<>(); 15 | map2.put(3, new Person(3, "Charlie")); 16 | map2.put(4, new Person(4, "David")); 17 | 18 | // Merge maps 19 | Map mergedMap = Stream.concat( 20 | map1.entrySet().stream(), 21 | map2.entrySet().stream()).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, 22 | (value1, value2) -> new Person(value2.getId(), value1.getName()))); 23 | 24 | System.out.println("Merged map: " + mergedMap); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_57_merging_two_maps/StreamOf.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._57_merging_two_maps; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | import java.util.stream.Collectors; 6 | import java.util.stream.Stream; 7 | 8 | public class StreamOf { 9 | public static void main(String[] args) { 10 | Map map1 = new HashMap<>(); 11 | map1.put(1, new Person(1, "Alice")); 12 | map1.put(2, new Person(2, "Bob")); 13 | 14 | Map map2 = new HashMap<>(); 15 | map2.put(3, new Person(3, "Charlie")); 16 | map2.put(4, new Person(4, "David")); 17 | 18 | // Merge maps 19 | Map mergedMap = Stream.of(map1, map2) 20 | .flatMap(map -> map.entrySet().stream()) 21 | .collect(Collectors.toMap( 22 | Map.Entry::getKey, 23 | Map.Entry::getValue, 24 | (v1, v2) -> new Person(v1.getId(), v2.getName()))); 25 | 26 | System.out.println("Merged map: " + mergedMap); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_58_java_records/Person.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._58_java_records; 2 | 3 | public record Person(String name, int age) { 4 | } -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_58_java_records/Range.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._58_java_records; 2 | 3 | public record Range(int lo, int hi) { 4 | public Range { 5 | if (lo > hi) { 6 | throw new IllegalArgumentException(String.format("(%d,%d)", lo, hi)); 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_58_java_records/RationalExample.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._58_java_records; 2 | 3 | public class RationalExample { 4 | } 5 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_5_java_memory_model/source/java_memory_brief_scheme.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_5_java_memory_model/source/java_memory_brief_scheme.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_5_java_memory_model/source/java_memory_detail_scheme.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_5_java_memory_model/source/java_memory_detail_scheme.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_5_java_memory_model/source/java_memory_scheme.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_5_java_memory_model/source/java_memory_scheme.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_65_visitor_pattern_in_java/VisitorPatternDemo.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._65_visitor_pattern_in_java; 2 | 3 | // Visitor interface 4 | interface Visitor { 5 | void visit(Book book); 6 | 7 | void visit(Fruit fruit); 8 | } 9 | 10 | // Concrete Visitor 11 | class ShoppingCartVisitor implements Visitor { 12 | @Override 13 | public void visit(Book book) { 14 | System.out.println("Book: " + book.getTitle() + ", Price: " + book.getPrice()); 15 | } 16 | 17 | @Override 18 | public void visit(Fruit fruit) { 19 | System.out.println("Fruit: " + fruit.getName() + ", Weight: " + fruit.getWeight() + ", Price: " + fruit.getPrice()); 20 | } 21 | } 22 | 23 | // Element interface 24 | interface ItemElement { 25 | void accept(Visitor visitor); 26 | } 27 | 28 | // Concrete Element - Book 29 | class Book implements ItemElement { 30 | private String title; 31 | private double price; 32 | 33 | public Book(String title, double price) { 34 | this.title = title; 35 | this.price = price; 36 | } 37 | 38 | public String getTitle() { 39 | return title; 40 | } 41 | 42 | public double getPrice() { 43 | return price; 44 | } 45 | 46 | @Override 47 | public void accept(Visitor visitor) { 48 | visitor.visit(this); 49 | } 50 | } 51 | 52 | // Concrete Element - Fruit 53 | class Fruit implements ItemElement { 54 | private String name; 55 | private double weight; 56 | private double price; 57 | 58 | public Fruit(String name, double weight, double price) { 59 | this.name = name; 60 | this.weight = weight; 61 | this.price = price; 62 | } 63 | 64 | public String getName() { 65 | return name; 66 | } 67 | 68 | public double getWeight() { 69 | return weight; 70 | } 71 | 72 | public double getPrice() { 73 | return price; 74 | } 75 | 76 | @Override 77 | public void accept(Visitor visitor) { 78 | visitor.visit(this); 79 | } 80 | } 81 | 82 | // Client 83 | public class VisitorPatternDemo { 84 | public static void main(String[] args) { 85 | ItemElement[] items = new ItemElement[]{ 86 | new Book("Design Patterns", 30.00), 87 | new Fruit("Apple", 2.0, 3.00) 88 | }; 89 | 90 | Visitor visitor = new ShoppingCartVisitor(); 91 | for (ItemElement item : items) { 92 | item.accept(visitor); 93 | } 94 | } 95 | } -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_66_observer_pattern_in_java/ObserverPatternDemo.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._66_observer_pattern_in_java; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | 7 | // Subject interface 8 | interface Subject { 9 | void registerObserver(Observer observer); 10 | 11 | void removeObserver(Observer observer); 12 | 13 | void notifyObservers(); 14 | } 15 | 16 | // Concrete Subject 17 | class ConcreteSubject implements Subject { 18 | private List observers; 19 | private int state; 20 | 21 | public ConcreteSubject() { 22 | this.observers = new ArrayList<>(); 23 | } 24 | 25 | public int getState() { 26 | return state; 27 | } 28 | 29 | public void setState(int state) { 30 | this.state = state; 31 | notifyObservers(); 32 | } 33 | 34 | @Override 35 | public void registerObserver(Observer observer) { 36 | observers.add(observer); 37 | } 38 | 39 | @Override 40 | public void removeObserver(Observer observer) { 41 | observers.remove(observer); 42 | } 43 | 44 | @Override 45 | public void notifyObservers() { 46 | for (Observer observer : observers) { 47 | observer.update(); 48 | } 49 | } 50 | } 51 | 52 | // Observer interface 53 | interface Observer { 54 | void update(); 55 | } 56 | 57 | // Concrete Observer 58 | class ConcreteObserver implements Observer { 59 | private ConcreteSubject subject; 60 | private int observerState; 61 | 62 | public ConcreteObserver(ConcreteSubject subject) { 63 | this.subject = subject; 64 | this.subject.registerObserver(this); 65 | } 66 | 67 | @Override 68 | public void update() { 69 | this.observerState = subject.getState(); 70 | display(); 71 | } 72 | 73 | public void display() { 74 | System.out.println("Observer State: " + observerState); 75 | } 76 | } 77 | 78 | // Demo class to demonstrate Observer Pattern 79 | public class ObserverPatternDemo { 80 | public static void main(String[] args) { 81 | ConcreteSubject subject = new ConcreteSubject(); 82 | 83 | ConcreteObserver observer1 = new ConcreteObserver(subject); 84 | ConcreteObserver observer2 = new ConcreteObserver(subject); 85 | 86 | subject.setState(10); // Updates all observers 87 | subject.setState(20); // Updates all observers 88 | } 89 | } -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_67_lombok/User.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._67_lombok; 2 | 3 | import java.util.Objects; 4 | 5 | public class User { 6 | private int id; 7 | private String name; 8 | 9 | public User() { 10 | } 11 | 12 | public User(int id, String name) { 13 | this.id = id; 14 | this.name = name; 15 | } 16 | 17 | public int getId() { 18 | return id; 19 | } 20 | 21 | public void setId(int id) { 22 | this.id = id; 23 | } 24 | 25 | public String getName() { 26 | return name; 27 | } 28 | 29 | public void setName(String name) { 30 | this.name = name; 31 | } 32 | 33 | @Override 34 | public boolean equals(Object o) { 35 | if (this == o) return true; 36 | if (o == null || getClass() != o.getClass()) return false; 37 | User user = (User) o; 38 | return id == user.id && Objects.equals(name, user.name); 39 | } 40 | 41 | @Override 42 | public int hashCode() { 43 | return Objects.hash(id, name); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_67_lombok/UserSimplified.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._67_lombok; 2 | 3 | import lombok.AccessLevel; 4 | import lombok.AllArgsConstructor; 5 | import lombok.Data; 6 | import lombok.NoArgsConstructor; 7 | import lombok.experimental.FieldDefaults; 8 | 9 | @Data 10 | @NoArgsConstructor 11 | @AllArgsConstructor 12 | @FieldDefaults(level = AccessLevel.PRIVATE) 13 | public class UserSimplified { 14 | int id; 15 | String name; 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_6_optimizing_java_apps/source/java_logo.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_6_optimizing_java_apps/source/java_logo.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_6_optimizing_java_apps/source/optimization_technics.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_6_optimizing_java_apps/source/optimization_technics.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_6_optimizing_java_apps/source/performance_scheme.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_6_optimizing_java_apps/source/performance_scheme.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_7_fundamentals_of_logging/source/loggers_scheme.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_7_fundamentals_of_logging/source/loggers_scheme.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_8_binary_search/BinarySearch.java: -------------------------------------------------------------------------------- 1 | package org.alx.article._8_binary_search; 2 | 3 | public class BinarySearch { 4 | public static int binarySearch(int[] arr, int target) { 5 | int left = 0; 6 | int right = arr.length - 1; 7 | 8 | while (left <= right) { 9 | int mid = left + (right - left) / 2; 10 | 11 | // Check if the target is found at the middle 12 | if (arr[mid] == target) { 13 | return mid; 14 | } 15 | 16 | // If the target is greater, ignore left half 17 | else if (arr[mid] < target) { 18 | left = mid + 1; 19 | } 20 | 21 | // If the target is smaller, ignore right half 22 | else { 23 | right = mid - 1; 24 | } 25 | } 26 | 27 | // If the target is not found in the array 28 | return -1; 29 | } 30 | 31 | public static void main(String[] args) { 32 | int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9}; 33 | int target = 5; 34 | int result = binarySearch(arr, target); 35 | if (result != -1) { 36 | System.out.println("Element " + target + " is present at index " + result); 37 | } else { 38 | System.out.println("Element " + target + " is not present in the array"); 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_8_binary_search/source/binary_search_scheme.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_8_binary_search/source/binary_search_scheme.jpeg -------------------------------------------------------------------------------- /src/main/java/org/alx/article/_9_intellij_plugins/source/intellij_idea_logo.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alxkm/articles/764c20bb37e68c3b771cb2e1660d5d2d828d2ad7/src/main/java/org/alx/article/_9_intellij_plugins/source/intellij_idea_logo.jpeg --------------------------------------------------------------------------------