├── CODE_OF_CONDUCT.md ├── LICENSE ├── README.md ├── algorithm.md ├── architecture.md ├── collections.md ├── concurrency.md ├── core.md ├── custom-stream ├── build.gradle ├── gradle │ └── wrapper │ │ ├── gradle-wrapper.jar │ │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── src │ ├── main │ └── java │ │ ├── ReferencePipeline.java │ │ ├── Sink.java │ │ ├── Stream.java │ │ └── StreamObject.java │ └── test │ └── java │ └── StreamTest.java ├── ddd.md ├── deadlock └── src │ └── Deadlock.java ├── git.md ├── graalvm.md ├── gradle.md ├── hibernate.md ├── javascript.md ├── linux.md ├── maven.md ├── microservices.md ├── patterns.md ├── rabbitmq.md ├── react.md ├── rest.md ├── servlet.md ├── spring.md ├── sql.md ├── test.md └── transaction.md /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, sex characteristics, gender identity and expression, 9 | level of experience, education, socio-economic status, nationality, personal 10 | appearance, race, religion, or sexual identity and orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at anton93lev@gmail.com. All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 72 | 73 | [homepage]: https://www.contributor-covenant.org 74 | 75 | For answers to common questions about this code of conduct, see 76 | https://www.contributor-covenant.org/faq 77 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Anton Liauchuk 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Table of Contents 2 | - [Core](#core) 3 | - [Collections](#collections) 4 | - [Concurrency](#concurrency) 5 | - [Spring](#spring) 6 | - [Servlet](#servlet) 7 | - [Hibernate](#hibernate) 8 | - [Git](#git) 9 | - [Maven](#maven) 10 | - [Gradle](#gradle) 11 | - [Microservices](#microservices) 12 | - [JavaScript](#javascript) 13 | - [Linux](#linux) 14 | - [Patterns](#patterns) 15 | - [DDD](#ddd) 16 | - [Architecture](#architecture) 17 | - [REST](#rest) 18 | - [SQL](#sql) 19 | - [Test](#test) 20 | - [Transactions](#transactions) 21 | - [RabbitMQ](#rabbitmq) 22 | 23 | ## Core 24 | - [What's new in Java 8?](core.md#whats-new-in-java-8) 25 | - [What are the memory types in Java?](core.md#what-are-the-memory-types-in-java) 26 | - [What is java agent?](core.md#what-is-java-agent) 27 | - [Possible Performance Tools for Java?](core.md#possible-performance-tools-for-java) 28 | - [What is java profiler?](core.md#what-is-java-profiler) 29 | - [What is stop the world?](core.md#what-is-stop-the-world) 30 | - [What is the difference between int, Integer and AtomicInteger?](core.md#what-is-the-difference-between-int-integer-and-atomicinteger) 31 | - [How i++ will work for Integer?](core.md#how-i-will-work-for-integer) 32 | - [What can you say about interface constants?](core.md#what-can-you-say-about-interface-constants) 33 | - [What is the contract between equals and hashcode?](core.md#what-is-the-contract-between-equals-and-hashcode) 34 | - [What are the rules for overriding equals/hashcode methods?](core.md#what-are-the-rules-for-overriding-equalshashcode-methods) 35 | - [Are the same fields needed for equals/hashcode implementation?](core.md#are-the-same-fields-needed-for-equalshashcode-implementation) 36 | - [What are the purposes of inner classes?](core.md#what-are-the-purposes-of-inner-classes) 37 | - [What is better interfaces or abstract classes?](core.md#what-is-better-interfaces-or-abstract-classes) 38 | - [Do inner classes have access to private fields from outer class?](core.md#do-inner-classes-have-access-to-private-fields-from-outer-class) 39 | - [What are the differences between static nested classes and non-static nested classes?](core.md#what-are-the-differences-between-static-nested-classes-and-non-static-nested-classes) 40 | - [What are the methods of Object class?](core.md#what-are-the-methods-of-object-class) 41 | - [What is Jmeter?](core.md#what-is-jmeter) 42 | - [Possible Ways to Capture Java Heap Dumps?](core.md#possible-ways-to-capture-java-heap-dumps) 43 | - [What is the result of this code:](core.md#what-is-the-result-of-this-code) 44 | - [Are checked exceptions bad?](core.md#are-checked-exceptions-bad) 45 | - [How var in Java 10 can be used?](core.md#how-var-in-java-10-can-be-used) 46 | - [What is functional interface?](#what-is-functional-interface) 47 | - [Functional interfaces vs abstract classes?](core.md#functional-interfaces-vs-abstract-classes) 48 | - [Why getters/setters?](core.md#why-getterssetters) 49 | - [Serialization?](core.md#serialization) 50 | - [Deserialization after changes in class? Possible issues?](core.md#deserialization-after-changes-in-class-possible-issues) 51 | - [What is the difference between cohesion and coupling?](core.md#what-is-the-difference-between-cohesion-and-coupling) 52 | - [@Override annotation?](core.md#override-annotation) 53 | - [Java modifiers?](core.md#java-modifiers) 54 | - [Exception Hierarchy?](core.md#exception-hierarchy) 55 | - [One exception is thrown by catch block and another one is thrown from finally block, which exception will be thrown by method?](core.md#one-exception-is-thrown-by-catch-block-and-another-one-is-thrown-from-finally-block-which-exception-will-be-thrown-by-method) 56 | - [Is it possible to serialize lambda expression?](core.md#is-it-possible-to-serialize-lambda-expression) 57 | - [Why can Java Collections not directly store Primitives types?](core.md#why-can-java-collections-not-directly-store-primitives-types) 58 | - [How is recursion implemented in Java?](core.md#how-is-recursion-implemented-in-java) 59 | - [Is it needed to document unchecked exceptions?](core.md#is-it-needed-to-document-unchecked-exceptions) 60 | - [Java Date classes?](core.md#java-date-classes) 61 | - [Why Do Local Variables Used in Lambdas Have to Be Final or Effectively Final?](core.md#why-do-local-variables-used-in-lambdas-have-to-be-final-or-effectively-final) 62 | - [orElse() vs orElseGet() in Optional?](core.md#orelse-vs-orelseget-in-optional) 63 | - [How to filter list of objects using Stream API without .filter()?](core.md#how-to-filter-list-of-objects-using-stream-api-without-filter) 64 | - [What is String Pool? How do Strings get there?](core.md#what-is-string-pool-how-do-strings-get-there) 65 | - [What is the difference between StringBuilder and StringBuffer?](core.md#what-is-the-difference-between-stringbuilder-and-stringbuffer) 66 | - [Difference between and ?](core.md#difference-between--super-t-and--extends-t-) 67 | - [How does JIT compiler work?](core.md#how-does-jit-compiler-work) 68 | - [Mutable vs Immutable object?](core.md#mutable-vs-immutable-object) 69 | - [Provide some examples when a finally block won't be executed in Java?](core.md#provide-some-examples-when-a-finally-block-wont-be-executed-in-java) 70 | - [What is type erasure?](core.md#what-is-type-erasure) 71 | - [What is built-in mechanism for creating singletons in Java?](core.md#what-is-built-in-mechanism-for-creating-singletons-in-java) 72 | - [How to understand a third-party library without source code?](core.md#how-to-understand-a-third-party-library-without-source-code) 73 | 74 | ## Collections 75 | - [What is the complexity for get in Hashmap?](collections.md#what-is-the-complexity-for-get-in-hashmap) 76 | - [What is the complexity for get in Hashmap for keys with hashcode = 1?](collections.md#what-is-the-complexity-for-get-in-hashmap-for-keys-with-hashcode--1) 77 | - [What is the hierarchy of collections?](collections.md#what-is-the-hierarchy-of-collections) 78 | - [What is the difference between LinkedList and ArrayList?](collections.md#what-is-the-difference-between-linkedlist-and-arraylist) 79 | - [What is better to use LinkedList or ArrayList?](collections.md#what-is-better-to-use-linkedlist-or-arraylist) 80 | - [What is the implementation of HashMap?](collections.md#what-is-the-implementation-of-hashmap) 81 | - [What are the implementations of Map?](collections.md#what-are-the-implementations-of-map) 82 | - [What is the complexity of removing the last element from LinkedList?](collections.md#what-is-the-complexity-of-removing-the-last-element-from-linkedlist) 83 | - [What are the differences between Set and Map?](collections.md#what-are-the-differences-between-set-and-map) 84 | - [What are the possible implementations of Map for concurrency?](collections.md#what-are-the-possible-implementations-of-map-for-concurrency) 85 | - [What is the main difference between Stream API and Collection?](collections.md#what-is-the-main-difference-between-stream-api-and-collection) 86 | - [What should be avoided in parallel stream?](collections.md#what-should-be-avoided-in-parallel-stream) 87 | - [Implement custom version of java.util.stream.Stream with filter/map methods](collections.md#implement-custom-version-of-javautilstreamstream-with-filtermap-methods) 88 | - [What is forEach?](collections.md#what-is-foreach) 89 | - [When is it better to use foreach loop instead of Iterable.forEach()?](collections.md#when-is-it-better-to-use-foreach-loop-instead-of-iterableforeach) 90 | - [What is SplitIterator?](collections.md#what-is-splititerator) 91 | 92 | ## Concurrency 93 | - [What is usage of wait/notify methods?](#what-is-usage-of-waitnotify-methods) 94 | - [Where wait() can be used?](concurrency.md#where-wait-can-be-used) 95 | - [What is the keyword synchronized?](concurrency.md#what-is-the-keyword-synchronized) 96 | - [What is the keyword volatile?](concurrency.md#what-is-the-keyword-volatile) 97 | - [How volatile is related to happens before?](concurrency.md#how-volatile-is-related-to-happens-before) 98 | - [What are the concurrent collections?](concurrency.md#what-are-the-concurrent-collections) 99 | - [What is CopyOnWriteArrayList?](concurrency.md#what-is-copyonwritearraylist) 100 | - [What can you say about ConcurrentHashMap?](concurrency.md#what-can-you-say-about-concurrenthashmap) 101 | - [What are the benefits of using ConcurrentHashMap over HashTable?](concurrency.md#what-are-the-benefits-of-using-concurrenthashmap-over-hashtable) 102 | - [What is the synchronized access?](concurrency.md#what-is-the-synchronized-access) 103 | - [What is the monitor for non-static synchronized method?](concurrency.md#what-is-the-monitor-for-non-static-synchronized-method) 104 | - [What are possible ways for synchronization threads?](concurrency.md#what-are-possible-ways-for-synchronization-threads) 105 | - [How to wait for finish of thread?](concurrency.md#how-to-wait-for-finish-of-thread) 106 | - [What is the result of this code?](concurrency.md#what-is-the-result-of-this-code) 107 | - [Change the code for getting deadlock](concurrency.md#change-the-code-for-getting-deadlock) 108 | - [What is the Difference between Future and CompletableFuture?](concurrency.md#what-is-the-difference-between-future-and-completablefuture) 109 | - [How do AtomicVariables work?](concurrency.md#how-do-atomicvariables-work) 110 | - [What is the difference between Runnable and Callable?](concurrency.md#what-is-the-difference-between-runnable-and-callable) 111 | 112 | ## Spring 113 | - [How make spring service thread-safe?](spring.md#how-make-spring-service-thread-safe) 114 | - [What is bean?](spring.md#what-is-bean) 115 | - [How bean gets into the container?](spring.md#how-bean-gets-into-the-container) 116 | - [What are the possible bean scopes?](spring.md#what-are-the-possible-bean-scopes) 117 | - [What is the difference @Service between @Component?](spring.md#what-is-the-difference-service-between-component) 118 | - [What is the difference between @Service and @Bean](spring.md#what-is-the-difference-between-service-and-bean) 119 | - [How to call a method after bean initialization?](spring.md#how-to-call-a-method-after-bean-initialization) 120 | - [What is the default scope?](spring.md#what-is-the-default-scope) 121 | - [What is the prototype scope?](spring.md#what-is-the-prototype-scope) 122 | - [What are the possible ways of Dependency Injection?](spring.md#what-are-the-possible-ways-of-dependency-injection) 123 | - [Where better to use dependency injection via constructor? Where via setter?](spring.md#where-better-to-use-dependency-injection-via-constructor-where-via-setter) 124 | - [How to catch the exceptions for controllers?](spring.md#how-to-catch-the-exceptions-for-controllers) 125 | - [What is the difference between BeanFactory and FactoryBean?](spring.md#what-is-the-difference-between-beanfactory-and-factorybean) 126 | - [What is the difference Spring and Spring Boot?](spring.md#what-is-the-difference-spring-and-spring-boot) 127 | - [How to add own auto-configurations?](spring.md#how-to-add-own-auto-configurations) 128 | - [Where can be stored the list of auto-configurations in META-INF?](spring.md#where-can-be-stored-the-list-of-auto-configurations-in-meta-inf) 129 | - [What are the possible ways of configurations in Spring?](spring.md#what-are-the-possible-ways-of-configurations-in-spring) 130 | - [What is the lookup method?](spring.md#what-is-the-lookup-method) 131 | - [What is declarative transaction in Spring?](spring.md#what-is-declarative-transaction-in-spring) 132 | - [What creates a proxy?](spring.md#what-creates-a-proxy) 133 | - [Does @transactional method work in the case of execution in the same class?](spring.md#does-transactional-method-work-in-the-case-of-execution-in-the-same-class) 134 | - [What is environment?](spring.md#what-is-environment) 135 | - [How does auto-configuration work?](spring.md#how-does-auto-configuration-work) 136 | - [What is the difference between @Resource and @Autowired annotations?](spring.md#what-is-the-difference-between-resource-and-autowired-annotations) 137 | - [What is the feature in Spring Boot for setting up the dependencies?](spring.md#what-is-the-feature-in-spring-boot-for-setting-up-the-dependencies) 138 | - [Where does Spring Boot application begin?](spring.md#where-does-spring-boot-application-begin) 139 | - [What is the difference between @Controller and @RestController annotations?](spring.md#what-is-the-difference-between-controller-and-restcontroller-annotations) 140 | - [Does @Qualifier annotation can work only with bean name from @Component annotation?](spring.md#does-qualifier-annotation-can-work-only-with-bean-name-from-component-annotation) 141 | - [Is it required to put @Repository annotation in the case of extending JpaRepository?](spring.md#is-it-required-to-put-repository-annotation-in-the-case-of-extending-jparepository) 142 | - [How ResponseEntity can be used?](spring.md#how-responseentity-can-be-used) 143 | - [Does entity from @Transactional method can be updated without executing save method?](spring.md#does-entity-from-transactional-method-can-be-updated-without-executing-save-method) 144 | - [Is it possible to have only one transaction in the case of executing several @Transactional methods?](spring.md#is-it-possible-to-have-only-one-transaction-in-the-case-of-executing-several-transactional-methods) 145 | - [Anti-patterns of bean validation?](spring.md#anti-patterns-of-bean-validation) 146 | - [Is it good practice to define interface for Spring bean?](spring.md#is-it-good-practice-to-define-interface-for-spring-bean) 147 | - [How does @Transactional annotation work?](spring.md#how-does-transactional-annotation-work) 148 | - [How to use @NamedEntityGraph with Spring Data JPA?](spring.md#how-to-use-namedentitygraph-with-spring-data-jpa) 149 | 150 | ## Servlet 151 | - [What is servlet?](servlet.md#what-is-servlet) 152 | - [What is difference between parameters and attributes?](servlet.md#what-is-difference-between-parameters-and-attributes) 153 | - [What is the life cycle of servlet?](servlet.md#what-is-the-life-cycle-of-servlet) 154 | - [What is the servlet mapping?](servlet.md#what-is-the-servlet-mapping) 155 | 156 | ## Hibernate 157 | - [What is detached entity?](hibernate.md#what-is-detached-entity) 158 | - [What is the use of flush?](hibernate.md#what-is-the-use-of-flush) 159 | - [What are the cache levels?](hibernate.md#what-are-the-cache-levels) 160 | - [What is the first-level cache?](hibernate.md#what-is-the-first-level-cache) 161 | - [Hibernate inheritance?](hibernate.md#hibernate-inheritance) 162 | - [Common hibernate mistakes?](hibernate.md#common-hibernate-mistakes) 163 | - [Hibernate best practice?](hibernate.md#hibernate-best-practice) 164 | - [How to Define and Use a @NamedEntityGraph?](hibernate.md#how-to-define-and-use-a-namedentitygraph) 165 | - [Possible issues with defining equals/hashcode on JPA entities?](hibernate.md#possible-issues-with-defining-equalshashcode-on-jpa-entities) 166 | - [How lazy loading works in hibernate?](hibernate.md#how-lazy-loading-works-in-hibernate) 167 | - [Optimal queries in Hibernate?](hibernate.md#optimal-queries-in-hibernate) 168 | - [Possible enum mapping solutions?](hibernate.md#possible-enum-mapping-solutions) 169 | - [In which cases LazyInitializationException can occur?](hibernate.md#in-which-cases-lazyinitializationexception-can-occur) 170 | - [There are three SQL statements in one transaction, during the first one exception occurred on DB level, what will happen with others if you catch the first one?](hibernate.md#there-are-three-sql-statements-in-one-transaction-during-the-first-one-exception-occurred-on-db-level-what-will-happen-with-others-if-you-catch-the-first-one) 171 | 172 | ## Git 173 | - [What is the difference between merge and rebase?](git.md#what-is-the-difference-between-merge-and-rebase) 174 | - [What is git reset?](git.md#what-is-git-reset) 175 | - [What is the difference between soft reset and hard reset?](git.md#what-is-the-difference-between-soft-reset-and-hard-reset) 176 | - [How to combine multiple commits into one prior to push?](git.md#how-to-combine-multiple-commits-into-one-prior-to-push) 177 | 178 | ## Maven 179 | - [What is the difference between Maven and Gradle?](maven.md#what-is-the-difference-between-maven-and-gradle) 180 | - [How will work Maven in the case of multiple version of the same dependency?](maven.md#how-will-work-maven-in-the-case-of-multiple-version-of-the-same-dependency) 181 | - [What is the dependency management in Maven?](maven.md#what-is-the-dependency-management-in-maven) 182 | - [Does maven support inheritance for pom files?](maven.md#does-maven-support-inheritance-for-pom-files) 183 | 184 | ## Gradle 185 | - [What is the difference between `api` and `implementation`?](gradle.md#what-is-the-difference-between-api-and-implementation) 186 | 187 | ## Microservices 188 | - [What are the possible ways for communication between microservices?](microservices.md#what-are-the-possible-ways-for-communication-between-microservices) 189 | - [What is exchange in message queue?](microservices.md#what-is-exchange-in-message-queue) 190 | - [What are the benefits of microservices?](microservices.md#what-are-the-benefits-of-microservices) 191 | - [What are the disadvantages of microservices?](microservices.md#what-are-the-disadvantages-of-microservices) 192 | - [What are the possible issues in microservices](microservices.md#what-are-the-possible-issues-in-microservices) 193 | - [What are the possible solutions for the case when one service is not available?](microservices.md#what-are-the-possible-solutions-for-the-case-when-one-service-is-not-available) 194 | - [What is the difference between synchronous and asynchronous communication?](microservices.md#what-is-the-difference-between-synchronous-and-asynchronous-communication) 195 | - [What are possible ways for implementing authentication in microservices?](microservices.md#what-are-possible-ways-for-implementing-authentication-in-microservices) 196 | - [What is Eventual consistency?](microservices.md#what-is-eventual-consistency) 197 | - [How different types of communication can influence on performance?](microservices.md#how-different-types-of-communication-can-influence-on-performance) 198 | - [What are possible strategies and issues in microservices deployment?](microservices.md#what-are-possible-strategies-and-issues-in-microservices-deployment) 199 | 200 | ## JavaScript 201 | - [What are possible variable scopes?](javascript.md#what-are-possible-variable-scopes) 202 | - [What is bind? call & apply?](javascript.md#what-is-bind-call--apply) 203 | - [What is losing of context in js?](javascript.md#what-is-losing-of-context-in-js) 204 | - [Is Javascript single threaded?](javascript.md#is-javascript-single-threaded) 205 | - [What is closure in js?](javascript.md#what-is-closure-in-js) 206 | - [How to check if element exists in html?](javascript.md#how-to-check-if-element-exists-in-html) 207 | - [2 functions with the same name but with different number of parameters. Can be the issues in this case?](javascript.md#2-functions-with-the-same-name-but-with-different-number-of-parameters-can-be-the-issues-in-this-case) 208 | 209 | ## Linux 210 | - [How to print the list of processes in terminal Linux?](linux.md#how-to-print-the-list-of-processes-in-terminal-linux) 211 | 212 | ## Patterns 213 | - [Which architectural patterns you know?](patterns.md#which-architectural-patterns-you-know) 214 | - [What does it mean single responsibility?](patterns.md#what-does-it-mean-single-responsibility) 215 | - [What is the difference between facade and proxy/gateway?](patterns.md#what-is-the-difference-between-facade-and-proxygateway) 216 | - [What can we do in the case of constructor with big number of parameters?](patterns.md#what-can-we-do-in-the-case-of-constructor-with-big-number-of-parameters) 217 | - [How can be implemented builder?](patterns.md#how-can-be-implemented-builder) 218 | - [What is pattern Visitor?](patterns.md#what-is-pattern-visitor) 219 | - [What is the issue can be solved by visitor?](patterns.md#what-is-the-issue-can-be-solved-by-visitor) 220 | - [What can you say about pattern observer?](patterns.md#what-can-you-say-about-pattern-observer) 221 | - [How to initialize object depends on type?](patterns.md#how-to-initialize-object-depends-on-type) 222 | - [Why Dependency Injection is needed?](patterns.md#why-dependency-injection-is-needed) 223 | - [Should services always return dtos?](patterns.md#should-services-always-return-dtos) 224 | - [The difference between adapter and decorator?](patterns.md#the-difference-between-adapter-and-decorator) 225 | 226 | ## DDD 227 | - [What is DDD?](ddd.md#what-is-ddd) 228 | - [Why DDD is needed?](ddd.md#why-ddd-is-needed) 229 | - [What is aggregate in DDD?](ddd.md#what-is-aggregate-in-ddd) 230 | - [What is anemic domain model?](ddd.md#what-is-anemic-domain-model) 231 | - [What is the correct way for having relations between aggregates?](ddd.md#what-is-the-correct-way-for-having-relations-between-aggregates) 232 | - [How to update several aggregates during one transaction?](ddd.md#how-to-update-several-aggregates-during-one-transaction) 233 | - [What is event storming?](ddd.md#what-is-event-storming) 234 | - [How domain events are related to eventual consistency?](ddd.md#how-domain-events-are-related-to-eventual-consistency) 235 | - [What is the difference between domain events and event sourcing?](ddd.md#what-is-the-difference-between-domain-events-and-event-sourcing) 236 | - [What is CQRS?](ddd.md#what-is-cqrs) 237 | - [What is the best practice for validation in DDD?](ddd.md#what-is-the-best-practice-for-validation-in-ddd) 238 | - [What is the best practice for Value Object?](ddd.md#what-is-the-best-practice-for-value-object) 239 | - [Possible issues with using domain model with public getters/setters and empty constructor?](ddd.md#possible-issues-with-using-domain-model-with-public-getterssetters-and-empty-constructor) 240 | - [How to work with large domain models? Is it correct to have a lot of fields in domain model?](ddd.md#how-to-work-with-large-domain-models-is-it-correct-to-have-a-lot-of-fields-in-domain-model) 241 | - [How should be published integration events? Inside or outside transaction?](ddd.md#how-should-be-published-integration-events-inside-or-outside-transaction) 242 | - [How to define the reference between aggregates?](ddd.md#how-to-define-the-reference-between-aggregates) 243 | - [Where to put validation rule for value object?](ddd.md#where-to-put-validation-rule-for-value-object) 244 | - [Possible integration ways between modules?](ddd.md#possible-integration-ways-between-modules) 245 | 246 | ## Architecture 247 | - [What are the differences between monolith and microservices? (Performance/Deployability/Failure impact and etc)](architecture.md#what-are-the-differences-between-monolith-and-microservices-performancedeployabilityfailure-impact-and-etc) 248 | - [Imperative vs functional vs reactive programming?](architecture.md#imperative-vs-functional-vs-reactive-programming) 249 | - [What is Serverless](architecture.md#what-is-serverless) 250 | - [What is the difference between native code, machine code and assembly code?](architecture.md#what-is-the-difference-between-native-code-machine-code-and-assembly-code) 251 | - [What is the difference between sharding and partitioning for databases?](architecture.md#what-is-the-difference-between-sharding-and-partitioning-for-databases) 252 | 253 | ## REST 254 | - [What is rest architecture? What are the requirements?](rest.md#what-is-rest-architecture-what-are-the-requirements) 255 | - [Is there state in rest architecture?](rest.md#is-there-state-in-rest-architecture) 256 | - [Can be used query params in rest architecture?](rest.md#can-be-used-query-params-in-rest-architecture) 257 | - [What is the difference get and post?](rest.md#what-is-the-difference-get-and-post) 258 | - [What is the difference between soap and rest?](rest.md#what-is-the-difference-between-soap-and-rest) 259 | - [Is it correct to update something during get request?](rest.md#is-it-correct-to-update-something-during-get-request) 260 | - [Is it possible to use body in get requests?](rest.md#is-it-possible-to-use-body-in-get-requests) 261 | - [What are possible types of requests for http protocol?](rest.md#what-are-possible-types-of-requests-for-http-protocol) 262 | - [Why method options is needed?](rest.md#why-method-options-is-needed) 263 | - [What is the difference between put and post?](rest.md#what-is-the-difference-between-put-and-post) 264 | - [What can be used as rest client?](rest.md#what-can-be-used-as-rest-client) 265 | - [How http protocol work?](rest.md#how-http-protocol-work) 266 | - [What are the possible solutions in the case of big number of parameters for search method?](rest.md#what-are-the-possible-solutions-in-the-case-of-big-number-of-parameters-for-search-method) 267 | - [What should be the response in the case of DELETE request?](rest.md#what-should-be-the-response-in-the-case-of-delete-request) 268 | - [What is the best solution for representing Enum in API?](rest.md#what-is-the-best-solution-for-representing-enum-in-api) 269 | - [What is the best practice for getting Unique Resource From Sub-Collection?](rest.md#what-is-the-best-practice-for-getting-unique-resource-from-sub-collection) 270 | - [How search in sub-collections can be implemented?](rest.md#how-search-in-sub-collections-can-be-implemented) 271 | - [What is the best practice for nested resources?](rest.md#what-is-the-best-practice-for-nested-resources) 272 | - [Fine Grained CRUD Resources vs. Coarse Grained Resources?](rest.md#fine-grained-crud-resources-vs-coarse-grained-resources) 273 | - [Best guidelines?](rest.md#best-guidelines) 274 | - [Best practice for PATCH?](rest.md#best-practice-for-patch) 275 | - [Do sessions violate REST?](rest.md#do-sessions-violate-rest) 276 | - [When to use GraphQL?](rest.md#when-to-use-graphql) 277 | - [What is ElasticSearch?](rest.md#what-is-elasticsearch) 278 | - [What are the possible ways of versioning?](rest.md#what-are-the-possible-ways-of-versioning) 279 | - [Is it good practice to use Map in a model for a REST API?](rest.md#is-it-good-practice-to-use-mapstring-object-in-a-model-for-a-rest-api) 280 | 281 | ## SQL 282 | - [What is having in sql?](sql.md#what-is-having-in-sql) 283 | - [What are the possible issues with indexes?](sql.md#what-are-the-possible-issues-with-indexes) 284 | - [Sql works very slowly, what are the possible improvements (the database is MySQL, for example)?](sql.md#sql-works-very-slowly-what-are-the-possible-improvements-the-database-is-mysql-for-example) 285 | - [NoSQL vs SQL Databases](sql.md#nosql-vs-sql-databases) 286 | - [OLAP vs OLTP Databases](sql.md#olap-vs-oltp-databases) 287 | 288 | ## Test 289 | - [What is the difference between integration and unit tests?](test.md#what-is-the-difference-between-integration-and-unit-tests) 290 | - [Unit test executes code from 2 classes, is it correct? Is it unit or integration test?](test.md#unit-test-executes-code-from-2-classes-is-it-correct-is-it-unit-or-integration-test) 291 | - [What can be used for unit tests?](test.md#what-can-be-used-for-unit-tests) 292 | - [What is better to use randomized or hardcode data for unit tests?](test.md#what-is-better-to-use-randomized-or-hardcode-data-for-unit-tests) 293 | - [Is it possible to test the architecture of application?](test.md#is-it-possible-to-test-the-architecture-of-application) 294 | - [Does TDD include integration tests?](test.md#does-tdd-include-integration-tests) 295 | - [Is it good practice to check in tests that non-state-changing methods were called?](test.md#is-it-good-practice-to-check-in-tests-that-non-state-changing-methods-were-called) 296 | - [The differences between Spy and Mock in Mockito?](test.md#the-differences-between-spy-and-mock-in-mockito) 297 | - [Is it good practice to use in-memory db for tests?](test.md#is-it-good-practice-to-use-in-memory-db-for-tests) 298 | - [Mockito: doReturn vs thenReturn?](test.md#mockito-doreturn-vs-thenreturn) 299 | - [How to mock third party service?](test.md#how-to-mock-third-party-service) 300 | - [How would you assess the quality and effectiveness of unit tests in a Java codebase? Can you explain what mutation testing is and how tools like PIT can help?](test.md#how-would-you-assess-the-quality-and-effectiveness-of-unit-tests-in-a-java-codebase-can-you-explain-what-mutation-testing-is-and-how-tools-like-pit-can-help) 301 | 302 | ## Transactions 303 | - [What is transaction?](transaction.md#what-is-transaction) 304 | - [What are the requirements for transactions?](transaction.md#what-are-the-requirements-for-transactions) 305 | - [What is a distributed transaction?](transaction.md#what-is-a-distributed-transaction) 306 | - [What are isolation levels?](transaction.md#what-are-isolation-levels) 307 | - [What are the possible issues in the case of parallel access by transactions?](transaction.md#what-are-the-possible-issues-in-the-case-of-parallel-access-by-transactions) 308 | - [What are possible options for implementing transactions in microservices](transaction.md#what-are-possible-options-for-implementing-transactions-in-microservices) 309 | - [What is the difference between optimistic and pessimistic locking?](transaction.md#what-is-the-difference-between-optimistic-and-pessimistic-locking) 310 | - [Is it possible to use transaction for select statements?](transaction.md#is-it-possible-to-use-transaction-for-select-statements) 311 | - [What locks are made in the case of using Repeatable Read isolation level?](transaction.md#what-locks-are-made-in-the-case-of-using-repeatable-read-isolation-level) 312 | 313 | ## RabbitMQ 314 | - [What is RabbitMQ?](rabbitmq.md#what-is-rabbitmq) 315 | - [What are the advantages/disadvantages of using message brokers?](rabbitmq.md#what-are-the-advantagesdisadvantages-of-using-message-brokers) 316 | - [What is the Exchange in RabbitMQ?](rabbitmq.md#what-is-the-exchange-in-rabbitmq) 317 | 318 | ## GraalVM 319 | - [What is GraalVM Native Image?](graalvm.md#what-is-graalvm-native-image) 320 | -------------------------------------------------------------------------------- /algorithm.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anton-liauchuk/java-interview/c12fb26b7aa8f16b5ba39fa9b8c38c626f99a696/algorithm.md -------------------------------------------------------------------------------- /architecture.md: -------------------------------------------------------------------------------- 1 | # Architecture 2 | - [What are the differences between monolith and microservices? (Performance/Deployability/Failure impact and etc)](#what-are-the-differences-between-monolith-and-microservices-performancedeployabilityfailure-impact-and-etc) 3 | - [Imperative vs functional vs reactive programming?](#imperative-vs-functional-vs-reactive-programming) 4 | - [What is Serverless](#what-is-serverless) 5 | - [What is the difference between native code, machine code and assembly code?](#what-is-the-difference-between-native-code-machine-code-and-assembly-code) 6 | - [What is the difference between sharding and partitioning for databases?](#what-is-the-difference-between-sharding-and-partitioning-for-databases) 7 | 8 | ## What are the differences between monolith and microservices? (Performance/Deployability/Failure impact and etc) 9 | ###### Relative links: 10 | - http://www.kamilgrzybek.com/design/modular-monolith-architectural-drivers/ 11 | 12 | ## Imperative vs functional vs reactive programming? 13 | **Imperative programming** is fundamental to any programming language and even machine language is imperative. Internally other programming paradigm in some way or the other use imperative style internally but abstracts this out for the caller. **Imperative style is mostly sequential and follows a natural flow**, hence it is easy to write, debug and troubleshoot. In most case this offers better raw performance than other. 14 | 15 | **Functional programming** is treating computation as “**mathematical functions**”, using pure function without side effect which does not change state. State are immutable in functional programming. 16 | 17 | **Reactive programming** is typically **asynchronous events data stream over time and its propagation of change**. It is built on observable (publish/subscribe) & iterator pattern. Generally there are also functional programming and reactive programming done together for transformation of one streams to another. 18 | ###### Relative links: 19 | - https://www.webagam.com/2018/11/24/imperative-functional-reactive-programming-which-one-to-use-when-and-for-what/ 20 | 21 | ## What is Serverless 22 | Like many trends in software, there’s no one clear view of what Serverless is. For starters, it encompasses two different but overlapping areas: 23 | 24 | 1. Serverless was first used to describe applications that significantly or fully incorporate third-party, cloud-hosted applications and services, to manage server-side logic and state. These are typically “rich client” applications—think single-page web apps, or mobile apps—that use the vast ecosystem of cloud-accessible databases (e.g., Parse, Firebase), authentication services (e.g., Auth0, AWS Cognito), and so on. These types of services have been previously described as “(Mobile) Backend as a Service", and I use "BaaS" as shorthand in the rest of this article. 25 | 2. Serverless can also mean applications where server-side logic is still written by the application developer, but, unlike traditional architectures, it’s run in stateless compute containers that are event-triggered, ephemeral (may only last for one invocation), and fully managed by a third party. One way to think of this is “Functions as a Service” or "FaaS". (Note: The original source for this name—a tweet by @marak—is no longer publicly available.) AWS Lambda is one of the most popular implementations of a Functions-as-a-Service platform at present, but there are many others, too. 26 | ###### Relative links: 27 | - https://martinfowler.com/articles/serverless.html 28 | 29 | ## What is the difference between native code, machine code and assembly code? 30 | ###### Relative links: 31 | - https://stackoverflow.com/questions/3434202/what-is-the-difference-between-native-code-machine-code-and-assembly-code 32 | 33 | ## What is the difference between sharding and partitioning for databases? 34 | ###### Relative links: 35 | - https://hazelcast.com/glossary/sharding/ -------------------------------------------------------------------------------- /collections.md: -------------------------------------------------------------------------------- 1 | # Collections 2 | - [What is the complexity for get in Hashmap?](#what-is-the-complexity-for-get-in-hashmap) 3 | - [What is the complexity for get in Hashmap for keys with hashcode = 1?](#what-is-the-complexity-for-get-in-hashmap-for-keys-with-hashcode--1) 4 | - [What is the hierarchy of collections?](#what-is-the-hierarchy-of-collections) 5 | - [What is the difference between LinkedList and ArrayList?](#what-is-the-difference-between-linkedlist-and-arraylist) 6 | - [What is better to use LinkedList or ArrayList?](#what-is-better-to-use-linkedlist-or-arraylist) 7 | - [What is the implementation of HashMap?](#what-is-the-implementation-of-hashmap) 8 | - [What are the implementations of Map?](#what-are-the-implementations-of-map) 9 | - [What is the complexity of removing the last element from LinkedList?](#what-is-the-complexity-of-removing-the-last-element-from-linkedlist) 10 | - [What are the differences between Set and Map?](#what-are-the-differences-between-set-and-map) 11 | - [What are the possible implementations of Map for concurrency?](#what-are-the-possible-implementations-of-map-for-concurrency) 12 | - [What is the main difference between Stream API and Collection?](#what-is-the-main-difference-between-stream-api-and-collection) 13 | - [What should be avoided in parallel stream?](#what-should-be-avoided-in-parallel-stream) 14 | - [Implement custom version of java.util.stream.Stream with filter/map methods](#implement-custom-version-of-javautilstreamstream-with-filtermap-methods) 15 | - [What is forEach?](#what-is-foreach) 16 | - [When is it better to use foreach loop instead of Iterable.forEach()?](#when-is-it-better-to-use-foreach-loop-instead-of-iterableforeach) 17 | - [What is SplitIterator?](#what-is-splititerator) 18 | 19 | ## What is the complexity for get in Hashmap? 20 | It depends on many things. It's usually O(1), with a decent hash which itself is constant time... but you could have a hash which takes a long time to compute, and if there are multiple items in the hash map which return the same hash code, get will have to iterate over them calling equals on each of them to find a match. 21 | ###### Relative links: 22 | + https://stackoverflow.com/questions/4553624/hashmap-get-put-complexity 23 | 24 | ## What is the complexity for get in Hashmap for keys with hashcode = 1? 25 | If there are multiple items in the hash map which return the same hash code, get will have to iterate over them calling equals on each of them to find a match, so it's O(n) in this case. 26 | ###### Relative links: 27 | + https://stackoverflow.com/questions/4553624/hashmap-get-put-complexity 28 | 29 | ## What is the hierarchy of collections? 30 | The collection interfaces are divided into two groups. The most basic interface, java.util.Collection, has the following descendants: 31 | + java.util.Set 32 | + java.util.SortedSet 33 | + java.util.NavigableSet 34 | + java.util.Queue 35 | + java.util.concurrent.BlockingQueue 36 | + java.util.concurrent.TransferQueue 37 | + java.util.Deque 38 | + java.util.concurrent.BlockingDeque 39 | 40 | The other collection interfaces are based on java.util.Map and are not true collections. However, these interfaces contain collection-view operations, which enable them to be manipulated as collections. Map has the following offspring: 41 | + java.util.SortedMap 42 | + java.util.NavigableMap 43 | + java.util.concurrent.ConcurrentMap 44 | + java.util.concurrent.ConcurrentNavigableMap 45 | ###### Relative links: 46 | + https://docs.oracle.com/javase/8/docs/technotes/guides/collections/overview.html 47 | + https://habr.com/ru/post/237043/ 48 | 49 | ## What is the difference between LinkedList and ArrayList? 50 | From the hierarchy diagram, they all implement List interface. They are very similar to use. Their main difference is their implementation which causes different performance for different operations. ArrayList is implemented as a resizable array. As more elements are added to ArrayList, its size is increased dynamically. It's elements can be accessed directly by using the get and set methods, since ArrayList is essentially an array. LinkedList is implemented as a double linked list. Its performance on add and remove is better than Arraylist, but worse on get and set methods. 51 | ###### Relative links: 52 | + https://stackoverflow.com/questions/322715/when-to-use-linkedlist-over-arraylist-in-java 53 | + https://dzone.com/articles/arraylist-vs-linkedlist-vs 54 | 55 | ## What is better to use LinkedList or ArrayList? 56 | The difference of their performance is obvious. LinkedList is faster in add and remove, but slower in get. Based on the complexity table and testing results, we can figure out when to use ArrayList or LinkedList. In brief, LinkedList should be preferred if: 57 | + there are no large number of random access of element 58 | + there are a large number of add/remove operations 59 | ###### Relative links: 60 | + https://dzone.com/articles/arraylist-vs-linkedlist-vs 61 | + https://stackoverflow.com/questions/322715/when-to-use-linkedlist-over-arraylist-in-java 62 | 63 | ## What is the implementation of HashMap? 64 | ***HashMap*** uses the array of Nodes(named as table), where Node has fields like the key, value (and much more). Here the Node is represented by class HashMapEntry. Basically, HashMap has an array where the key-value data is stored. It calculates the index in the array where the Node can be placed and it is placed there. Now while getting the element from HashMap, it again calculates the index of the element to retrieve and goes to the array index and returns the value of the element/Node(if exists). 65 | ###### Relative links: 66 | + https://medium.com/@mr.anmolsehgal/java-hashmap-internal-implementation-21597e1efec3 67 | + https://www.geeksforgeeks.org/java-util-hashmap-in-java/ 68 | 69 | ## What are the implementations of Map? 70 | The Java platform contains three general-purpose Map implementations: ***HashMap***, ***TreeMap***, and ***LinkedHashMap***. Their behavior and performance are precisely analogous to HashSet, TreeSet, and LinkedHashSet 71 | ###### Relative links: 72 | + https://docs.oracle.com/javase/tutorial/collections/interfaces/map.html 73 | 74 | ## What is the complexity of removing the last element from LinkedList? 75 | O(1) 76 | ###### Relative links: 77 | + https://stackoverflow.com/questions/322715/when-to-use-linkedlist-over-arraylist-in-java 78 | 79 | ## What are the differences between Set and Map? 80 | Main differences between a ***Set*** and a ***Map*** in Java are: 81 | + Duplicate Elements: A Set does not allow inserting duplicate elements. A Map does not allow using duplicate keys, but it allows inserting duplicate values for unique keys. 82 | + Null values: A Set allows inserting maximum one null value. In a Map we can have single null key at most and any number of null values. 83 | + Ordering: A Set does not maintain any order of elements. Some of sub-classes of a Set can sort the elements in an order like LinkedHashSet. A Map does not maintain any order of its elements. Some of its sub-classes like TreeMap store elements of the map in ascending order of keys. 84 | ###### Relative links: 85 | + https://www.quora.com/What-is-the-difference-between-a-Set-and-a-Map-in-Java 86 | 87 | ## What are the possible implementations of Map for concurrency? 88 | + ***ConcurrentHashMap*** allows concurrent modification of the Map from several threads without the need to block them. Collections.synchronizedMap(map) creates a blocking Map which will degrade performance, albeit ensure consistency (if used properly). 89 | + ***Collections.synchronizedMap(Map)*** is the second option if you need to ensure data consistency, and each thread needs to have an up-to-date view of the map. Use the first if performance is critical, and each thread only inserts data to the map, with reads happening less frequently. 90 | ###### Relative links: 91 | + https://stackoverflow.com/questions/510632/whats-the-difference-between-concurrenthashmap-and-collections-synchronizedmap 92 | 93 | ## What is the main difference between Stream API and Collection? 94 | Streams differ from collections in several ways: 95 | + No storage. A stream is not a data structure that stores elements; instead, it conveys elements from a source such as a data structure, an array, a generator function, or an I/O channel, through a pipeline of computational operations. 96 | + Functional in nature. An operation on a stream produces a result, but does not modify its source. For example, filtering a Stream obtained from a collection produces a new Stream without the filtered elements, rather than removing elements from the source collection. 97 | + Laziness-seeking. Many stream operations, such as filtering, mapping, or duplicate removal, can be implemented lazily, exposing opportunities for optimization. For example, "find the first String with three consecutive vowels" need not examine all the input strings. Stream operations are divided into intermediate (Stream-producing) operations and terminal (value- or side-effect-producing) operations. Intermediate operations are always lazy. 98 | + Possibly unbounded. While collections have a finite size, streams need not. Short-circuiting operations such as limit(n) or findFirst() can allow computations on infinite streams to complete in finite time. 99 | + Consumable. The elements of a stream are only visited once during the life of a stream. Like an Iterator, a new stream must be generated to revisit the same elements of the source. 100 | ###### Relative links: 101 | + https://stackoverflow.com/questions/39432699/what-is-the-difference-between-streams-and-collections-in-java-8 102 | 103 | ## What should be avoided in parallel stream? 104 | The problem is that all parallel streams use common fork-join thread pool, and if you submit a long-running task, you effectively block all threads in the pool. Consequently, you block all other tasks that are using parallel streams. 105 | ###### Relative links: 106 | + https://dzone.com/articles/think-twice-using-java-8 107 | + https://stackoverflow.com/questions/20375176/should-i-always-use-a-parallel-stream-when-possible 108 | 109 | ## Implement custom version of java.util.stream.Stream with filter/map methods 110 | The example of implementation can be found in folder [custom-stream](./custom-stream) 111 | 112 | ## What is forEach? 113 | ###### Relative links: 114 | - https://mkyong.com/java8/java-8-foreach-examples/ 115 | 116 | ## When is it better to use foreach loop instead of Iterable.forEach()? 117 | The deficiencies of Iterable.forEach(): 118 | - Can't use non-final variables; 119 | - Can't handle checked exceptions; 120 | - Limited flow-control; 121 | - Might execute in parallel; 122 | - Might hurt performance; 123 | - If you do need parallelism, it is probably much faster and not much more difficult to use an ExecutorService; 124 | - Makes debugging more confusing; 125 | - Streams in general are more difficult to code, read, and debug; 126 | ###### Relative links: 127 | - https://stackoverflow.com/questions/16635398/java-8-iterable-foreach-vs-foreach-loop 128 | 129 | ## What is SplitIterator? 130 | ###### Relative links: 131 | - https://www.baeldung.com/java-spliterator 132 | - https://www.geeksforgeeks.org/java-util-interface-spliterator-java8/ 133 | - https://blog.rapid7.com/2015/10/28/java-8-introduction-to-parallelism-and-spliterator/ 134 | 135 | [Home Page](README.md) 136 | -------------------------------------------------------------------------------- /concurrency.md: -------------------------------------------------------------------------------- 1 | # Concurrency 2 | - [What is usage of wait/notify methods?](#what-is-usage-of-waitnotify-methods) 3 | - [Where wait() can be used?](#where-wait-can-be-used) 4 | - [What is the keyword synchronized?](#what-is-the-keyword-synchronized) 5 | - [What is the keyword volatile?](#what-is-the-keyword-volatile) 6 | - [How volatile is related to happens before?](#how-volatile-is-related-to-happens-before) 7 | - [What are the concurrent collections?](#what-are-the-concurrent-collections) 8 | - [What is CopyOnWriteArrayList?](#what-is-copyonwritearraylist) 9 | - [What can you say about ConcurrentHashMap?](#what-can-you-say-about-concurrenthashmap) 10 | - [What are the benefits of using ConcurrentHashMap over HashTable?](#what-are-the-benefits-of-using-concurrenthashmap-over-hashtable) 11 | - [What is the synchronized access?](#what-is-the-synchronized-access) 12 | - [What is the monitor for non-static synchronized method?](#what-is-the-monitor-for-non-static-synchronized-method) 13 | - [What are possible ways for synchronization threads?](#what-are-possible-ways-for-synchronization-threads) 14 | - [How to wait for finish of thread?](#how-to-wait-for-finish-of-thread) 15 | - [What is the result of this code?](#what-is-the-result-of-this-code) 16 | - [Change the code for getting deadlock](#change-the-code-for-getting-deadlock) 17 | - [What is the Difference between Future and CompletableFuture?](#what-is-the-difference-between-future-and-completablefuture) 18 | - [How do AtomicVariables work?](#how-do-atomicvariables-work) 19 | 20 | ## What is usage of wait/notify methods? 21 | ***wait().*** It tells the calling thread to give up the lock and go to sleep until some other thread enters the same monitor and calls notify(). 22 | ***notify().*** It wakes up one single thread that called wait() on the same object. It should be noted that calling notify() does not actually give up a lock on a resource. It tells a waiting thread that that thread can wake up. However, the lock is not actually given up until the notifier’s synchronized block has completed. 23 | ***notifyAll().*** It wakes up all the threads that called wait() on the same object. The highest priority thread will run first in most of the situation, though not guaranteed. Other things are same as notify() method above. 24 | ###### Relative links: 25 | + https://howtodoinjava.com/java/multi-threading/wait-notify-and-notifyall-methods/ 26 | 27 | ## Where wait() can be used? 28 | synchronized 29 | ###### Relative links: 30 | + https://stackoverflow.com/questions/2779484/why-must-wait-always-be-in-synchronized-block 31 | 32 | ## What is the keyword synchronized? 33 | A piece of logic marked with synchronized becomes a synchronized block, allowing only one thread to execute at any given time. 34 | ###### Relative links: 35 | + https://www.baeldung.com/java-synchronized 36 | 37 | ## What is the keyword volatile? 38 | The ***volatile*** modifier guarantees that any thread that reads a field will see the most recently written value. In Java, each thread has a separate memory space known as working memory; this holds the values of different variables used for performing operations. After performing an operation, thread copies the updated value of the variable to the main memory, and from there other threads can read the latest value. Simply put, the volatile keyword marks a variable to always go to main memory, for both reads and writes, in the case of multiple threads accessing it. 39 | ###### Relative links: 40 | + https://stackoverflow.com/questions/106591/what-is-the-volatile-keyword-useful-for 41 | + https://www.baeldung.com/java-volatile 42 | 43 | ## How volatile is related to happens before? 44 | To address the instruction reordering challenge, the Java volatile keyword gives a "happens-before" guarantee, in addition to the visibility guarantee. The happens-before guarantee guarantees that: 45 | + Reads from and writes to other variables cannot be reordered to occur after a write to a volatile variable, if the reads / writes originally occurred before the write to the volatile variable. The reads / writes before a write to a volatile variable are guaranteed to "happen before" the write to the volatile variable. Notice that it is still possible for e.g. reads / writes of other variables located after a write to a volatile to be reordered to occur before that write to the volatile. Just not the other way around. From after to before is allowed, but from before to after is not allowed. 46 | + Reads from and writes to other variables cannot be reordered to occur before a read of a volatile variable, if the reads / writes originally occurred after the read of the volatile variable. Notice that it is possible for reads of other variables that occur before the read of a volatile variable can be reordered to occur after the read of the volatile. Just not the other way around. From before to after is allowed, but from after to before is not allowed. 47 | 48 | The above happens-before guarantee assures that the visibility guarantee of the volatile keyword are being enforced. 49 | ###### Relative links: 50 | + http://tutorials.jenkov.com/java-concurrency/volatile.html#the-java-volatile-happens-before-guarantee 51 | 52 | ## What are the concurrent collections? 53 | + ***ConcurrentHashMap*** 54 | + ***CopyOnWriteArrayList/CopyOnWriteArraySet*** 55 | + ***BlockingQueue*** 56 | ###### Relative links: 57 | + https://medium.com/coding-corpus/concurrent-collections-in-java-9b131e41b3ad 58 | 59 | ## What is CopyOnWriteArrayList? 60 | A thread-safe variant of ArrayList in which all mutative operations (add, set, and so on) are implemented by making a fresh copy of the underlying array. 61 | ###### Relative links: 62 | + https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CopyOnWriteArrayList.html 63 | + https://medium.com/coding-corpus/concurrent-collections-in-java-9b131e41b3ad 64 | 65 | ## What can you say about ConcurrentHashMap? 66 | A hash table supporting full concurrency of retrievals and high expected concurrency for updates. This class obeys the same functional specification as Hashtable, and includes versions of methods corresponding to each method of Hashtable. However, even though all operations are thread-safe, retrieval operations do not entail locking, and there is not any support for locking the entire table in a way that prevents all access. This class is fully interoperable with Hashtable in programs that rely on its thread safety but not on its synchronization details. 67 | ###### Relative links: 68 | + https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentHashMap.html 69 | + https://habr.com/ru/post/132884/ 70 | 71 | ## What are the benefits of using ConcurrentHashMap over HashTable? 72 | ConcurrentHashMap uses multiple buckets to store data. This avoids read locks and greatly improves performance over a HashTable. Both are thread safe, but there are obvious performance wins with ConcurrentHashMap. 73 | When you read from a ConcurrentHashMap using get(), there are no locks, contrary to the HashTable for which all operations are simply synchronized. HashTable was released in old versions of Java whereas ConcurrentHashMap is a java 5+ thing. 74 | HashMap is the best thing to use in a single threaded application. 75 | ###### Relative links: 76 | + https://stackoverflow.com/questions/12646404/concurrenthashmap-and-hashtable-in-java 77 | 78 | ## What is the synchronized access? 79 | Synchronized blocks in Java are marked with the synchronized keyword. A synchronized block in Java is synchronized on some object. All synchronized blocks synchronized on the same object can only have one thread executing inside them at the same time. All other threads attempting to enter the synchronized block are blocked until the thread inside the synchronized block exits the block. 80 | ###### Relative links: 81 | - http://tutorials.jenkov.com/java-concurrency/synchronized.html 82 | 83 | ## What is the monitor for non-static synchronized method? 84 | When synchronizing a non static method, the monitor belongs to the instance. 85 | ###### Relative links: 86 | + https://stackoverflow.com/questions/6367885/difference-between-synchronizing-a-static-method-and-a-non-static-method 87 | 88 | ## What are possible ways for synchronization threads? 89 | - Volatile; 90 | - Synchronized; 91 | - Atomic Primitives; 92 | - Locks; 93 | - Concurrent Utilities (Semaphore, CyclicBarrier, CountDownLatch, Concurrent collections). 94 | ###### Relative links: 95 | - https://proandroiddev.com/synchronization-and-thread-safety-techniques-in-java-and-kotlin-f63506370e6d 96 | 97 | ## How to wait for finish of thread? 98 | Thread has a method that does that for you join which will block until the thread has finished executing. 99 | ###### Relative links: 100 | - https://stackoverflow.com/questions/4691533/java-wait-for-thread-to-finish 101 | 102 | ## What is the result of this code? 103 | ```java 104 | public class StopThread { 105 | private static boolean stopRequested; 106 | public static void main(String[] args) 107 | throws InterruptedException { 108 | Thread backgroundThread = new Thread(new Runnable() { 109 | public void run() { 110 | int i = 0; 111 | while (!stopRequested) 112 | i++; 113 | } 114 | }); 115 | backgroundThread.start(); 116 | TimeUnit.SECONDS.sleep(1); 117 | stopRequested = true; 118 | } 119 | } 120 | ``` 121 | Ideally, the program should run for 1 second and after the “stopRequested” has become true, the “backgroundThread” should end, terminating the whole program. 122 | 123 | But if you run the above on a computer with multiple cores, you will observe that the program keeps on executing without getting terminated. The problem occurs with the write operation on the “stopRequested” variable. There is no guarantee that the change of the value in “stopRequested” variable (from the main thread) becoming visible to the “backgroundThread” that we created. As the write operation to the “stopRequested” variable to true from the main method is invisible to the “backgroundThread”, it will go into an infinite loop. 124 | 125 | As the main thread and our “backgroundThread” is running on two different cores inside the processor, the “stopRequested” will be loaded into the cache of the core that executes the “backgroundThread”. The main thread will keep the updated value of the “stopRequested” value in a cache of a different core. Since now the “stopRequested” value resides in two different caches, the updated value may not be visible to the “backgroundThread”. 126 | ###### Relative links: 127 | - https://medium.com/@kasunpdh/handling-java-memory-consistency-with-happens-before-relationship-95ddc837ab13 128 | 129 | ## Change the code for getting deadlock 130 | ```java 131 | import java.util.ArrayList; 132 | import java.util.Collections; 133 | import java.util.List; 134 | import java.util.Random; 135 | 136 | public class Deadlock { 137 | private static final Object monitor1 = new Object(); 138 | private static final Object monitor2 = new Object(); 139 | 140 | public static void main(final String[] args) throws InterruptedException { 141 | List threads = new ArrayList<>(); 142 | threads.add(new Thread(Deadlock::handler1)); 143 | threads.add(new Thread(Deadlock::handler2)); 144 | 145 | Collections.shuffle(threads); 146 | 147 | threads.get(0).start(); 148 | Thread.sleep(new Random().nextLong()); 149 | threads.get(1).start(); 150 | } 151 | 152 | private static void handler1() { 153 | synchronized (monitor1) { 154 | synchronized (monitor2) { 155 | System.out.println("Hello from handler1"); 156 | } 157 | } 158 | } 159 | 160 | private static void handler2() { 161 | synchronized (monitor2) { 162 | synchronized (monitor1) { 163 | System.out.println("Hello from handler2"); 164 | } 165 | } 166 | } 167 | } 168 | ``` 169 | Possible solution - adding delays inside synchronized blocks, the example is in module [deadlock](./deadlock). 170 | 171 | ## What is the Difference between Future and CompletableFuture 172 | ###### Relative links: 173 | - https://stackoverflow.com/questions/35329845/difference-between-completablefuture-future-and-rxjavas-observable 174 | - https://www.youtube.com/watch?v=ImtZgX1nmr8 175 | 176 | [Home Page](README.md) 177 | 178 | ## How do AtomicVariables work? 179 | Long story short: they use compare and swap algorithm. 180 | ###### Relative links: 181 | - https://www.baeldung.com/java-atomic-variables 182 | -------------------------------------------------------------------------------- /core.md: -------------------------------------------------------------------------------- 1 | # Core 2 | - [What's new in Java 8?](#whats-new-in-java-8) 3 | - [What are the memory types in Java?](#what-are-the-memory-types-in-java) 4 | - [What is java agent?](#what-is-java-agent) 5 | - [Possible Performance Tools for Java?](#possible-performance-tools-for-java) 6 | - [What is java profiler?](#what-is-java-profiler) 7 | - [What is stop the world?](#what-is-stop-the-world) 8 | - [What is the difference between int, Integer and AtomicInteger?](#what-is-the-difference-between-int-integer-and-atomicinteger) 9 | - [How i++ will work for Integer?](#how-i-will-work-for-integer) 10 | - [What can you say about interface constants?](#what-can-you-say-about-interface-constants) 11 | - [What is the contract between equals and hashcode?](#what-is-the-contract-between-equals-and-hashcode) 12 | - [What are the rules for overriding equals/hashcode methods?](#what-are-the-rules-for-overriding-equalshashcode-methods) 13 | - [Are the same fields needed for equals/hashcode implementation?](#are-the-same-fields-needed-for-equalshashcode-implementation) 14 | - [What are the purposes of inner classes?](#what-are-the-purposes-of-inner-classes) 15 | - [What is better interfaces or abstract classes?](#what-is-better-interfaces-or-abstract-classes) 16 | - [Do inner classes have access to private fields from outer class?](#do-inner-classes-have-access-to-private-fields-from-outer-class) 17 | - [What are the differences between static nested classes and non-static nested classes?](#what-are-the-differences-between-static-nested-classes-and-non-static-nested-classes) 18 | - [What are the methods of Object class?](#what-are-the-methods-of-object-class) 19 | - [What is Jmeter?](#what-is-jmeter) 20 | - [Possible Ways to Capture Java Heap Dumps?](#possible-ways-to-capture-java-heap-dumps) 21 | - [What is the result of this code:](#what-is-the-result-of-this-code) 22 | - [Are checked exceptions bad?](#are-checked-exceptions-bad) 23 | - [How var in Java 10 can be used?](#how-var-in-java-10-can-be-used) 24 | - [What is functional interface?](#what-is-functional-interface) 25 | - [Functional interfaces vs abstract classes?](#functional-interfaces-vs-abstract-classes) 26 | - [Why getters/setters?](#why-getterssetters) 27 | - [Serialization?](#serialization) 28 | - [Deserialization after changes in class? Possible issues?](#deserialization-after-changes-in-class-possible-issues) 29 | - [What is the difference between cohesion and coupling?](#what-is-the-difference-between-cohesion-and-coupling) 30 | - [@Override annotation?](#override-annotation) 31 | - [Java modifiers?](#java-modifiers) 32 | - [Exception Hierarchy?](#exception-hierarchy) 33 | - [One exception is thrown by catch block and another one is thrown from finally block, which exception will be thrown by method?](#one-exception-is-thrown-by-catch-block-and-another-one-is-thrown-from-finally-block-which-exception-will-be-thrown-by-method) 34 | - [Is it possible to serialize lambda expression?](#is-it-possible-to-serialize-lambda-expression) 35 | - [Why do Java Collections can not directly store Primitives types?](#why-do-java-collections-can-not-directly-store-primitives-types) 36 | - [How is recursion implemented in Java?](#how-is-recursion-implemented-in-java) 37 | - [Is it needed to document unchecked exceptions?](#is-it-needed-to-document-unchecked-exceptions) 38 | - [Java Date classes?](#java-date-classes) 39 | - [Why Do Local Variables Used in Lambdas Have to Be Final or Effectively Final?](#why-do-local-variables-used-in-lambdas-have-to-be-final-or-effectively-final) 40 | - [orElse() vs orElseGet() in Optional?](#orelse-vs-orelseget-in-optional) 41 | - [How to filter list of objects using Stream API without .filter()?](#how-to-filter-list-of-objects-using-stream-api-without-filter) 42 | - [What is String Pool? How do Strings get there?](#what-is-string-pool-how-do-strings-get-there) 43 | - [What is the difference between StringBuilder and StringBuffer?](#what-is-the-difference-between-stringbuilder-and-stringbuffer) 44 | - [Difference between and ?](#difference-between-superT-and-extendsT) 45 | - [How does JIT compiler work?](#how-does-jit-compiler-work) 46 | - [Mutable vs Immutable object?](#mutable-vs-immutable-object) 47 | - [Provide some examples when a finally block won't be executed in Java?](#provide-some-examples-when-a-finally-block-wont-be-executed-in-java) 48 | - [What is type erasure?](#what-is-type-erasure) 49 | 50 | ## What's new in Java 8? 51 | + Lambda expressions, Method Reference , Optional, Streams added. 52 | + Advanced Date , Time, Zone and Calendar Classes introduced. 53 | + PermGen Removed. 54 | ###### Relative links: 55 | + https://codete.com/blog/java-8-java-11-quick-guide/ 56 | + https://www.quora.com/What-are-the-differences-between-Java-8-9-10-and-11 57 | 58 | ## What are the memory types in Java? 59 | + ***Stack.*** Stack memory is responsible for holding references to heap objects and for storing value types (also known in Java as primitive types), which hold the value itself rather than a reference to an object from the heap. 60 | + ***Heap.*** This part of memory stores the actual object in memory. Those are referenced by the variables from the stack. 61 | ###### Relative links: 62 | + https://dzone.com/articles/java-memory-management 63 | 64 | ## What is java agent? 65 | Java agents are able to “intrude” into the execution of Java applications running on the JVM at runtime by performing the direct modifications of the bytecode. Java agents are extremely as powerful as dangerous: they can do mostly everything however if something goes wrong, they can easily crash the JVM. 66 | ###### Relative links: 67 | + https://www.javacodegeeks.com/2015/09/java-agents.html 68 | + https://javabeat.net/introduction-to-java-agents/ 69 | + https://docs.oracle.com/javase/7/docs/api/java/lang/instrument/package-summary.html 70 | 71 | ## Possible Performance Tools for Java? 72 | + Java Profilers 73 | + Tracing Java Web Requests and Transactions 74 | + Java Application Performance Management (APM) 75 | + Real User Monitoring (RUM) 76 | + JVM Performance Metrics 77 | + Web Server (Apache/Nginx) Access Logs 78 | + Tracking All Java Exceptions 79 | + Memory Analysis 80 | ###### Relative links: 81 | + https://stackify.com/java-performance-tools-8-types-tools-need-know/ 82 | 83 | ## What is java profiler? 84 | A Java Profiler is a tool that monitors Java bytecode constructs and operations at the JVM level. These code constructs and operations include object creation, iterative executions (including recursive calls), method executions, thread executions, and garbage collections. 85 | ###### Relative links: 86 | + https://www.baeldung.com/java-profilers 87 | 88 | ## What is stop the world? 89 | Stop-the-world will occur no matter which GC algorithm you choose. Stop-the-world means that the JVM is stopping the application from running to execute a GC. When stop-the-world occurs, every thread except for the threads needed for the GC will stop their tasks. The interrupted tasks will resume only after the GC task has completed. GC tuning often means reducing this stop-the-world time. 90 | ###### Relative links: 91 | + https://www.cubrid.org/blog/understanding-java-garbage-collection 92 | + https://stackoverflow.com/questions/16695874/why-does-the-jvm-full-gc-need-to-stop-the-world 93 | 94 | ## What is the difference between int, Integer and AtomicInteger? 95 | + ***int*** is a primitive type. Variables of type int store the actual binary value for the integer you want to represent. int.parseInt("1") doesn't make sense because int is not a class and therefore doesn't have any methods. 96 | + ***Integer*** is a class, no different from any other in the Java language. Variables of type Integer store references to Integer objects, just as with any other reference (object) type. Integer.parseInt("1") is a call to the static method parseInt from class Integer (note that this method actually returns an int and not an Integer). To be more specific, Integer is a class with a single field of type int. This class is used where you need an int to be treated like any other object, such as in generic types or situations where you need nullability. 97 | + ***AtomicInteger*** is used in multithreaded environments when you need to make sure that only one thread can update an int variable. The advantage is that no external synchronization is requried since the operations which modify it's value are executed in a thread-safe way. 98 | ###### Relative links: 99 | + https://stackoverflow.com/questions/8660691/what-is-the-difference-between-integer-and-int-in-java 100 | + https://stackoverflow.com/questions/38846976/what-is-the-difference-between-atomic-integer-and-normal-immutable-integer-class 101 | 102 | ## How i++ will work for Integer? 103 | variable will be changed 104 | ###### Relative links: 105 | + https://stackoverflow.com/questions/13280134/why-does-post-increment-work-on-wrapper-classes 106 | 107 | ## What can you say about interface constants? 108 | The constant interface pattern is a poor use of interfaces. That a class uses some constants internally is an implementation detail. Implementing a constant interface causes this implementation detail to leak into the class's exported API. It is of no consequence to the users of a class that the class implements a constant interface. In fact, it may even confuse them. Worse, it represents a commitment: if in a future release the class is modified so that it no longer needs to use the constants, it still must implement the interface to ensure binary compatibility. If a nonfinal class implements a constant interface, all of its subclasses will have their namespaces polluted by the constants in the interface. There are several constant interfaces in the java platform libraries, such as java.io.ObjectStreamConstants. These interfaces should be regarded as anomalies and should not be emulated. 109 | ###### Relative links: 110 | + https://stackoverflow.com/questions/2659593/what-is-the-use-of-interface-constants 111 | 112 | ## What is the contract between equals and hashcode? 113 | objects which are .equals() MUST have the same .hashCode(). 114 | ###### Relative links: 115 | + https://stackoverflow.com/questions/17027777/relationship-between-hashcode-and-equals-method-in-java 116 | 117 | ## What are the rules for overriding equals/hashcode methods? 118 | + Always use same attributes of an object to generate hashCode() and equals() both. 119 | + equals() must be consistent (if the objects are not modified, then it must keep returning the same value). 120 | + Whenever a.equals(b), then a.hashCode() must be same as b.hashCode(). 121 | + If you override one, then you should override the other. 122 | ###### Relative links: 123 | + https://howtodoinjava.com/java/basics/java-hashcode-equals-methods/ 124 | 125 | ## Are the same fields needed for equals/hashcode implementation? 126 | The fields don't have to be the same. The requirement is for two objects that are equal, they must have the same hash code. If they have the same hash code, they don't have to be equal. For example, you could return 1 as your hash code always, and you would obey the hash code contract, no matter what fields you used in your equals method. Returning 1 all the time would improve the computation time of hashCode, but HashMap's performance would drop since it would have to resort to equals() more often. 127 | ###### Relative links: 128 | + https://stackoverflow.com/questions/22827652/different-fields-for-equals-and-hashcode 129 | 130 | ## What are the purposes of inner classes? 131 | + It is a way of logically grouping classes that are only used in one place. 132 | + It increases encapsulation. 133 | + It can lead to more readable and maintainable code. 134 | ###### Relative links: 135 | + https://stackoverflow.com/questions/11398122/what-are-the-purposes-of-inner-classes 136 | + https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html 137 | 138 | ## What is better interfaces or abstract classes? 139 | Use abstract classes when you have a class that A is kind of B and interface when A can do B. 140 | + A class can implement multiple interfaces, but it can only extend one abstract class. 141 | + Interfaces allow the creation of proxies that encapsulate a concrete class. This is used extensively by frameworks in order to intercept method calls to the concrete class (e.g., for starting a transaction before the method is executed or to write to the log). 142 | ###### Relative links: 143 | + https://stackoverflow.com/questions/2971265/situation-where-interface-is-better-than-abstract-class 144 | + https://stackoverflow.com/questions/11889588/choosing-interface-or-abstract-class 145 | 146 | ## Do inner classes have access to private fields from outer class? 147 | Inner classes has access to private fields from outer class. 148 | ###### Relative links: 149 | + https://www.geeksforgeeks.org/nested-classes-java/ 150 | 151 | ## What are the differences between static nested classes and non-static nested classes? 152 | + Static nested classes do not directly have access to other members(non-static variables and methods) of the enclosing class because as it is static, it must access the non-static members of its enclosing class through an object. That is, it cannot refer to non-static members of its enclosing class directly. Because of this restriction, static nested classes are seldom used. 153 | + Non-static nested classes (inner classes) has access to all members(static and non-static variables and methods, including private) of its outer class and may refer to them directly in the same way that other non-static members of the outer class do. 154 | ###### Relative links: 155 | + https://www.geeksforgeeks.org/nested-classes-java/ 156 | + https://stackoverflow.com/questions/253492/static-nested-class-in-java-why 157 | 158 | ## What are the methods of Object class? 159 | toString(), hashCode(), equals(Object obj), getClass(), finalize(), clone(), wait(), notify() notifyAll() 160 | ###### Relative links: 161 | + https://www.geeksforgeeks.org/object-class-in-java/ 162 | 163 | ## What is Jmeter? 164 | Apache JMeter is an open source, Java-based, load testing tool that can be used to analyze the functional behavior of a system and measure the performance of a system under a load test. A load test will simulate end-user behavior that approach the limits of an application’s specifications. Apache JMeter can be used to simulate varying or heavy loads on singular or multiple servers, networks or objects to test a system’s strength. 165 | ###### Relative links: 166 | + https://searchsoftwarequality.techtarget.com/definition/Apache-JMeter 167 | 168 | ## Possible Ways to Capture Java Heap Dumps? 169 | Possible options from the link. 170 | ###### Relative links: 171 | + https://www.baeldung.com/java-heap-dump-capture 172 | 173 | ## What is the result of this code: 174 | ```java 175 | public static void main(String[] args) { 176 | Point pnt1 = new Point(0, 0); 177 | Point pnt2 = new Point(0, 0); 178 | System.out.println("X: " + pnt1.x + " Y: " + pnt1.y); 179 | System.out.println("X: " + pnt2.x + " Y: " + pnt2.y); 180 | System.out.println(" "); 181 | tricky(pnt1, pnt2); 182 | System.out.println("X: " + pnt1.x + " Y:" + pnt1.y); 183 | System.out.println("X: " + pnt2.x + " Y: " + pnt2.y); 184 | } 185 | 186 | public void tricky(Point arg1, Point arg2) { 187 | arg1.x = 100; 188 | arg1.y = 100; 189 | Point temp = arg1; 190 | arg1 = arg2; 191 | arg2 = temp; 192 | } 193 | ``` 194 | 195 | If we execute this main() method, we see the following output: 196 | ``` 197 | X: 0 Y: 0 198 | X: 0 Y: 0 199 | X: 100 Y: 100 200 | X: 0 Y: 0 201 | ``` 202 | The method successfully alters the value of pnt1, even though it is passed by value; however, a swap of pnt1 and pnt2 fails! This is the major source of confusion. In the main() method, pnt1 and pnt2 are nothing more than object references. When you pass pnt1 and pnt2 to the tricky() method, Java passes the references by value just like any other parameter. This means the references passed to the method are actually copies of the original references. 203 | ###### Relative links: 204 | - https://www.javaworld.com/article/2077424/learn-java-does-java-pass-by-reference-or-pass-by-value.html 205 | 206 | ## Are checked exceptions bad? 207 | ###### Relative links: 208 | - https://www.javaworld.com/article/3142626/are-checked-exceptions-good-or-bad.html 209 | - https://www.yegor256.com/2015/07/28/checked-vs-unchecked-exceptions.html 210 | - https://medium.com/@eob/checked-exceptions-considered-evil-f7d07e051fa6 211 | 212 | ## How var in Java 10 can be used? 213 | ###### Relative links: 214 | - https://dzone.com/articles/finally-java-10-has-var-to-declare-local-variables 215 | 216 | ## What is functional interface? 217 | ###### Relative links: 218 | - https://www.geeksforgeeks.org/functional-interfaces-java/ 219 | 220 | ## Functional interfaces vs abstract classes? 221 | ###### Relative links: 222 | - https://stackoverflow.com/questions/19998454/interface-with-default-methods-vs-abstract-class-in-java-8 223 | 224 | ## Why getters/setters? 225 | ###### Relative links: 226 | - https://stackoverflow.com/questions/1568091/why-use-getters-and-setters-accessors 227 | 228 | ## Serialization? 229 | ###### Relative links: 230 | - https://dev.to/njnareshjoshi/what-is-serialization-everything-you-need-to-know-about-java-serialization-explained-with-example-9mj 231 | 232 | ## Deserialization after changes in class? Possible issues? 233 | ###### Relative links: 234 | - https://howtodoinjava.com/java/serialization/a-mini-guide-for-implementing-serializable-interface-in-java/ 235 | 236 | ## What is the difference between cohesion and coupling? 237 | ###### Relative links: 238 | - https://stackoverflow.com/questions/3085285/difference-between-cohesion-and-coupling 239 | 240 | ## @Override annotation? 241 | ###### Relative links: 242 | - https://www.tutorialspoint.com/importance-of-override-annotation-in-java 243 | 244 | ## Java modifiers? 245 | ###### Relative links: 246 | - https://www.tutorialspoint.com/java/java_modifier_types.htm 247 | 248 | ## Exception Hierarchy? 249 | ###### Relative links: 250 | - https://www.geeksforgeeks.org/exceptions-in-java/ 251 | 252 | ## One exception is thrown by catch block and another one is thrown from finally block, which exception will be thrown by method? 253 | ###### Relative links: 254 | - https://stackoverflow.com/questions/3779285/exception-thrown-in-catch-and-finally-clause 255 | 256 | ## Is it possible to serialize lambda expression? 257 | ###### Relative links: 258 | - https://stackoverflow.com/questions/22807912/how-to-serialize-a-lambda 259 | 260 | ## Why do Java Collections can not directly store Primitives types? 261 | It's a combination of two facts: 262 | + Java primitive types are not reference types (e.g. an int is not an Object) 263 | + Java does generics using type-erasure of reference types (e.g. a `List` is really a `List` at run-time) 264 | ###### Relative links: 265 | + https://stackoverflow.com/questions/2504959/why-can-java-collections-not-directly-store-primitives-types 266 | 267 | ## How is recursion implemented in Java? 268 | ###### Relative links: 269 | - https://freecontent.manning.com/stack-safe-recursion-in-java/ 270 | 271 | ## Is it needed to document unchecked exceptions? 272 | ###### Relative links: 273 | - https://books.google.by/books?id=ka2VUBqHiWkC&pg=PA252&lpg=PA252&dq=java+is+it+needed+document+unchecked+exceptions&source=bl&ots=y_KhOeo_M3&sig=ACfU3U0TpATCoEC62Irm3SaPj6tMWDnZLQ&hl=en&sa=X&ved=2ahUKEwiS7_vG4OvnAhXF8qQKHeniBtIQ6AEwD3oECAkQAQ#v=onepage&q&f=false 274 | 275 | ## Java Date classes? 276 | ###### Relative links: 277 | - https://www.baeldung.com/java-8-date-time-intro 278 | 279 | ## Why Do Local Variables Used in Lambdas Have to Be Final or Effectively Final? 280 | ###### Relative links: 281 | - https://www.baeldung.com/java-lambda-effectively-final-local-variables 282 | 283 | ## orElse() vs orElseGet() in Optional? 284 | ###### Relative links: 285 | - https://www.baeldung.com/java-optional-or-else-vs-or-else-get 286 | 287 | ## How to filter list of objects using Stream API without .filter()? 288 | ```java 289 | public static void main(String[] args) { 290 | 291 | final List list = Arrays.asList(Person.builder().setAge(25).build(), Person.builder().setAge(10).build(), 292 | Person.builder().setAge(15).build(), Person.builder().setAge(21).build()); 293 | 294 | list.stream() 295 | .flatMap(person -> person.getAge() < 18 ? Stream.of(person) : Stream.empty()) 296 | .forEach(person -> System.out.println(person.getAge())); 297 | } 298 | ``` 299 | 300 | ## What is String Pool? How do Strings get there? 301 | String pool is the special memory region where Strings are stored by the JVM. 302 | ###### Relative links: 303 | - https://www.baeldung.com/java-string-pool 304 | 305 | ## What is the difference between StringBuilder and StringBuffer? 306 | All public methods of StringBuffer are synchronized, it provides Thread safety but on a performance cost. 307 | 308 | ## Difference between and ? 309 | ###### Relative links: 310 | - https://stackoverflow.com/questions/4343202/difference-between-super-t-and-extends-t-in-java 311 | 312 | ## How does JIT compiler work? 313 | ###### Relative links: 314 | - https://aboullaite.me/understanding-jit-compiler-just-in-time-compiler/ 315 | 316 | ## Mutable vs Immutable object? 317 | ###### Relative links: 318 | - https://www.interviewcake.com/concept/java/mutable#:~:text=A%20mutable%20object%20can%20be,an%20immutable%20object%20can't.&text=That%20said%2C%20if%20you're,all%20fields%20final%20and%20private.&text=Strings%20are%20immutable%20in%20Java. 319 | - https://www.edureka.co/blog/java-mutable-and-immutable-objects/ 320 | 321 | ## Provide some examples when a finally block won't be executed in Java? 322 | If the JVM exits while the try or catch code is being executed, then the finally block may not execute. Likewise, if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues. 323 | ###### Relative links: 324 | - https://stackoverflow.com/questions/2417958/is-there-possibility-that-a-finally-block-might-not-execute 325 | 326 | ## What is type erasure? 327 | Type erasure removes all type parameters and replaces them with their bounds or with Object if the type parameter is unbounded. This way, the bytecode after compilation contains only normal classes, interfaces and methods, ensuring that no new types are produced. Proper casting is applied as well to the Object type at compile time. 328 | ###### Relative links: 329 | - https://www.baeldung.com/java-generics 330 | 331 | ## What is built-in mechanism for creating singletons in Java? 332 | Java enum 333 | ###### Relative links: 334 | - https://dzone.com/articles/java-singletons-using-enum 335 | 336 | ## How to understand a third-party library without source code? 337 | One way to understand how a third-party library works without its source code is by using a **decompiler**. A decompiler converts the compiled bytecode (e.g., `.class` files in Java) back into readable source code. 338 | 339 | [Home Page](README.md) 340 | -------------------------------------------------------------------------------- /custom-stream/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | } 4 | 5 | group 'custom-stream' 6 | version '1.0-SNAPSHOT' 7 | 8 | sourceCompatibility = 1.8 9 | 10 | repositories { 11 | mavenCentral() 12 | } 13 | 14 | dependencies { 15 | testCompile group: 'junit', name: 'junit', version: '4.12' 16 | } 17 | -------------------------------------------------------------------------------- /custom-stream/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anton-liauchuk/java-interview/c12fb26b7aa8f16b5ba39fa9b8c38c626f99a696/custom-stream/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /custom-stream/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.10.3-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /custom-stream/gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /custom-stream/gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /custom-stream/src/main/java/ReferencePipeline.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.List; 3 | import java.util.Objects; 4 | import java.util.function.Function; 5 | import java.util.function.Predicate; 6 | 7 | /** 8 | * Custom reference pipeline implementation with basic functions. 9 | * The original class is {@link java.util.stream.ReferencePipeline} 10 | */ 11 | public class ReferencePipeline implements Stream { 12 | 13 | ReferencePipeline previousStage; 14 | 15 | private List objects; 16 | 17 | private ReferencePipeline(List objects) { 18 | this.objects = objects; 19 | } 20 | 21 | ReferencePipeline() { 22 | } 23 | 24 | public Sink opWrapSink(Sink sink) { 25 | throw new UnsupportedOperationException(); 26 | } 27 | 28 | public static ReferencePipeline of(List objects) { 29 | return new ReferencePipeline(objects); 30 | } 31 | 32 | public Stream filter(Predicate predicate) { 33 | return new Operation(this) { 34 | @Override 35 | public Sink opWrapSink(Sink sink) { 36 | return new ChainedReference(sink) { 37 | 38 | @Override 39 | public void accept(Object o) { 40 | if (predicate.test((StreamObject) o)) 41 | downstream.accept(o); 42 | } 43 | }; 44 | } 45 | }; 46 | } 47 | 48 | public Stream map(Function function) { 49 | return new Operation(this) { 50 | @Override 51 | public Sink opWrapSink(Sink sink) { 52 | return new ChainedReference(sink) { 53 | 54 | @Override 55 | public void accept(Object o) { 56 | downstream.accept(function.apply(o)); 57 | } 58 | }; 59 | } 60 | }; 61 | } 62 | 63 | public List toList() { 64 | final List result = new ArrayList<>(); 65 | 66 | Sink finalSink = o -> result.add(o); 67 | 68 | ReferencePipeline previousStage = this; 69 | Sink sink = finalSink; 70 | 71 | while (previousStage.previousStage != null) { 72 | sink = previousStage.opWrapSink(sink); 73 | previousStage = previousStage.previousStage; 74 | } 75 | 76 | for (StreamObject object : previousStage.objects) { 77 | sink.accept(object); 78 | } 79 | 80 | return result; 81 | } 82 | 83 | /** 84 | * Represents Operation which has the info about previous stage. 85 | */ 86 | abstract class Operation extends ReferencePipeline { 87 | 88 | Operation(ReferencePipeline previousStage) { 89 | this.previousStage = previousStage; 90 | } 91 | } 92 | 93 | /** 94 | * Represents Chained Reference which has the link to downstream. 95 | */ 96 | abstract class ChainedReference implements Sink { 97 | final Sink downstream; 98 | 99 | ChainedReference(Sink downstream) { 100 | this.downstream = Objects.requireNonNull(downstream); 101 | } 102 | } 103 | 104 | } 105 | -------------------------------------------------------------------------------- /custom-stream/src/main/java/Sink.java: -------------------------------------------------------------------------------- 1 | import java.util.function.Consumer; 2 | 3 | interface Sink extends Consumer { 4 | 5 | } 6 | -------------------------------------------------------------------------------- /custom-stream/src/main/java/Stream.java: -------------------------------------------------------------------------------- 1 | import java.util.List; 2 | import java.util.function.Function; 3 | import java.util.function.Predicate; 4 | 5 | /** 6 | * Custom Stream interface with basic functions. 7 | * Original class is {@link java.util.stream.Stream} 8 | */ 9 | interface Stream { 10 | 11 | /** 12 | * Original method is {@link java.util.stream.Stream#filter(Predicate)} 13 | */ 14 | Stream filter(Predicate predicate); 15 | 16 | /** 17 | * Original method is {@link java.util.stream.Stream#map(Function)} 18 | */ 19 | Stream map(Function function); 20 | 21 | /** 22 | * Terminal operation which returns the list. 23 | */ 24 | List toList(); 25 | } -------------------------------------------------------------------------------- /custom-stream/src/main/java/StreamObject.java: -------------------------------------------------------------------------------- 1 | public class StreamObject { 2 | 3 | private int id; 4 | private String name; 5 | 6 | public int getId() { 7 | return id; 8 | } 9 | 10 | public void setId(int id) { 11 | this.id = id; 12 | } 13 | 14 | public String getName() { 15 | return name; 16 | } 17 | 18 | public void setName(String name) { 19 | this.name = name; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /custom-stream/src/test/java/StreamTest.java: -------------------------------------------------------------------------------- 1 | import org.junit.Test; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | import java.util.stream.Collectors; 6 | 7 | public class StreamTest { 8 | 9 | @Test 10 | public void debugStream() { 11 | StreamObject object0 = new StreamObject(); 12 | object0.setId(0); 13 | object0.setName("0"); 14 | 15 | StreamObject object1 = new StreamObject(); 16 | object1.setId(1); 17 | object1.setName("1"); 18 | 19 | List collection = Arrays.asList(object0, object1); 20 | // final List collect = collection.stream() 21 | // .filter(streamObject -> streamObject.getId() == 0) 22 | // .map(StreamObject::getId) 23 | // .collect(Collectors.toList()); 24 | 25 | ReferencePipeline.of(collection) 26 | .filter(streamObject -> streamObject.getId() == 0) 27 | .map(StreamObject::getId) 28 | .toList(); 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /ddd.md: -------------------------------------------------------------------------------- 1 | # DDD 2 | - [What is DDD?](#what-is-ddd) 3 | - [Why DDD is needed?](#why-ddd-is-needed) 4 | - [What is aggregate in DDD?](#what-is-aggregate-in-ddd) 5 | - [What is anemic domain model?](#what-is-anemic-domain-model) 6 | - [What is the correct way for having relations between aggregates?](#what-is-the-correct-way-for-having-relations-between-aggregates) 7 | - [How to update several aggregates during one transaction?](#how-to-update-several-aggregates-during-one-transaction) 8 | - [What is event storming?](#what-is-event-storming) 9 | - [How domain events are related to eventual consistency?](#how-domain-events-are-related-to-eventual-consistency) 10 | - [What is the difference between domain events and event sourcing?](#what-is-the-difference-between-domain-events-and-event-sourcing) 11 | - [What is CQRS?](#what-is-cqrs) 12 | - [What is the best practice for validation in DDD?](#what-is-the-best-practice-for-validation-in-ddd) 13 | - [What is the best practice for Value Object?](#what-is-the-best-practice-for-value-object) 14 | - [Possible issues with using domain model with public getters/setters and empty constructor?](#possible-issues-with-using-domain-model-with-public-getterssetters-and-empty-constructor) 15 | - [How to work with large domain models? Is it correct to have a lot of fields in domain model?](#how-to-work-with-large-domain-models-is-it-correct-to-have-a-lot-of-fields-in-domain-model) 16 | - [How should be published integration events? Inside or outside transaction?](#how-should-be-published-integration-events-inside-or-outside-transaction) 17 | - [How to define the reference between aggregates?](#how-to-define-the-reference-between-aggregates) 18 | - [Where to put validation rule for value object?](#where-to-put-validation-rule-for-value-object) 19 | - [Possible integration ways between modules?](#possible-integration-ways-between-modules) 20 | 21 | ## What is DDD? 22 | ###### Relative links: 23 | - https://vaadin.com/learn/tutorials/ddd/strategic_domain_driven_design 24 | - https://vaadin.com/learn/tutorials/ddd/tactical_domain_driven_design 25 | - https://vaadin.com/learn/tutorials/ddd/ddd_and_hexagonal 26 | - https://github.com/peholmst/DDDExample 27 | 28 | ## Why DDD is needed? 29 | ###### Relative links: 30 | - https://simpleprogrammer.com/importance-domain-driven-design/ 31 | 32 | ## What is aggregate in DDD? 33 | ###### Relative links: 34 | - https://martinfowler.com/bliki/DDD_Aggregate.html 35 | 36 | ## What is anemic domain model? 37 | ###### Relative links: 38 | - https://martinfowler.com/bliki/AnemicDomainModel.html 39 | - https://thedomaindrivendesign.io/anemic-model/ 40 | 41 | ## What is the correct way for having relations between aggregates? 42 | ###### Relative links: 43 | - https://vaadin.com/learn/tutorials/ddd/tactical_domain_driven_design 44 | 45 | ## How to update several aggregates during one transaction? 46 | ###### Relative links: 47 | - https://docs.microsoft.com/en-us/dotnet/architecture/microservices/microservice-ddd-cqrs-patterns/domain-events-design-implementation 48 | 49 | ## What is event storming? 50 | ###### Relative links: 51 | - https://philippe.bourgau.net/how-to-use-event-storming-to-introduce-domain-driven-design/ 52 | - https://github.com/mariuszgil/awesome-eventstorming 53 | 54 | ## How domain events are related to eventual consistency? 55 | ###### Relative links: 56 | - https://www.infoq.com/news/2015/09/domain-events-consistency/ 57 | 58 | ## What is the difference between domain events and event sourcing? 59 | ###### Relative links: 60 | - https://www.innoq.com/en/blog/domain-events-versus-event-sourcing/ 61 | 62 | ## What is CQRS? 63 | ###### Relative links: 64 | - https://docs.microsoft.com/en-us/azure/architecture/patterns/cqrs 65 | - https://www.kamilgrzybek.com/design/simple-cqrs-implementation-with-raw-sql-and-ddd/ 66 | - https://dzone.com/articles/cqrs-understanding-from-first-principles 67 | - https://stackoverflow.com/questions/24474859/what-is-the-difference-between-command-commandhandler-and-service 68 | 69 | 70 | ## What is the best practice for validation in DDD? 71 | ###### Relative links: 72 | - https://docs.microsoft.com/en-us/dotnet/architecture/microservices/microservice-ddd-cqrs-patterns/domain-model-layer-validations 73 | - http://gorodinski.com/blog/2012/05/19/validation-in-domain-driven-design-ddd/ 74 | - https://enterprisecraftsmanship.com/posts/always-valid-vs-not-always-valid-domain-model/ 75 | - https://enterprisecraftsmanship.com/posts/validation-and-ddd/ 76 | - https://danielwhittaker.me/2016/04/20/how-to-validate-commands-in-a-cqrs-application/ 77 | - https://enterprisecraftsmanship.com/posts/validate-commands-cqrs/ 78 | - http://www.kamilgrzybek.com/design/domain-model-validation/ 79 | - http://www.kamilgrzybek.com/design/rest-api-data-validation/ 80 | 81 | ## What is the best practice for Value Object? 82 | ###### Relative links: 83 | - https://dzone.com/articles/value-objects 84 | 85 | ## Possible issues with using domain model with public getters/setters and empty constructor? 86 | ###### Relative links: 87 | - https://thedomaindrivendesign.io/anemic-model/ 88 | 89 | ## How to work with large domain models? Is it correct to have a lot of fields in domain model? 90 | ###### Relative links: 91 | - https://martinfowler.com/bliki/BoundedContext.html 92 | 93 | ## How should be published integration events? Inside or outside transaction? 94 | ###### Relative links: 95 | - https://devblogs.microsoft.com/cesardelatorre/domain-events-vs-integration-events-in-domain-driven-design-and-microservices-architectures/ 96 | 97 | ## How to define the reference between aggregates? 98 | ###### Relative links: 99 | - https://www.informit.com/articles/article.aspx?p=2020371&seqNum=4 100 | 101 | ## Where to put validation rule for value object? 102 | ###### Relative links: 103 | - https://builtwithdot.net/blog/where-do-i-put-my-business-rules-and-validation 104 | 105 | ## Possible integration ways between modules? 106 | ###### Relative links: 107 | - https://www.kamilgrzybek.com/design/modular-monolith-integration-styles/ 108 | -------------------------------------------------------------------------------- /deadlock/src/Deadlock.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.Collections; 3 | import java.util.List; 4 | 5 | public class Deadlock { 6 | private static final Object monitor1 = new Object(); 7 | private static final Object monitor2 = new Object(); 8 | 9 | public static void main(final String[] args) throws InterruptedException { 10 | List threads = new ArrayList<>(); 11 | threads.add(new Thread(Deadlock::handler1)); 12 | threads.add(new Thread(Deadlock::handler2)); 13 | 14 | Collections.shuffle(threads); 15 | 16 | threads.get(0).start(); 17 | Thread.sleep(1000); 18 | threads.get(1).start(); 19 | } 20 | 21 | private static void handler1() { 22 | synchronized (monitor1) { 23 | try { 24 | Thread.sleep(3000); 25 | } catch (InterruptedException e) { 26 | e.printStackTrace(); 27 | } 28 | synchronized (monitor2) { 29 | System.out.println("Hello from handler1"); 30 | } 31 | } 32 | } 33 | 34 | private static void handler2() { 35 | synchronized (monitor2) { 36 | try { 37 | Thread.sleep(3000); 38 | } catch (InterruptedException e) { 39 | e.printStackTrace(); 40 | } 41 | synchronized (monitor1) { 42 | System.out.println("Hello from handler2"); 43 | } 44 | } 45 | } 46 | } -------------------------------------------------------------------------------- /git.md: -------------------------------------------------------------------------------- 1 | # Git 2 | - [What is the difference between merge and rebase?](#what-is-the-difference-between-merge-and-rebase) 3 | - [What is git reset?](#what-is-git-reset) 4 | - [What is the difference between soft reset and hard reset?](#what-is-the-difference-between-soft-reset-and-hard-reset) 5 | - [How to combine multiple commits into one prior to push?](#how-to-combine-multiple-commits-into-one-prior-to-push) 6 | 7 | ## What is the difference between merge and rebase? 8 | - Both commits D and E are still here, but we create merge commit M that inherits changes from both D and E. However, this creates diamond shape, which many people find very confusing. 9 | - We create commit R, which actual file content is identical to that of merge commit M above. But, we get rid of commit E, like it never existed (denoted by dots - vanishing line). Because of this obliteration, E should be local to developer Ed and should have never been pushed to any other repository. 10 | ###### Relative links: 11 | - https://stackoverflow.com/questions/16666089/whats-the-difference-between-git-merge-and-git-rebase 12 | 13 | ## What is git reset? 14 | ***git-reset*** - Reset current HEAD to the specified state 15 | ###### Relative links: 16 | - https://git-scm.com/docs/git-reset 17 | - https://www.atlassian.com/git/tutorials/undoing-changes/git-reset 18 | 19 | ## What is the difference between soft reset and hard reset? 20 | - ***soft***: uncommit changes, changes are left staged (index). 21 | - ***mixed (default)***: uncommit + unstage changes, changes are left in working tree. 22 | - ***hard***: uncommit + unstage + delete changes, nothing left. 23 | ###### Relative links: 24 | - https://stackoverflow.com/questions/3528245/whats-the-difference-between-git-reset-mixed-soft-and-hard 25 | 26 | ## How to combine multiple commits into one prior to push? 27 | ###### Relative links: 28 | - https://www.internalpointers.com/post/squash-commits-into-one-git 29 | 30 | [Home Page](README.md) 31 | -------------------------------------------------------------------------------- /graalvm.md: -------------------------------------------------------------------------------- 1 | # GraalVM 2 | - [What is GraalVM Native Image?](#what-is-graalvm-native-image) 3 | 4 | ## What is GraalVM Native Image? 5 | **GraalVM Native Image** allows you to ahead-of-time compile Java code to a standalone executable, called a **native image**. This executable includes the application classes, classes from its dependencies, runtime library classes from JDK and statically linked native code from JDK. It does not run on the Java VM, but includes necessary components like memory management and thread scheduling from a different virtual machine, called “Substrate VM”. Substrate VM is the name for the runtime components (like the deoptimizer, garbage collector, thread scheduling etc.). The resulting program has faster startup time and lower runtime memory overhead compared to a Java VM. 6 | ###### Relative links: 7 | - https://www.graalvm.org/docs/reference-manual/native-image/ 8 | 9 | [Home Page](README.md) 10 | -------------------------------------------------------------------------------- /gradle.md: -------------------------------------------------------------------------------- 1 | # Gradle 2 | - [What is the difference between `api` and `implementation`?](#what-is-the-difference-between-api-and-implementation) 3 | 4 | ## What is the difference between `api` and `implementation`? 5 | ###### Relative links: 6 | - https://docs.gradle.org/current/userguide/java_library_plugin.html#sec:java_library_separation 7 | -------------------------------------------------------------------------------- /hibernate.md: -------------------------------------------------------------------------------- 1 | # Hibernate 2 | - [What is detached entity?](#what-is-detached-entity) 3 | - [What is the use of flush?](#what-is-the-use-of-flush) 4 | - [What are the cache levels?](#what-are-the-cache-levels) 5 | - [What is the first-level cache?](#what-is-the-first-level-cache) 6 | - [Hibernate inheritance?](#hibernate-inheritance) 7 | - [Common hibernate mistakes?](#common-hibernate-mistakes) 8 | - [Hibernate best practice?](#hibernate-best-practice) 9 | - [How to Define and Use a @NamedEntityGraph?](#how-to-define-and-use-a-namedentitygraph) 10 | - [Possible issues with defining equals/hashcode on JPA entities?](#possible-issues-with-defining-equalshashcode-on-jpa-entities) 11 | - [How lazy loading works in hibernate?](#how-lazy-loading-works-in-hibernate) 12 | - [Optimal queries in Hibernate?](#optimal-queries-in-hibernate) 13 | - [Possible enum mapping solutions?](#possible-enum-mapping-solutions) 14 | - [In which cases LazyInitializationException can occur?](#in-which-cases-lazyinizializtion-can-occur) 15 | - [There are three SQL statements in one transaction, during the first one exception occurred on DB level, what will happen with others if you catch the first one?](#there-are-three-sql-statements-in-one-transaction-during-the-first-one-exception-occurred-on-db-level-what-will-happen-with-others-if-you-catch-the-first-one) 16 | 17 | ## What is detached entity? 18 | - A `new` instance of a persistent class which is not associated with a `Session`, has no representation in the database and no identifier value is considered ***transient*** by Hibernate. 19 | - A ***persistent*** instance has a representation in the database, an identifier value and is associated with a `Session`. You can make a transient instance ***persistent*** by associating it with a `Session`. 20 | - If we `close` the Hibernate `Session`, the persistent instance will become a ***detached*** instance: it isn't attached to a `Session` anymore (but can still be modified and reattached to a new `Session` later though). 21 | ###### Relative links: 22 | + https://stackoverflow.com/questions/2573739/what-are-detached-persistent-and-transient-objects-in-hibernate 23 | 24 | ## What is the use of flush? 25 | Flushing the session forces Hibernate to synchronize the in-memory state of the Session with the database (i.e. to write changes to the database). By default, Hibernate will flush changes automatically for you: 26 | - before some query executions 27 | - when a transaction is committed 28 | 29 | Allowing to explicitly flush the Session gives finer control that may be required in some circumstances (to get an ID assigned, to control the size of the Session,...). 30 | ###### Relative links: 31 | + https://stackoverflow.com/questions/3220336/whats-the-use-of-session-flush-in-hibernate 32 | 33 | ## What are the cache levels? 34 | + ***Session Cache.*** The session cache caches objects within the current session. It is enabled by default in Hibernate. Objects in the session cache reside in the same memory location. 35 | + ***Second Level Cache.*** The second level cache is responsible for caching objects across sessions. When this is turned on, objects will first be searched in the cache and if they are not found, a database query will be fired. Second level cache will be used when the objects are loaded using their primary key. This includes fetching of associations. Second level cache objects are constructed and reside in different memory locations. 36 | + ***Query Cache.*** Query Cache is used to cache the results of a query. 37 | ###### Relative links: 38 | + https://dzone.com/articles/all-about-hibernate-second 39 | + https://habr.com/ru/post/135176/ 40 | 41 | ## What is the first-level cache? 42 | ***Session Cache.*** The session cache caches objects within the current session. It is enabled by default in Hibernate. Read more about Session Cache . Objects in the session cache reside in the same memory location. 43 | ###### Relative links: 44 | + https://dzone.com/articles/all-about-hibernate-second 45 | + https://habr.com/ru/post/135176/ 46 | 47 | ## Hibernate inheritance? 48 | ###### Relative links: 49 | - https://www.baeldung.com/hibernate-inheritance 50 | 51 | ## Common hibernate mistakes? 52 | - When you’re defining your associations, you should prefer FetchType.LAZY and map many-to-many associations to a java.util.Set. 53 | - If your use case uses a lazily fetched association, you should initialize it within the query that loads the entity, e.g., with a JOIN FETCH expression. 54 | - Cascading and updating or removing multiple entities require more SQL statements than you might expect. It’s often better to implement a bulk operation as a native, JPQL or Criteria query. 55 | ###### Relative links: 56 | - https://thoughts-on-java.org/5-common-hibernate-mistakes-that-cause-dozens-of-unexpected-queries/ 57 | 58 | ## Hibernate best practice? 59 | ###### Relative links: 60 | - https://thoughts-on-java.org/hibernate-best-practices/ 61 | 62 | ## How to Define and Use a @NamedEntityGraph? 63 | ###### Relative links: 64 | - https://thoughts-on-java.org/jpa-21-entity-graph-part-1-named-entity/ 65 | 66 | ## Possible issues with defining equals/hashcode on JPA entities? 67 | ###### Relative links: 68 | - https://stackoverflow.com/questions/4388360/should-i-write-equals-and-hashcode-methods-in-jpa-entities 69 | - https://developer.jboss.org/wiki/EqualsandHashCode 70 | 71 | ## Scripts vs table generation from entity annotations? 72 | ###### Relative links: 73 | - https://thoughts-on-java.org/create-generate-table-model/ 74 | 75 | ## How lazy loading works in hibernate? 76 | ###### Relative links: 77 | - https://howtodoinjava.com/hibernate/lazy-loading-in-hibernate/ 78 | 79 | ## Optimal queries in Hibernate? 80 | ###### Relative links: 81 | - https://thorben-janssen.com/optimal-query-and-projection-jpa-hibernate/ 82 | 83 | ## Possible enum mapping solutions? 84 | ###### Relative links: 85 | - https://thorben-janssen.com/hibernate-enum-mappings/#standardMapping 86 | 87 | ## In which cases LazyInitializationException can occur? 88 | ###### Relative links: 89 | - https://thorben-janssen.com/lazyinitializationexception/ 90 | 91 | ## There are three SQL statements in one transaction, during the first one exception occurred on DB level, what will happen with others if you catch the first one? 92 | All Java code after Exception catching will be normally executed with other statements, but at the moment you want to try to close transaction, it won't commit any of statements, 93 | because transaction was marked as "to be rollbacked". 94 | 95 | [Home Page](README.md) 96 | -------------------------------------------------------------------------------- /javascript.md: -------------------------------------------------------------------------------- 1 | #JavaScript 2 | - [Какие есть области видимости?](#какие-есть-области-видимости) 3 | - [Что такое bind? call & apply?](#что-такое-bind-call--apply) 4 | - [Потеря контекста в js?](#потеря-контекста-в-js) 5 | - [js однопоточный или многопоточный?](#js-однопоточный-или-многопоточный) 6 | - [Что такое closure в js?](#что-такое-closure-в-js) 7 | - [Как проверить присутствует ли идентификатор в html?](#как-проверить-присутствует-ли-идентификатор-в-html) 8 | - [2 функции с одинаковам названием, но разным количеством параметров, могут ли быть проблемы?](#2-функции-с-одинаковам-названием-но-разным-количеством-параметров-могут-ли-быть-проблемы) 9 | 10 | ## What are possible variable scopes? 11 | + Local scope 12 | + Global scope 13 | ###### Relative links: 14 | + https://www.w3schools.com/js/js_scope.asp 15 | 16 | ## What is bind? call & apply? 17 | call()/apply() to invoke the function immediately. bind() returns a bound function that, when executed later, will have the correct context ("this") for calling the original function. So bind() can be used when the function needs to be called later in certain events when it's useful. 18 | ###### Relative links: 19 | + https://www.codementor.io/niladrisekhardutta/how-to-call-apply-and-bind-in-javascript-8i1jca6jp 20 | 21 | ## What is losing of context in js? 22 | this is set primarily by how the function is called, not where it's defined. 23 | ###### Relative links: 24 | + https://stackoverflow.com/questions/30486345/losing-this-context-in-javascript-when-passing-around-members 25 | + https://ru.stackoverflow.com/questions/535030/%D0%9F%D0%BE%D1%82%D0%B5%D1%80%D1%8F-%D0%BA%D0%BE%D0%BD%D1%82%D0%B5%D0%BA%D1%81%D1%82%D0%B0-%D0%B2%D1%8B%D0%B7%D0%BE%D0%B2%D0%B0 26 | 27 | ## Is Javascript single threaded? 28 | Javascript is a single threaded language. This means it has one call stack and one memory heap. As expected, it executes code in order and must finish executing a piece code before moving onto the next. 29 | ###### Relative links: 30 | - https://dev.to/steelvoltage/if-javascript-is-single-threaded-how-is-it-asynchronous-56gd 31 | 32 | ## What is closure in js? 33 | A closure is an inner function that has access to the outer (enclosing) function’s variables—scope chain. The closure has three scope chains: it has access to its own scope (variables defined between its curly brackets), it has access to the outer function’s variables, and it has access to the global variables. 34 | ###### Relative links: 35 | - https://javascriptissexy.com/understand-javascript-closures-with-ease/ 36 | 37 | ## How to check if element exists in html? 38 | here's an easy way to do it with jQuery: 39 | ``` 40 | if ($('#elementId').length > 0) { 41 | // exists. 42 | } 43 | ``` 44 | And if you can't use 3rd-party libraries, just stick to base JavaScript: 45 | ``` 46 | var element = document.getElementById('elementId'); 47 | if (typeof(element) != 'undefined' && element != null) 48 | { 49 | // exists. 50 | } 51 | ``` 52 | ###### Relative links: 53 | - https://stackoverflow.com/questions/5629684/how-to-check-if-element-exists-in-the-visible-dom 54 | 55 | ## 2 functions with the same name but with different number of parameters. Can be the issues in this case? 56 | it is not possible to overload functions in Javascript 57 | ###### Relative links: 58 | - https://stackoverflow.com/questions/456177/function-overloading-in-javascript-best-practices 59 | 60 | [Home Page](README.md) 61 | -------------------------------------------------------------------------------- /linux.md: -------------------------------------------------------------------------------- 1 | #Linux 2 | - [How to print the list of processes in terminal Linux?](#how-to-print-the-list-of-processes-in-terminal-linux) 3 | 4 | ## How to print the list of processes in terminal Linux? 5 | The ps command lists running processes. The following command lists all processes running on your system: 6 | ``` 7 | ps -A 8 | ``` 9 | ###### Relative links: 10 | - https://www.howtogeek.com/107217/how-to-manage-processes-from-the-linux-terminal-10-commands-you-need-to-know/ 11 | 12 | [Home Page](README.md) 13 | -------------------------------------------------------------------------------- /maven.md: -------------------------------------------------------------------------------- 1 | # Maven 2 | - [What is the difference between Maven and Gradle?](#what-is-the-difference-between-maven-and-gradle) 3 | - [How will work Maven in the case of multiple version of the same dependency?](#how-will-work-maven-in-the-case-of-multiple-version-of-the-same-dependency) 4 | - [What is the dependency management in Maven?](#what-is-the-dependency-management-in-maven) 5 | - [Does maven support inheritance for pom files?](#does-maven-support-inheritance-for-pom-files) 6 | 7 | ## What is the difference between Maven and Gradle? 8 | You can think of Gradle as goodness of Ant and Maven put together minus the noise of XML. And scriptability with groovy is very big plus. 9 | - Gradle gives you conventions but still gives you power to override them easily. 10 | - Gradle build files are less verbose as they are written in groovy. 11 | - It provides very nice DSL for writing build tasks. 12 | - Has lot of good plugins and vibrant ecosystem 13 | - When to use Gradle and When to use Maven ? 14 | ###### Relative links: 15 | - https://stackoverflow.com/questions/18072456/difference-between-gradle-and-maven 16 | 17 | ## How will work Maven in the case of multiple version of the same dependency? 18 | For Java it doesn't matter how many versions of a class you provide. The default classloader will just pick the first one on the classpath it can find. 19 | ###### Relative links: 20 | - https://stackoverflow.com/questions/35381533/maven-multiple-version-of-same-dependency 21 | - https://stackoverflow.com/questions/24962607/multiple-versions-of-the-same-dependency-in-maven 22 | 23 | ## What is the dependency management in Maven? 24 | The dependency management section is a mechanism for centralizing dependency information. When you have a set of projects that inherits a common parent it's possible to put all information about the dependency in the common POM and have simpler references to the artifacts in the child POMs. 25 | ###### Relative links: 26 | - http://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html#Dependency_Management 27 | 28 | ## Does maven support inheritance for pom files? 29 | yes 30 | ###### Relative links: 31 | - https://stackoverflow.com/questions/9299083/what-is-inherited-in-maven-projects 32 | - http://maven.apache.org/pom.html#Inheritance 33 | 34 | [Home Page](README.md) 35 | -------------------------------------------------------------------------------- /microservices.md: -------------------------------------------------------------------------------- 1 | # Microservices 2 | - [What are the possible ways for communication between microservices?](#what-are-the-possible-ways-for-communication-between-microservices) 3 | - [What is exchange in message queue?](#what-is-exchange-in-message-queue) 4 | - [What are the benefits of microservices?](#what-are-the-benefits-of-microservices) 5 | - [What are the disadvantages of microservices?](#what-are-the-disadvantages-of-microservices) 6 | - [What are the possible issues in microservices](#what-are-the-possible-issues-in-microservices) 7 | - [What are the possible solutions for the case when one service is not available?](#what-are-the-possible-solutions-for-the-case-when-one-service-is-not-available) 8 | - [What is the difference between synchronous and asynchronous communication?](#what-is-the-difference-between-synchronous-and-asynchronous-communication) 9 | - [What are possible ways for implementing authentication in microservices?](#what-are-possible-ways-for-implementing-authentication-in-microservices) 10 | - [What is Eventual consistency?](#what-is-eventual-consistency) 11 | - [How different types of communication can influence on performance?](#how-different-types-of-communication-can-influence-on-performance) 12 | - [What are possible strategies and issues in microservices deployment?](#what-are-possible-strategies-and-issues-in-microservices-deployment) 13 | 14 | ## What are the possible ways for communication between microservices? 15 | + ***Synchronous protocol.*** HTTP is a synchronous protocol. The client sends a request and waits for a response from the service. That's independent of the client code execution that could be synchronous (thread is blocked) or asynchronous (thread isn't blocked, and the response will reach a callback eventually). The important point here is that the protocol (HTTP/HTTPS) is synchronous and the client code can only continue its task when it receives the HTTP server response. 16 | + ***Asynchronous protocol.*** Other protocols like AMQP (a protocol supported by many operating systems and cloud environments) use asynchronous messages. The client code or message sender usually doesn't wait for a response. It just sends the message as when sending a message to a RabbitMQ queue or any other message broker. 17 | ###### Relative links: 18 | + https://docs.microsoft.com/en-us/dotnet/architecture/microservices/architect-microservice-container-applications/communication-in-microservice-architecture 19 | + https://dzone.com/articles/communication-between-microservices 20 | 21 | ## What is exchange in message queue? 22 | Exchange: a queue aggregator that abstract away message queues and routes messages to the appropriate queue based on some predefined logic. 23 | ###### Relative links: 24 | + https://dev.to/matteojoliveau/microservices-communications-why-you-should-switch-to-message-queues--48ia 25 | 26 | ## What are the benefits of microservices? 27 | + Technology Heterogeneity 28 | + Resilience 29 | + Scaling 30 | + Ease of Deployment 31 | + Organizational Alignment 32 | + Composability 33 | + Optimizing for Replaceability 34 | ###### Relative links: 35 | + https://stackoverflow.com/questions/34903605/microservices-what-are-pros-and-cons 36 | + https://www.tiempodev.com/blog/disadvantages-of-a-microservices-architecture/ 37 | 38 | ## What are the disadvantages of microservices? 39 | + Microservices Are More Complex 40 | + Microservices Require Cultural Changes 41 | + Microservices Are More Expensive 42 | + Microservices Pose Security Challenges 43 | ###### Relative links: 44 | https://www.tiempodev.com/blog/disadvantages-of-a-microservices-architecture/ 45 | 46 | ## What are the possible issues in microservices 47 | 1. As if monitoring a monolith wasn’t hard enough 48 | 2. Logging is distributed between services 49 | 3. An issue that’s caused by one service, can cause trouble elsewhere 50 | 4. Finding the root cause of problems 51 | 5. Version management and cyclic dependencies between services 52 | ###### Relative links: 53 | + https://blog.overops.com/5-ways-to-not-f-up-your-microservices-in-production/ 54 | 55 | ## What are the possible solutions for the case when one service is not available? 56 | 1. The circuit breaker pattern is the solution to this problem. The basic idea behind the circuit breaker is very simple. You wrap a protected function call in a circuit breaker object, which monitors for failures. Once the failures reach a certain threshold, the circuit breaker trips, and all further calls to the circuit breaker return with an error or with some alternative service or default message, without the protected call being made at all. This will make sure system is responsive and threads are not waiting for an unresponsive call. 57 | 2. Retry Logic 58 | ###### Relative links: 59 | + https://blog.risingstack.com/designing-microservices-architecture-for-failure/ 60 | + https://dzone.com/articles/circuit-breaker-pattern 61 | 62 | ## What is the difference between synchronous and asynchronous communication? 63 | + ***Synchronous protocol.*** HTTP is a synchronous protocol. The client sends a request and waits for a response from the service. That's independent of the client code execution that could be synchronous (thread is blocked) or asynchronous (thread isn't blocked, and the response will reach a callback eventually). The important point here is that the protocol (HTTP/HTTPS) is synchronous and the client code can only continue its task when it receives the HTTP server response. 64 | + ***Asynchronous protocol.*** Other protocols like AMQP (a protocol supported by many operating systems and cloud environments) use asynchronous messages. The client code or message sender usually doesn't wait for a response. It just sends the message as when sending a message to a RabbitMQ queue or any other message broker. 65 | ###### Relative links: 66 | https://docs.microsoft.com/en-us/dotnet/architecture/microservices/architect-microservice-container-applications/communication-in-microservice-architecture 67 | 68 | ## What are possible ways for implementing authentication in microservices? 69 | 1. Distributed Session Management 70 | 2. Client Token 71 | 3. Single sign-on 72 | 4. Client Token with API Gateway 73 | 5. Third-party application access 74 | 6. Mutual Authentication 75 | ###### Relative links: 76 | + https://medium.com/tech-tajawal/microservice-authentication-and-authorization-solutions-e0e5e74b248a 77 | + https://medium.com/@marcus.cavalcanti/stateless-authentication-for-microservices-9914c3529663 78 | 79 | ## What is Eventual consistency? 80 | Rather than ensuring that the system is in a consistent state all the time, instead we can accept that the system will get it at some point in the future. This approach is especially useful for long-living business operations. 81 | ###### Relative links: 82 | + https://softwareengineering.stackexchange.com/questions/354911/microservices-handling-eventual-consistency 83 | 84 | ## How different types of communication can influence on performance? 85 | You should prefer asynchronous communication for all remote calls. They don’t block any resources while you’re waiting for the response and you can even execute multiple calls in parallel. That can provide huge performance improvements because you just need to wait until the slowest service answered your request. 86 | 87 | As always, there are several ways to implement an asynchronous communication between two services. One of them is an asynchronous REST call. 88 | ###### Relative links: 89 | - https://stackify.com/communication-microservices-avoid-common-problems/ 90 | 91 | ## What are possible strategies and issues in microservices deployment? 92 | ###### Relative links: 93 | - https://www.infoworld.com/article/3565750/4-deployment-strategies-for-resilient-microservices.html 94 | 95 | [Home Page](README.md) 96 | -------------------------------------------------------------------------------- /patterns.md: -------------------------------------------------------------------------------- 1 | # Patterns 2 | - [Which architectural patterns you know?](#which-architectural-patterns-you-know) 3 | - [What does it mean single responsibility?](#what-does-it-mean-single-responsibility) 4 | - [What is the difference between facade and proxy/gateway?](#what-is-the-difference-between-facade-and-proxygateway) 5 | - [What can we do in the case of constructor with big number of parameters?](#what-can-we-do-in-the-case-of-constructor-with-big-number-of-parameters) 6 | - [How can be implemented builder?](#how-can-be-implemented-builder) 7 | - [What is pattern Visitor?](#what-is-pattern-visitor) 8 | - [What is the issue can be solved by visitor?](#what-is-the-issue-can-be-solved-by-visitor) 9 | - [What can you say about pattern observer?](#what-can-you-say-about-pattern-observer) 10 | - [How to initialize object depends on type?](#how-to-initialize-object-depends-on-type) 11 | - [Why Dependency Injection is needed?](#why-dependency-injection-is-needed) 12 | - [Should services always return dtos?](#should-services-always-return-dtos) 13 | - [The difference between adapter and decorator?](#the-difference-between-adapter-and-decorator) 14 | 15 | ## Which architectural patterns you know? 16 | + Layered Pattern 17 | + Microkernel 18 | + CQRS 19 | + Event Sourcing 20 | + Microservices 21 | ###### Relative links: 22 | + https://dzone.com/articles/software-architecture-the-5-patterns-you-need-to-k 23 | 24 | ## What does it mean single responsibility? 25 | Every module should have one single responsibility. This means two separate concerns/responsibilities/tasks should always be implemented in separate modules. Robert C. Martin defines a “responsibility” as a “reason to change”. If a module has several responsibilities, there are several reasons to change this module—namely the requirements for each responsibility may change. On the other hand a reason to change a module also means that it is the responsibility of the module to implement the aspect that is changed. 26 | ###### Relative links: 27 | + http://www.principles-wiki.net/principles:single_responsibility_principle 28 | + https://javarush.ru/groups/posts/osnovnye-principy-dizajna-klassov-solid-v-java 29 | 30 | ## What is the difference between facade and proxy/gateway? 31 | Reviewing Facade in the GoF book and the link in another answer to Martin Fowler's Gateway, it appears that their focus is in opposite directions. 32 | Facade provides a simple uniform view of complex internals to (one or more)external clients; 33 | Gateway provides a simple uniform view of external resources to the internals of an application. 34 | This distinction lets us focus on which is more important in a design : 35 | With the Facade, the external system is our customer; it is better to add complexity facing inwards if it makes the external interface simpler. 36 | With the Gateway, the internal system is our customer; give it all the help we can, even if the externals are more complex. 37 | ###### Relative links: 38 | + https://stackoverflow.com/questions/4422211/what-is-the-difference-between-facade-and-gateway-design-patterns 39 | 40 | ## What can we do in the case of constructor with big number of parameters? 41 | Builder pattern. 42 | ###### Relative links: 43 | + https://stackoverflow.com/questions/222214/managing-constructors-with-many-parameters-in-java 44 | 45 | ## How can be implemented builder? 46 | We will configure all of the fields that we want on the builder, and then we'll use the builder to create models. At the same time, we'll remove the public constructor from the class and replace it with a private constructor so that models can only be created via the builder. 47 | ###### Relative links: 48 | + https://dzone.com/articles/design-patterns-the-builder-pattern 49 | 50 | ## What is pattern Visitor? 51 | The core of this pattern is the Visitor interface. This interface defines a visit operation for each type of ConcreteElement in the object structure. Meanwhile, the ConcreteVisitor implements the operations defined in the Visitor interface. The concrete visitor will store local state, typically as it traverses the set of elements. The element interface simply defines an accept method to allow the visitor to run some action over that element - the ConcreteElement will implement this accept method. 52 | ###### Relative links: 53 | + https://dzone.com/articles/design-patterns-visitor 54 | + https://refactoring.guru/ru/design-patterns/visitor 55 | 56 | ## What is the issue can be solved by visitor? 57 | So, while the Visitor may seem a bit strange at first, you can see how much it helps to clean up your code. That's the whole point of this pattern - to allow you seperate out certain logic from the elements themselves, keeping your data classes simple. 58 | ###### Relative links: 59 | + https://dzone.com/articles/design-patterns-visitor 60 | + https://refactoring.guru/ru/design-patterns/visitor 61 | 62 | ## What can you say about pattern observer? 63 | ***Observer*** is a behavioral design pattern. It specifies communication between objects: observable and observers. An observable is an object which notifies observers about the changes in its state. 64 | ###### Relative links: 65 | + https://www.baeldung.com/java-observer-pattern 66 | 67 | ## How to initialize object depends on type? 68 | Abstract Factory, Factory method 69 | ###### Relative links: 70 | + https://www.geeksforgeeks.org/design-patterns-set-2-factory-method/ 71 | + https://www.geeksforgeeks.org/abstract-factory-pattern/ 72 | 73 | ## Why Dependency Injection is needed? 74 | Dependency injection is one of two ways of how to remove dependencies in your code. It is very useful for configuration changes after compile-time, and it is a great thing for unit testing (as it makes it very easy to inject stubs and / or mocks). 75 | ###### Relative links: 76 | - https://stackoverflow.com/questions/14301389/why-does-one-use-dependency-injection 77 | 78 | ## Should services always return dtos? 79 | ###### Relative links: 80 | - https://stackoverflow.com/questions/21554977/should-services-always-return-dtos-or-can-they-also-return-domain-models 81 | - https://vaadin.com/learn/tutorials/ddd/ddd_and_hexagonal 82 | 83 | ## The difference between adapter and decorator? 84 | **Decorator**, attach additional responsibilities to an object dynamically. 85 | 86 | **Adapter**, adapts interface of an existing class to another interface. 87 | ###### Relative links: 88 | - https://stackoverflow.com/questions/42737096/design-patterns-adapter-pattern-vs-decorator-pattern 89 | 90 | [Home Page](README.md) 91 | -------------------------------------------------------------------------------- /rabbitmq.md: -------------------------------------------------------------------------------- 1 | # RabbitMQ 2 | - [What is RabbitMQ?](#what-is-rabbitmq) 3 | - [What are the advantages/disadvantages of using message brokers?](#what-are-the-advantagesdisadvantages-of-using-message-brokers) 4 | - [What is the Exchange in RabbitMQ?](#what-is-the-exchange-in-rabbitmq) 5 | 6 | ## What is RabbitMQ? 7 | RabbitMQ, also known as Open-Source Message Broker, supports multiple message protocols and can be deployed on distributed systems. It is lightweight and makes it easy to deploy applications. It mainly acts as a queue where a message which is entered can first be operated on. RabbitMQ runs on many operating systems and cloud environments and provides a wide range of developer tools for most popular languages. It is a Producer-Consumer style pattern where the producer sends a message and the consumer consumes it. The main features of RabbitMQ are mentioned below: 8 | + Asynchronous Messaging 9 | + Distributed Deployment 10 | + Management & Monitoring 11 | + Enterprise- and Cloud-Ready 12 | ###### Relative links: 13 | + https://dzone.com/articles/rabbitmq-in-microservices 14 | 15 | ## What are the advantages/disadvantages of using message brokers? 16 | There are many advantages to using messaging: 17 | 18 | - Decouples the client from the service – A client makes a request simply by sending a message to the appropriate channel. The client is completely unaware of the service instances. It does not need to use a discovery mechanism to determine the location of a service instance. 19 | - Message buffering – With a synchronous request/response protocol, such as a HTTP, both the client and service must be available for the duration of the exchange. In contrast, a message broker queues up the messages written to a channel until they can be processed by the consumer. This means, for example, that an online store can accept orders from customers even when the order fulfillment system is slow or unavailable. The order messages simply queue up. 20 | - Flexible client‑service interactions – Messaging supports all of the interaction styles described earlier. 21 | - Explicit inter‑process communication – RPC‑based mechanisms attempt to make invoking a remote service look the same as calling a local service. However, because of the laws of physics and the possibility of partial failure, they are in fact quite different. Messaging makes these differences very explicit so developers are not lulled into a false sense of security. 22 | 23 | There are, however, some downsides to using messaging: 24 | 25 | - Additional operational complexity – The messaging system is yet another system component that must be installed, configured, and operated. It’s essential that the message broker be highly available, otherwise system reliability is impacted. 26 | - Complexity of implementing request/response‑based interaction – Request/response‑style interaction requires some work to implement. Each request message must contain a reply channel identifier and a correlation identifier. The service writes a response message containing the correlation ID to the reply channel. The client uses the correlation ID to match the response with the request. It is often easier to use an IPC mechanism that directly supports request/response. 27 | ###### Relative links: 28 | - https://www.nginx.com/blog/building-microservices-inter-process-communication/ 29 | 30 | ## What is the Exchange in RabbitMQ? 31 | Messages are not published directly to a queue. Instead, the producer sends messages to an exchange. Exchanges are message routing agents, defined by the virtual host within RabbitMQ. An exchange is responsible for routing the messages to different queues with the help of header attributes, bindings, and routing keys. 32 | ###### Relative links: 33 | - https://www.cloudamqp.com/blog/2015-09-03-part4-rabbitmq-for-beginners-exchanges-routing-keys-bindings.html 34 | -------------------------------------------------------------------------------- /react.md: -------------------------------------------------------------------------------- 1 | # React 2 | 3 | ## как работает redux? 4 | 5 | ## что такое reducer? 6 | 7 | ## можно state менять в компоненте? 8 | 9 | ## как reducers срабатывают? 10 | 11 | ## как компонент связан с reducer? он же не вызывается напрямую? 12 | 13 | ## как написать reducer? 14 | 15 | ## где create store нужн оли что-то прописывать? 16 | 17 | ## life cycle react компонента? 18 | 19 | ## какие life-cycle методы есть у компонента? 20 | 21 | ## render метод? 22 | 23 | ## чем отличается state от props? 24 | 25 | ## как меняется state в компоненте? 26 | 27 | -------------------------------------------------------------------------------- /rest.md: -------------------------------------------------------------------------------- 1 | # REST 2 | - [What is rest architecture? What are the requirements?](#what-is-rest-architecture-what-are-the-requirements) 3 | - [Is there state in rest architecture?](#is-there-state-in-rest-architecture) 4 | - [Can be used query params in rest architecture?](#can-be-used-query-params-in-rest-architecture) 5 | - [What is the difference get and post?](#what-is-the-difference-get-and-post) 6 | - [What is the difference between soap and rest?](#what-is-the-difference-between-soap-and-rest) 7 | - [Is it correct to update something during get request?](#is-it-correct-to-update-something-during-get-request) 8 | - [Is it possible to use body in get requests?](#is-it-possible-to-use-body-in-get-requests) 9 | - [What are possible types of requests for http protocol?](#what-are-possible-types-of-requests-for-http-protocol) 10 | - [Why method options is needed?](#why-method-options-is-needed) 11 | - [What is the difference between put and post?](#what-is-the-difference-between-put-and-post) 12 | - [What can be used as rest client?](#what-can-be-used-as-rest-client) 13 | - [How http protocol work?](#how-http-protocol-work) 14 | - [What are the possible solutions in the case of big number of parameters for search method?](#what-are-the-possible-solutions-in-the-case-of-big-number-of-parameters-for-search-method) 15 | - [What should be the response in the case of DELETE request?](#what-should-be-the-response-in-the-case-of-delete-request) 16 | - [What is the best solution for representing Enum in API?](#what-is-the-best-solution-for-representing-enum-in-api) 17 | - [What is the best practice for getting Unique Resource From Sub-Collection?](#what-is-the-best-practice-for-getting-unique-resource-from-sub-collection) 18 | - [How search in sub-collections can be implemented?](#how-search-in-sub-collections-can-be-implemented) 19 | - [What is the best practice for nested resources?](#what-is-the-best-practice-for-nested-resources) 20 | - [Fine Grained CRUD Resources vs. Coarse Grained Resources?](#fine-grained-crud-resources-vs-coarse-grained-resources) 21 | - [Best guidelines?](#best-guidelines) 22 | - [Best practice for PATCH?](#best-practice-for-patch) 23 | - [Do sessions violate REST?](#do-sessions-violate-rest) 24 | - [When to use GraphQL?](#when-to-use-graphql) 25 | - [What is ElasticSearch?](#what-is-elasticsearch) 26 | - [What are the possible ways of versioning?](#what-are-the-possible-ways-of-versioning) 27 | - [Is it good practice to use Map in a model for a REST API?](#is-it-good-practice-to-use-mapstring-object-in-a-model-for-a-rest-api) 28 | 29 | ## What is rest architecture? What are the requirements? 30 | - resources being identified by a persistent identifier: URIs are the ubiquitous choice of identifier these days 31 | - resources being manipulated using a common set of verbs: HTTP methods are the commonly seen case - the venerable Create, Retrieve, Update, Delete becomes POST, GET, PUT, and DELETE. But REST is not limited to HTTP, it is just the most commonly used transport right now. 32 | - the actual representation retrieved for a resource is dependent on the request and not the identifier: use Accept headers to control whether you want XML, HTTP, or even a Java Object representing the resource 33 | - maintaining the state in the object and representing the state in the representation 34 | - representing the relationships between resources in the representation of the resource: the links between objects are embedded directly in the representation 35 | - resource representations describe how the representation can be used and under what circumstances it should be discarded/refetched in a consistent manner: usage of HTTP Cache-Control headers 36 | ###### Relative links: 37 | + https://stackoverflow.com/questions/671118/what-exactly-is-restful-programming 38 | + https://restfulapi.net/rest-architectural-constraints/ 39 | 40 | ## Is there state in rest architecture? 41 | As per the REST (REpresentational “State” Transfer) architecture, the server does not store any state about the client session on the server side. This restriction is called Statelessness. Each request from the client to server must contain all of the information necessary to understand the request, and cannot take advantage of any stored context on the server. Session state is therefore kept entirely on the client. client is responsible for storing and handling all application state related information on client side. 42 | ###### Relative links: 43 | + https://restfulapi.net/statelessness/ 44 | 45 | ## Can be used query params in rest architecture? 46 | I'd recommend putting any required parameters in the path, and any optional parameters should certainly be query string parameters. Putting optional parameters in the path will end up getting really messy when trying to write URL handlers that match different combinations. 47 | ###### Relative links: 48 | + https://stackoverflow.com/questions/4024271/rest-api-best-practices-where-to-put-parameters 49 | + https://stackoverflow.com/questions/11552248/when-to-use-queryparam-vs-pathparam 50 | 51 | ## What is the difference get and post? 52 | - **GET** is idempotent: it is for obtaining a resource, without changing anything on the server. As a consequence it should be perfectly safe to resubmit a GET request. 53 | - **POST** is not: it is for updating information on the server. It can therefore not be assumed that it is safe to re-submit the request which is why most browsers ask for confirmation when you hit refresh on a POST request. 54 | ###### Relative links: 55 | + https://stackoverflow.com/questions/2080863/what-is-the-difference-between-a-http-get-and-http-post-and-why-is-http-post-wea 56 | 57 | ## What is the difference between soap and rest? 58 | - REST API has no has no official standard at all because it is an architectural style. SOAP API, on the other hand, has an official standard because it is a protocol. 59 | - REST APIs uses multiple standards like HTTP, JSON, URL, and XML while SOAP APIs is largely based on HTTP and XML. 60 | - As REST API deploys multiple standards, so it takes fewer resources and bandwidth as compared to SOAP that uses XML for the creation of Payload and results in the large sized file. 61 | - The ways both APIs exposes the business logics are also different. REST API takes advantage of URL exposure like @path("/WeatherService") while SOAP API use of services interfaces like @WebService. 62 | - SOAP API defines too many standards, and its implementer implements the things in a standard way only. In the case of miscommunication from service, the result will be the error. REST API, on the other hand, don't make emphasis on too many standards and results in corrupt API in the end. 63 | - REST API uses Web Application Description Language, and SOAP API used Web Services Description language for describing the functionalities being offered by web services. 64 | - REST APIs are more convenient with JavaScript and can be implemented easily as well. SOAP APIs are also convenient with JavaScript but don't support for greater implementation. 65 | ###### Relative links: 66 | + https://dzone.com/articles/difference-between-rest-and-soap-api 67 | 68 | ## Is it correct to update something during get request? 69 | no. GET is idempotent: it is for obtaining a resource, without changing anything on the server. As a consequence it should be perfectly safe to resubmit a GET request. 70 | ###### Relative links: 71 | + https://stackoverflow.com/questions/2080863/what-is-the-difference-between-a-http-get-and-http-post-and-why-is-http-post-wea 72 | 73 | ## Is it possible to use body in get requests? 74 | Yes, you can send a request body with GET but it should not have any meaning. If you give it meaning by parsing it on the server and changing your response based on its contents, then you are ignoring this recommendation in the HTTP/1.1 spec, section 4.3: 75 | 76 | [...] if the request method does not include defined semantics for an entity-body, then the message-body SHOULD be ignored when handling the request. 77 | ###### Relative links: 78 | - https://stackoverflow.com/questions/978061/http-get-with-request-body 79 | 80 | ## What are possible types of requests for http protocol? 81 | **GET** 82 | 83 | The GET method requests a representation of the specified resource. Requests using GET should only retrieve data. 84 | 85 | **HEAD** 86 | 87 | The HEAD method asks for a response identical to that of a GET request, but without the response body. 88 | 89 | **POST** 90 | 91 | The POST method is used to submit an entity to the specified resource, often causing a change in state or side effects on the server. 92 | 93 | **PUT** 94 | 95 | The PUT method replaces all current representations of the target resource with the request payload. 96 | 97 | **DELETE** 98 | 99 | The DELETE method deletes the specified resource. 100 | 101 | **CONNECT** 102 | 103 | The CONNECT method establishes a tunnel to the server identified by the target resource. 104 | 105 | **OPTIONS** 106 | 107 | The OPTIONS method is used to describe the communication options for the target resource. 108 | 109 | **TRACE** 110 | 111 | The TRACE method performs a message loop-back test along the path to the target resource. 112 | 113 | **PATCH** 114 | 115 | The PATCH method is used to apply partial modifications to a resource. 116 | ###### Relative links: 117 | - https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods 118 | 119 | ## Why method options is needed? 120 | The **HTTP OPTIONS** method is used to request information about the communication options available for the target resource. The response may include an Allow header indicating allowed HTTP methods on the resource, or various Cross Origin Resource Sharing headers. The HTTP OPTIONS method is both safe and idempotent, as it is intended only for use in querying information about ways to interact with a resource. 121 | ###### Relative links: 122 | - https://egghead.io/lessons/tools-use-http-options-method 123 | 124 | ## What is the difference between put and post? 125 | - **POST** to a URL creates a child resource at a server defined URL. 126 | - **PUT** to a URL creates/replaces the resource in its entirety at the client defined URL. 127 | - **PATCH** to a URL updates part of the resource at that client defined URL. 128 | ###### Relative links: 129 | - https://stackoverflow.com/questions/630453/put-vs-post-in-rest 130 | 131 | ## What can be used as rest client? 132 | 1. Netflix provides Feign as an abstraction over REST-based calls, by which microservices can communicate with each other, but developers don't have to bother about REST internal details. 133 | 2. Jersey 134 | 3. Spring RestTemplate 135 | ###### Relative links: 136 | + https://dzone.com/articles/microservices-communication-feign-as-rest-client 137 | + https://stackoverflow.com/questions/221442/rest-clients-for-java 138 | 139 | ## How http protocol work? 140 | As a request-response protocol, HTTP gives users a way to interact with web resources such as HTML files by transmitting hypertext messages between clients and servers. HTTP clients generally use Transmission Control Protocol (TCP) connections to communicate with servers. 141 | ###### Relative links: 142 | + https://www.extrahop.com/resources/protocols/http/ 143 | + https://www.quora.com/How-does-HTTP-work 144 | 145 | ## What are the possible solutions in the case of big number of parameters for search method? 146 | 1. POST request with body; 147 | 2. Encoding the query string in GET request; 148 | 3. Aliases. 149 | ###### Relative links: 150 | - https://softwareengineering.stackexchange.com/questions/353086/what-is-a-proper-way-to-do-a-complex-restful-search-method 151 | 152 | ## What should be the response in the case of DELETE request? 153 | There is no hard RESTful standard. **204 No Content** is a popular response for DELETE. 154 | ###### Relative links: 155 | - https://stackoverflow.com/questions/25970523/restful-what-should-a-delete-response-body-contain 156 | 157 | ## What is the best solution for representing Enum in API? 158 | Strings. 159 | ###### Relative links: 160 | - https://softwareengineering.stackexchange.com/questions/220091/how-to-represent-enum-types-in-a-public-api 161 | 162 | ## What is the best practice for getting Unique Resource From Sub-Collection? 163 | ###### Relative links: 164 | - https://cloud.google.com/apis/design/design_patterns#get_unique_resource_from_sub-collection 165 | 166 | ## How search in sub-collections can be implemented? 167 | ###### Relative links: 168 | - https://cloud.google.com/apis/design/design_patterns#list_sub-collections 169 | 170 | ## What is the best practice for nested resources? 171 | ###### Relative links: 172 | - https://www.moesif.com/blog/technical/api-design/REST-API-Design-Best-Practices-for-Sub-and-Nested-Resources/ 173 | 174 | ## Fine Grained CRUD Resources vs. Coarse Grained Resources? 175 | ###### Relative links: 176 | - https://dzone.com/articles/rest-api-design-resource-modeling-1 177 | - https://medium.com/garri-hov/rest-api-guideline-resource-modeling-48e63807a1b3 178 | - https://nordicapis.com/how-granular-should-you-design-apis/ 179 | 180 | ## Best guidelines? 181 | ###### Relative links: 182 | - https://github.com/microsoft/api-guidelines/blob/vNext/Guidelines.md 183 | - https://opensource.zalando.com/restful-api-guidelines/ 184 | 185 | ## Best practice for PATCH? 186 | ###### Relative links: 187 | - https://opensource.zalando.com/restful-api-guidelines/#patch 188 | 189 | ## Do sessions violate REST? 190 | ###### Relative links: 191 | - https://stackoverflow.com/questions/6068113/do-sessions-really-violate-restfulness 192 | 193 | ## When to use GraphQL? 194 | ###### Relative links: 195 | - https://dzone.com/articles/why-and-when-to-use-graphql-1 196 | 197 | ## What is ElasticSearch? 198 | ###### Relative links: 199 | - https://dzone.com/articles/what-is-elasticsearch-and-how-it-can-be-useful 200 | 201 | ## What are the possible ways of versioning? 202 | ###### Relative links: 203 | - https://restfulapi.net/versioning/ 204 | 205 | ## Is it good practice to use `Map` in a model for a REST API? 206 | Using `Map` in REST models is generally discouraged due to poor type safety, lack of schema clarity, and harder API validation. However, it can be acceptable for internal use, plugin-like extensibility, or storing custom metadata. 207 | 208 | [Home Page](README.md) 209 | -------------------------------------------------------------------------------- /servlet.md: -------------------------------------------------------------------------------- 1 | # Servlet 2 | - [What is servlet?](#what-is-servlet) 3 | - [What is difference between parameters and attributes?](#what-is-difference-between-parameters-and-attributes) 4 | - [What is the life cycle of servlet?](#what-is-the-life-cycle-of-servlet) 5 | - [What is the servlet mapping?](#what-is-the-servlet-mapping) 6 | 7 | ## What is servlet? 8 | A servlet is simply a class which responds to a particular type of network request - most commonly an HTTP request. Basically servlets are usually used to implement web applications - but there are also various frameworks which operate on top of servlets (e.g. Struts) to give a higher-level abstraction than the "here's an HTTP request, write to this HTTP response" level which servlets provide. 9 | 10 | Servlets run in a servlet container which handles the networking side (e.g. parsing an HTTP request, connection handling etc). One of the best-known open source servlet containers is Tomcat. 11 | ###### Relative links: 12 | + https://stackoverflow.com/questions/7213541/what-is-java-servlet 13 | 14 | ## What is difference between parameters and attributes? 15 | + ***getParameter()*** returns http request parameters. Those passed from the client to the server. For example http://example.com/servlet?parameter=1. Can only return String 16 | + ***getAttribute()*** is for server-side usage only - you fill the request with attributes that you can use within the same request. For example - you set an attribute in a servlet, and read it from a JSP. Can be used for any object, not just string. 17 | ###### Relative links: 18 | + https://stackoverflow.com/questions/5243754/difference-between-getattribute-and-getparameter 19 | 20 | ## What is the life cycle of servlet? 21 | There are three life cycle methods of a Servlet: 22 | + init() 23 | + service() 24 | + destroy() 25 | ###### Relative links: 26 | + https://www.geeksforgeeks.org/life-cycle-of-a-servlet/ 27 | 28 | ## What is the servlet mapping? 29 | Servlet mapping specifies the web container of which java servlet should be invoked for a url given by client. It maps url patterns to servlets. When there is a request from a client, servlet container decides to which application it should forward to. Then context path of url is matched for mapping servlets. 30 | ###### Relative links: 31 | + https://javapapers.com/servlet/what-is-servlet-mapping/ 32 | 33 | [Home Page](README.md) 34 | -------------------------------------------------------------------------------- /spring.md: -------------------------------------------------------------------------------- 1 | # Spring 2 | - [How make spring service thread-safe?](#how-make-spring-service-thread-safe) 3 | - [What is bean?](#what-is-bean) 4 | - [How bean gets into the container?](#how-bean-gets-into-the-container) 5 | - [What are the possible bean scopes?](#what-are-the-possible-bean-scopes) 6 | - [What is the difference @Service between @Component?](#what-is-the-difference-service-between-component) 7 | - [What is the difference between @Service and @Bean](#what-is-the-difference-between-service-and-bean) 8 | - [How to call a method after bean initialization?](#how-to-call-a-method-after-bean-initialization) 9 | - [What is the default scope?](#what-is-the-default-scope) 10 | - [What is the prototype scope?](#what-is-the-prototype-scope) 11 | - [What are the possible ways of Dependency Injection?](#what-are-the-possible-ways-of-dependency-injection) 12 | - [Where better to use dependency injection via constructor? Where via setter?](#where-better-to-use-dependency-injection-via-constructor-where-via-setter) 13 | - [How to catch the exceptions for controllers?](#how-to-catch-the-exceptions-for-controllers) 14 | - [What is the difference between BeanFactory and FactoryBean?](#what-is-the-difference-between-beanfactory-and-factorybean) 15 | - [What is the difference Spring and Spring Boot?](#what-is-the-difference-spring-and-spring-boot) 16 | - [How to add own auto-configurations?](#how-to-add-own-auto-configurations) 17 | - [Where can be stored the list of auto-configurations in META-INF?](#where-can-be-stored-the-list-of-auto-configurations-in-meta-inf) 18 | - [What are the possible ways of configurations in Spring?](#what-are-the-possible-ways-of-configurations-in-spring) 19 | - [What is the lookup method?](#what-is-the-lookup-method) 20 | - [What is declarative transaction in Spring?](#what-is-declarative-transaction-in-spring) 21 | - [What creates a proxy?](#what-creates-a-proxy) 22 | - [Does @transactional method work in the case of execution in the same class?](#does-transactional-method-work-in-the-case-of-execution-in-the-same-class) 23 | - [What is environment?](#what-is-environment) 24 | - [How does auto-configuration work?](#how-does-auto-configuration-work) 25 | - [What is the difference between @Resource and @Autowired annotations?](#what-is-the-difference-between-resource-and-autowired-annotations) 26 | - [What is the feature in Spring Boot for setting up the dependencies?](#what-is-the-feature-in-spring-boot-for-setting-up-the-dependencies) 27 | - [Where does Spring Boot application begin?](#where-does-spring-boot-application-begin) 28 | - [What is the difference between @Controller and @RestController annotations?](#what-is-the-difference-between-controller-and-restcontroller-annotations) 29 | - [Does @Qualifier annotation can work only with bean name from @Component annotation?](#does-qualifier-annotation-can-work-only-with-bean-name-from-component-annotation) 30 | - [Is it required to put @Repository annotation in the case of extending JpaRepository?](#is-it-required-to-put-repository-annotation-in-the-case-of-extending-jparepository) 31 | - [How ResponseEntity can be used?](#how-responseentity-can-be-used) 32 | - [Does entity from @Transactional method can be updated without executing save method?](#does-entity-from-transactional-method-can-be-updated-without-executing-save-method) 33 | - [Is it possible to have only one transaction in the case of executing several @Transactional methods?](#is-it-possible-to-have-only-one-transaction-in-the-case-of-executing-several-transactional-methods) 34 | - [Anti-patterns of bean validation?](#anti-patterns-of-bean-validation) 35 | - [Is it good practice to define interface for Spring bean?](#is-it-good-practice-to-define-interface-for-spring-bean) 36 | - [How does @Transactional annotation work?](#how-does-transactional-annotation-work) 37 | - [How to use @NamedEntityGraph with Spring Data JPA?](#how-to-use-namedentitygraph-with-spring-data-jpa) 38 | 39 | ## How make spring service thread-safe? 40 | There are several ways, probably too long to list here but here are a few examples: 41 | + Design your beans immutable: for example have no setters and only use constructor arguments to create a bean. There are other ways, such as Builder pattern, etc.. 42 | + Design your beans stateless: for example a bean that does something can be just a function (or several). This bean in most cases can and should be stateless, which means it does not have any state, it only does things with function arguments you provide each time (on each invocation) 43 | + Design your beans persistent: which is a special case of "immutable", but has some very nice properties. Usually is used in functional programming, where Spring (at least yet) not as useful as in imperative world, but I have used them with Scala/Spring projects. 44 | + Design your beans with locks [last resort]: I would recommend against this unless you are working on a lower level library. The reason is we (humans) are not good thinking in terms of locks. Just the way we are raised and nurtured. Everything happens in parallel without us needing to "put that rain on pause, let me get an umbrella". Computers however are all about locks when you are talking "multiple things at the same time", hence there are some of us (exceptional people) who are doing their fair share and implementing libraries based on these locks. Most of other humans can just use these libraries and worry not about concurrency. 45 | ###### Relative links: 46 | + http://dolszewski.com/spring/spring-bean-thread-safety-guide/ 47 | + https://stackoverflow.com/questions/15745140/are-spring-objects-thread-safe 48 | 49 | ## What is bean? 50 | The objects that form the backbone of your application and that are managed by the Spring IoC container are called beans. A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container. These beans are created with the configuration metadata that you supply to the container. 51 | ###### Relative links: 52 | + https://www.tutorialspoint.com/spring/spring_bean_definition.htm 53 | 54 | ## How bean gets into the container? 55 | The IoC container receives metadata from either an XML file, Java annotations, or Java code. The container gets its instructions on what objects to instantiate, configure, and assemble from simple Plain Old Java Objects (POJO) by reading the configuration metadata provided. These created objects through this process called Spring Beans. 56 | 57 | The responsibilities of IoC container are: 58 | + Instantiating the bean 59 | + Wiring the beans together 60 | + Configuring the beans 61 | + Managing the bean’s entire life-cycle 62 | ###### Relative links: 63 | + https://www.zoltanraffai.com/blog/how-does-spring-work-internally/ 64 | 65 | ## What are the possible bean scopes? 66 | + ***singleton.*** Scopes a single bean definition to a single object instance per Spring IoC container. 67 | + ***prototype.*** Scopes a single bean definition to any number of object instances. 68 | + ***request.*** Scopes a single bean definition to the lifecycle of a single HTTP request; that is each and every HTTP request will have its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext. 69 | + ***session.*** Scopes a single bean definition to the lifecycle of a HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext. 70 | + ***global session.*** Scopes a single bean definition to the lifecycle of a global HTTP Session. Typically only valid when used in a portlet context. Only valid in the context of a web-aware Spring ApplicationContext. 71 | ###### Relative links: 72 | + https://docs.spring.io/spring/docs/3.0.0.M3/reference/html/ch04s04.html 73 | 74 | ## What is the difference @Service between @Component? 75 | Apart from the fact that it's used to indicate, that it's holding the business logic, there’s nothing else noticeable in this annotation; but who knows, Spring may add some additional exceptional in future. 76 | ###### Relative links: 77 | + https://stackoverflow.com/questions/6827752/whats-the-difference-between-component-repository-service-annotations-in 78 | 79 | ## What-is-the-difference-between-service-and-bean 80 | @Bean annotation is method-level and is used in configuration classes to fine tune special bean and add it to IoC container. @Service annotation is class-level and is used to show Spring that this class has to be managed by IoC container. 81 | 82 | ## How to call a method after bean initialization? 83 | + afterPropertiesSet method; 84 | + annotation @PostConstruct; 85 | + init-method attribute; 86 | + BeanPostProcessor; 87 | ###### Relative links: 88 | + https://codippa.com/callback-methods-in-spring-beans/ 89 | + http://findnerd.com/list/view/How-to-call-a-method-after-bean-initialization-is-complete/7530/ 90 | 91 | ## What is the default scope? 92 | singleton 93 | ###### Relative links: 94 | + https://www.tutorialspoint.com/spring/spring_bean_scopes.htm 95 | 96 | ## What is the prototype scope? 97 | Scopes a single bean definition to any number of object instances. 98 | ###### Relative links: 99 | + https://docs.spring.io/spring/docs/3.0.0.M3/reference/html/ch04s04.html 100 | 101 | ## What are the possible ways of Dependency Injection? 102 | + Constructor-Based Dependency Injection; 103 | + Setter-Based Dependency Injection; 104 | + Field-Based Dependency Injection; 105 | ###### Relative links: 106 | + https://www.baeldung.com/inversion-control-and-dependency-injection-in-spring 107 | + https://www.javacodegeeks.com/2019/02/field-setter-constructor-injection.html 108 | 109 | ## Where better to use dependency injection via constructor? Where via setter? 110 | + required dependencies via constructor; 111 | + optional dependencies via setter; 112 | ###### Relative links: 113 | + https://www.dariawan.com/tutorials/spring/constructor-vs-setter-dependency-injection/ 114 | 115 | ## How to catch the exceptions for controllers? 116 | ***ExceptionHandler*** is a Spring annotation that provides a mechanism to treat exceptions that are thrown during execution of handlers (Controller operations). This annotation, if used on methods of controller classes, will serve as the entry point for handling exceptions thrown within this controller only. Altogether, the most common way is to use @ExceptionHandler on methods of @ControllerAdvice classes so that the exception handling will be applied globally or to a subset of controllers. 117 | ###### Relative links: 118 | + https://www.toptal.com/java/spring-boot-rest-api-error-handling 119 | 120 | ## What is the difference between BeanFactory and FactoryBean? 121 | + The ***BeanFactory*** is an interface in Spring and is a factory class for managing beans. The BeanFactory is the core of the IOC container. The accusations include: instantiating, configuring objects in the application and establishing dependencies between them. The ApplicationContext is an advanced version of the BeanFactory. 122 | + ***FactoryBean*** is a way to customize the instantiation of the bean, through the implementation of the FactoryBean, complete the custom bean instantiation details. For example, the FactoryBean proxy object can be used to intercept all its methods to form AOP-like functions. Using FactoryBean avoids the need to configure various properties in the XML file, which is more flexible, but you need to encode the instantiation of the class in the implementation class of the FactoryBean. 123 | ###### Relative links: 124 | + http://www.programmersought.com/article/6987917473/ 125 | 126 | ## What is the difference Spring and Spring Boot? 127 | + Spring Boot does all of those using AutoConfiguration and will take care of all the internal dependencies that your application needs — all you need to do is run your application. Spring Boot will auto-configure with the Dispatcher Servlet, if Spring jar is in the class path. It will auto-configue to the datasource, if Hibernate jar is in the class path. Spring Boot gives us a pre-configured set of Starter Projects to be added as a dependency in our project. 128 | + During web-application development, we would need the jars that we want to use, which versions of the jars to use, and how to connect them together. All web applications have similar needs, for example, Spring MVC, Jackson Databind, Hibernate core, and Log4j (for logging). So, we had to choose the compatible versions of all these jars. In order to decrease the complexity, Spring Boot has introduced what we call Spring Boot Starters. 129 | ###### Relative links: 130 | + https://dzone.com/articles/understanding-the-basics-of-spring-vs-spring-boot 131 | + https://dzone.com/articles/spring-vs-spring-boot 132 | 133 | ## How to add own auto-configurations? 134 | + You need to opt-in to auto-configuration by adding the @EnableAutoConfiguration or @SpringBootApplication annotations to one of your @Configuration classes. 135 | + Spring Boot checks for the presence of a META-INF/spring.factories file within your published jar. The file should list your configuration classes under the EnableAutoConfiguration key, as shown in the following example: 136 | ###### Relative links: 137 | + https://www.baeldung.com/spring-boot-custom-auto-configuration 138 | + https://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-auto-configuration.html 139 | 140 | ## Where can be stored the list of auto-configurations in META-INF? 141 | META-INF/spring.factories 142 | ###### Relative links: 143 | + https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-developing-auto-configuration.html 144 | 145 | ## What are the possible ways of configurations in Spring? 146 | + xml-based configuration, when you describe configuration in xml file; 147 | + java-based configuration, when configuration is Java class, marked with specific annotations; 148 | + groovy-based configuration, when configuration is file with Groovy code; 149 | ###### Relative links: 150 | + https://stackoverflow.com/questions/35807056/how-many-ways-are-there-to-configure-the-spring-framework-what-are-the-differen 151 | 152 | ## What is the lookup method? 153 | The getter method will return us the reference that is been set but suppose you want a new instance of the dependent bean each time you invoke the getter method 154 | ###### Relative links: 155 | + https://www.javacodegeeks.com/2015/05/spring-lookup-method-example.html 156 | 157 | ## What is declarative transaction in Spring? 158 | 1. Allows us to manage transactions through configuration. 159 | 2. This means separating transaction logic with business logic. 160 | 3. We use annotations (Or XML files) to manage transactions. 161 | 4. Easy to maintain. Boilerplate is kept away from business logic. 162 | 5. Preferred when working with large amount of Transaction logic. 163 | ###### Relative links: 164 | + https://stackoverflow.com/questions/11222103/declarative-or-programmatic-transaction-in-spring 165 | 166 | ## What creates a proxy? 167 | After the bean instances are created they are run through a series of BeanPostProcessors - Based on the AOP advice, the proxies are created by a BeanPostProcessor called AnnotationAwareAspectJAutoProxyCreator (or possibly its subclasses) 168 | ###### Relative links: 169 | + https://stackoverflow.com/questions/12648394/when-does-spring-creates-proxies-in-the-beans-lifecycle 170 | + https://dzone.com/articles/spring-pitfalls-proxying 171 | + https://ntsim.uk/posts/a-closer-look-at-spring-proxies 172 | 173 | ## Does @transactional method work in the case of execution in the same class? 174 | The problem here is, that Spring's AOP proxies don't extend but rather wrap your service instance to intercept calls. This has the effect, that any call to "this" from within your service instance is directly invoked on that instance and cannot be intercepted by the wrapping proxy (the proxy is not even aware of any such call). 175 | ###### Relative links: 176 | + https://stackoverflow.com/questions/3423972/spring-transaction-method-call-by-the-method-within-the-same-class-does-not-wo 177 | 178 | ## What is environment? 179 | Interface representing the environment in which the current application is running. Models two key aspects of the application environment: profiles and properties. Methods related to property access are exposed via the PropertyResolver superinterface. 180 | 181 | A profile is a named, logical group of bean definitions to be registered with the container only if the given profile is active. Beans may be assigned to a profile whether defined in XML or via annotations; see the spring-beans 3.1 schema or the @Profile annotation for syntax details. The role of the Environment object with relation to profiles is in determining which profiles (if any) are currently active, and which profiles (if any) should be active by default. 182 | 183 | Properties play an important role in almost all applications, and may originate from a variety of sources: properties files, JVM system properties, system environment variables, JNDI, servlet context parameters, ad-hoc Properties objects, Maps, and so on. The role of the environment object with relation to properties is to provide the user with a convenient service interface for configuring property sources and resolving properties from them. 184 | ###### Relative links: 185 | - https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/core/env/Environment.html 186 | 187 | ## How does auto-configuration work? 188 | Under the hood, auto-configuration is implemented with standard @Configuration classes. Additional @Conditional annotations are used to constrain when the auto-configuration should apply. Usually, auto-configuration classes use @ConditionalOnClass and @ConditionalOnMissingBean annotations. This ensures that auto-configuration applies only when relevant classes are found and when you have not declared your own @Configuration. 189 | ###### Relative links: 190 | - https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-developing-auto-configuration.html 191 | 192 | ## What is the difference between @Resource and @Autowired annotations? 193 | - @Resource means get me a known resource by name. The name is extracted from the name of the annotated setter or field, or it is taken from the name-Parameter. 194 | - @Inject or @Autowired try to wire in a suitable other component by type. 195 | ###### Relative links: 196 | - https://stackoverflow.com/questions/4093504/resource-vs-autowired 197 | 198 | ## What is the feature in Spring Boot for setting up the dependencies? 199 | Spring Boot Starters is one of the major key features or components of Spring Boot Framework. The main responsibility of Spring Boot Starter is to combine a group of common or related dependencies into single dependencies. 200 | ###### Relative links: 201 | - https://www.journaldev.com/7989/key-components-and-internals-of-spring-boot-framework 202 | 203 | ## Where does Spring Boot application begin? 204 | Spring Boot application begins from dependency to Spring Boot Starter. 205 | ###### Relative links: 206 | - https://spring.io/guides/gs/spring-boot/ 207 | 208 | ## What is the difference between @Controller and @RestController annotations? 209 | The job of @Controller is to create a Map of model object and find a view but @RestController simply return the object and object data is directly written into HTTP response as JSON or XML. 210 | 211 | This can also be done with traditional @Controller and use @ResponseBody annotation but since this is the default behavior of RESTful Web services, Spring introduced @RestController which combined the behavior of @Controller and @ResponseBody together. 212 | ###### Relative links: 213 | - https://javarevisited.blogspot.com/2017/08/difference-between-restcontroller-and-controller-annotations-spring-mvc-rest.html#ixzz61TUwViPi 214 | 215 | ## Does @Qualifier annotation can work only with bean name from @Component annotation? 216 | @Qualifier annotation can be used on classes instead of specifying bean name in @Component annotation. 217 | ###### Relative links: 218 | - https://www.baeldung.com/spring-qualifier-annotation 219 | 220 | ## Is it required to put @Repository annotation in the case of extending JpaRepository? 221 | It is indeed not necessary to put the @Repository annotation on interfaces that extend JpaRepository; Spring recognises the repositories by the fact that they extend one of the predefined Repository interfaces. 222 | ###### Relative links: 223 | - https://stackoverflow.com/questions/44069367/repository-not-necessary-when-implementing-jparepository 224 | 225 | ## How ResponseEntity can be used? 226 | ResponseEntity is meant to represent the entire HTTP response. You can control anything that goes into it: status code, headers, and body. 227 | ###### Relative links: 228 | - https://stackoverflow.com/questions/26549379/when-use-responseentityt-and-restcontroller-for-spring-restful-applications 229 | 230 | ## Does entity from @Transactional method can be updated without executing save method? 231 | Yes, because hibernate will automatically detect changes made to persistent entities and update the database accordingly. 232 | ###### Relative links: 233 | - https://stackoverflow.com/questions/8190926/transactional-saves-without-calling-update-method 234 | 235 | ## Is it possible to have only one transaction in the case of executing several @Transactional methods? 236 | Yes, it depends on the propagation attribute. ***PROPAGATION_REQUIRED*** - the same transaction for both methods, ***PROPAGATION_REQUIRES_NEW*** starts a new transaction. 237 | ###### Relative links: 238 | - https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#tx-propagation 239 | 240 | ## Anti-patterns of bean validation? 241 | - Anti-Pattern #1: Validating Only in the Persistence Layer; 242 | - Anti-Pattern #2: Validating with a Shotgun; 243 | - Anti-Pattern #3: Using Validation Groups for Use Case Validations; 244 | ###### Relative links: 245 | - https://reflectoring.io/bean-validation-anti-patterns/ 246 | 247 | ## Is it good practice to define interface for Spring bean? 248 | ###### Relative links: 249 | - http://stackoverflow.com/questions/5288153/using-spring-to-wire-directly-a-concrete-class 250 | - https://octoperf.com/blog/2016/10/27/impl-classes-are-evil/ 251 | - https://dzone.com/articles/spring-pitfalls-proxying 252 | 253 | ## How does @Transactional annotation work? 254 | ###### Relative links: 255 | - https://www.marcobehler.com/guides/spring-transaction-management-transactional-in-depth 256 | 257 | ## How to use @NamedEntityGraph with Spring Data JPA? 258 | ###### Relative links: 259 | - https://www.baeldung.com/spring-data-jpa-named-entity-graphs 260 | 261 | [Home Page](README.md) 262 | -------------------------------------------------------------------------------- /sql.md: -------------------------------------------------------------------------------- 1 | #SQL 2 | - [What is having in sql?](#what-is-having-in-sql) 3 | - [What are the possible issues with indexes?](#what-are-the-possible-issues-with-indexes) 4 | - [Sql works very slowly, what are the possible improvements (the database is MySQL, for example)?](#sql-works-very-slowly-what-are-the-possible-improvements-the-database-is-mysql-for-example) 5 | - [NoSQL vs SQL Databases](#nosql-vs-sql-databases) 6 | - [OLAP vs OLTP Databases](#olap-vs-oltp-databases) 7 | 8 | ## What is having in sql? 9 | + HAVING filters records that work on summarized GROUP BY results. 10 | + HAVING applies to summarized group records, whereas WHERE applies to individual records. 11 | + Only the groups that meet the HAVING criteria will be returned. 12 | + HAVING requires that a GROUP BY clause is present. 13 | + WHERE and HAVING can be in the same query. 14 | ###### Relative links: 15 | + https://www.dofactory.com/sql/having 16 | 17 | ## What are the possible issues with indexes? 18 | Although indexes are intended to enhance a database's performance, there are times when they should be avoided. 19 | + The following guidelines indicate when the use of an index should be reconsidered. 20 | + Indexes should not be used on small tables. 21 | + Tables that have frequent, large batch updates or insert operations. 22 | + Indexes should not be used on columns that contain a high number of NULL values. 23 | + Columns that are frequently manipulated should not be indexed. 24 | ###### Relative links: 25 | + https://www.tutorialspoint.com/sql/sql-indexes.htm 26 | 27 | ## Sql works very slowly, what are the possible improvements (the database is MySQL, for example)? 28 | 1. Index All Columns Used in 'where', 'order by', and 'group by' Clauses 29 | 2. Optimize Like Statements With Union Clause 30 | 3. Avoid Like Expressions With Leading Wildcards 31 | 4. Take Advantage of MySQL Full-Text Searches 32 | 5. Optimize Your Database Schema 33 | 6. MySQL Query Caching 34 | ###### Relative links: 35 | - https://dzone.com/articles/how-to-optimize-mysql-queries-for-speed-and-perfor 36 | 37 | ## NoSQL vs SQL Databases 38 | ###### Relative links: 39 | - https://www.mongodb.com/nosql-explained/nosql-vs-sql 40 | 41 | ## OLAP vs OLTP Databases 42 | ###### Relative links: 43 | - https://www.ibm.com/cloud/blog/olap-vs-oltp 44 | 45 | [Home Page](README.md) 46 | -------------------------------------------------------------------------------- /test.md: -------------------------------------------------------------------------------- 1 | #Test 2 | - [What is the difference between integration and unit tests?](#what-is-the-difference-between-integration-and-unit-tests) 3 | - [Unit test executes code from 2 classes, is it correct? Is it unit or integration test?](#unit-test-executes-code-from-2-classes-is-it-correct-is-it-unit-or-integration-test) 4 | - [What can be used for unit tests?](#what-can-be-used-for-unit-tests) 5 | - [What is better to use randomized or hardcode data for unit tests?](#what-is-better-to-use-randomized-or-hardcode-data-for-unit-tests) 6 | - [Is it possible to test the architecture of application?](#is-it-possible-to-test-the-architecture-of-application) 7 | - [Does TDD include integration tests?](#does-tdd-include-integration-tests) 8 | - [Is it good practice to check in tests that non-state-changing methods were called?](#is-it-good-practice-to-check-in-tests-that-non-state-changing-methods-were-called) 9 | - [The differences between Spy and Mock in Mockito?](#the-differences-between-spy-and-mock-in-mockito) 10 | - [Is it good practice to use in-memory db for tests?](#is-it-good-practice-to-use-in-memory-db-for-tests) 11 | - [Mockito: doReturn vs thenReturn?](#mockito-doreturn-vs-thenreturn) 12 | - [How would you assess the quality and effectiveness of unit tests in a Java codebase? Can you explain what mutation testing is and how tools like PIT can help?](#how-would-you-assess-the-quality-and-effectiveness-of-unit-tests-in-a-java-codebase-can-you-explain-what-mutation-testing-is-and-how-tools-like-pit-can-help) 13 | 14 | ## What is the difference between integration and unit tests? 15 | A ***unit test*** is a test written by the programmer to verify that a relatively small piece of code is doing what it is intended to do. They are narrow in scope, they should be easy to write and execute, and their effectiveness depends on what the programmer considers to be useful. The tests are intended for the use of the programmer, they are not directly useful to anybody else, though, if they do their job, testers and users downstream should benefit from seeing fewer bugs. 16 | 17 | Part of being a unit test is the implication that things outside the code under test are mocked or stubbed out. Unit tests shouldn't have dependencies on outside systems. They test internal consistency as opposed to proving that they play nicely with some outside system. 18 | 19 | An ***integration test*** is done to demonstrate that different pieces of the system work together. Integration tests can cover whole applications, and they require much more effort to put together. They usually require resources like database instances and hardware to be allocated for them. The integration tests do a more convincing job of demonstrating the system works (especially to non-programmers) than a set of unit tests can, at least to the extent the integration test environment resembles production. 20 | 21 | Actually "integration test" gets used for a wide variety of things, from full-on system tests against an environment made to resemble production to any test that uses a resource (like a database or queue) that isn't mocked out. At the lower end of the spectrum an integration test could be a junit test where a repository is exercised against an in-memory database, toward the upper end it could be a system test verifying applications can exchange messages. 22 | ###### Relative links: 23 | - https://stackoverflow.com/questions/5357601/whats-the-difference-between-unit-tests-and-integration-tests 24 | 25 | ## Unit test executes code from 2 classes, is it correct? Is it unit or integration test? 26 | In general, I would say that it's unit tests but with requirements: 27 | - test executes the logic from one module; 28 | - test checks only one scenario (in the nested execution there is no branching). 29 | 30 | ## What can be used for unit tests? 31 | **JUnit** and **TestNG** are the main unit test frameworks. 32 | ###### Relative links: 33 | - https://stackoverflow.com/questions/4055957/what-are-the-unit-testing-frameworks-available-in-java 34 | 35 | ## What is better to use randomized or hardcode data for unit tests? 36 | Avoid randomized data as it can lead to toggling tests which can be hard to debug and omit error messages that make tracing the error back to the code harder. 37 | 38 | Instead, use fixed values for everything. They will create highly reproducible tests, which are easy to debug and create error messages that can be easily traced back to the relevant line of code. 39 | ###### Relative links: 40 | - https://phauer.com/2019/modern-best-practices-testing-java/ 41 | 42 | ## Is it possible to test the architecture of application? 43 | Yes, ArchUnit as example. It does not test your code flow or business logic. The library lets you test your “architecture” including class dependencies, cyclic dependencies, layer accesses, naming conventions, and inheritance checking. 44 | ###### Relative links: 45 | - https://www.freecodecamp.org/news/java-archunit-testing-the-architecture-a09f089585be/ 46 | - https://github.com/TNG/ArchUnit 47 | 48 | ## Does TDD include integration tests? 49 | ###### Relative links: 50 | - https://stackoverflow.com/questions/18988040/does-tdd-include-integration-tests 51 | 52 | ## Is it good practice to check in tests that non-state-changing methods were called? 53 | ###### Relative links: 54 | - https://testing.googleblog.com/2017/12/testing-on-toilet-only-verify-state.html 55 | 56 | ## The differences between Spy and Mock in Mockito? 57 | When Mockito creates a mock – it does so from the Class of a Type, not from an actual instance. The mock simply creates a bare-bones shell instance of the Class, entirely instrumented to track interactions with it. 58 | 59 | On the other hand, the spy will wrap an existing instance. It will still behave in the same way as the normal instance – the only difference is that it will also be instrumented to track all the interactions with it. 60 | ###### Relative links: 61 | - https://www.baeldung.com/mockito-spy 62 | 63 | ## Is it good practice to use in-memory db for tests? 64 | ###### Relative links: 65 | - https://phauer.com/2017/dont-use-in-memory-databases-tests-h2/ 66 | 67 | ## Mockito doReturn vs thenReturn? 68 | ###### Relative links: 69 | - http://sangsoonam.github.io/2019/02/04/mockito-doreturn-vs-thenreturn.html 70 | 71 | ## How would you assess the quality and effectiveness of unit tests in a Java codebase? Can you explain what mutation testing is and how tools like PIT can help? 72 | One effective way to assess the quality of unit tests in Java is through **mutation testing**, which checks whether tests can detect intentional defects. A commonly used tool for this is **PIT (Pitest)**. PIT works by introducing small changes (mutations) to the production code—like flipping conditions or modifying operators—and then running the existing tests. If the tests fail, the mutation is “killed.” If not, it indicates a possible gap in the test’s effectiveness. This approach goes beyond traditional code coverage, focusing on how well tests catch real issues. 73 | ###### Relative links: 74 | - https://pitest.org/ 75 | 76 | [Home Page](README.md) 77 | -------------------------------------------------------------------------------- /transaction.md: -------------------------------------------------------------------------------- 1 | #Transactions 2 | - [What is transaction?](#what-is-transaction) 3 | - [What are the requirements for transactions?](#what-are-the-requirements-for-transactions) 4 | - [What is a distributed transaction?](#what-is-a-distributed-transaction) 5 | - [What are isolation levels?](#what-are-isolation-levels) 6 | - [What are the possible issues in the case of parallel access by transactions?](#what-are-the-possible-issues-in-the-case-of-parallel-access-by-transactions) 7 | - [What are possible options for implementing transactions in microservices](#what-are-possible-options-for-implementing-transactions-in-microservices) 8 | - [What is the difference between optimistic and pessimistic locking?](#what-is-the-difference-between-optimistic-and-pessimistic-locking) 9 | - [Is it possible to use transaction for select statements?](#is-it-possible-to-use-transaction-for-select-statements) 10 | - [What locks are made in the case of using Repeatable Read isolation level?](#what-locks-are-made-in-the-case-of-using-repeatable-read-isolation-level) 11 | 12 | ## What is transaction? 13 | A **transaction** is a sequence of operations performed (using one or more SQL statements) on a database as a single logical unit of work. The effects of all the SQL statements in a transaction can be either all committed (applied to the database) or all rolled back (undone from the database). A database transaction must be atomic, consistent, isolated and durable. 14 | ###### Relative links: 15 | + https://www.w3resource.com/sql/controlling-transactions.php 16 | 17 | ## What are the requirements for transactions? 18 | - ***Atomic:*** A transaction is a logical unit of work which must be either completed with all of its data modifications, or none of them is performed. 19 | - ***Consistent:*** At the end of the transaction, all data must be left in a consistent state. 20 | - ***Isolated:*** Modifications of data performed by a transaction must be independent of another transaction. Unless this happens, the outcome of a transaction may be erroneous. 21 | - ***Durable:*** When the transaction is completed, effects of the modifications performed by the transaction must be permanent in the system. 22 | ###### Relative links: 23 | - https://www.w3resource.com/sql/controlling-transactions.php 24 | - https://github.com/enhorse/java-interview/blob/master/db.md#%D0%BD%D0%B0%D0%B7%D0%BE%D0%B2%D0%B8%D1%82%D0%B5-%D0%BE%D1%81%D0%BD%D0%BE%D0%B2%D0%BD%D1%8B%D0%B5-%D1%81%D0%B2%D0%BE%D0%B9%D1%81%D1%82%D0%B2%D0%B0-%D1%82%D1%80%D0%B0%D0%BD%D0%B7%D0%B0%D0%BA%D1%86%D0%B8%D0%B8 25 | - https://habr.com/ru/post/446662/ 26 | - https://vladmihalcea.com/a-beginners-guide-to-acid-and-database-transactions/ 27 | 28 | ## What is a distributed transaction? 29 | **Distributed transactions** span multiple physical systems, whereas standard transactions do not. Synchronization amongst the systems becomes a need which traditionally would not exist in a standard transaction. 30 | ###### Relative links: 31 | - https://stackoverflow.com/questions/4217270/what-is-a-distributed-transaction 32 | 33 | ## What are isolation levels? 34 | - ***Read Uncommitted*** – Read Uncommitted is the lowest isolation level. In this level, one transaction may read not yet committed changes made by other transaction, thereby allowing dirty reads. In this level, transactions are not isolated from each other. 35 | - ***Read Committed*** – This isolation level guarantees that any data read is committed at the moment it is read. Thus it does not allows dirty read. The transaction holds a read or write lock on the current row, and thus prevent other transactions from reading, updating or deleting it. 36 | - ***Repeatable Read*** – This is the most restrictive isolation level. The transaction holds read locks on all rows it references and writes locks on all rows it inserts, updates, or deletes. Since other transaction cannot read, update or delete these rows, consequently it avoids non-repeatable read. 37 | - ***Serializable*** – This is the Highest isolation level. A serializable execution is guaranteed to be serializable. Serializable execution is defined to be an execution of operations in which concurrently executing transactions appears to be serially executing. 38 | ###### Relative links: 39 | + https://www.geeksforgeeks.org/transaction-isolation-levels-dbms/ 40 | 41 | ## What are the possible issues in the case of parallel access by transactions? 42 | - ***Dirty Read*** – A Dirty read is the situation when a transaction reads a data that has not yet been committed. For example, Let’s say transaction 1 updates a row and leaves it uncommitted, meanwhile, Transaction 2 reads the updated row. If transaction 1 rolls back the change, transaction 2 will have read data that is considered never to have existed. 43 | - ***Non Repeatable read*** – Non Repeatable read occurs when a transaction reads same row twice, and get a different value each time. For example, suppose transaction T1 reads data. Due to concurrency, another transaction T2 updates the same data and commit, Now if transaction T1 rereads the same data, it will retrieve a different value. 44 | - ***Phantom Read*** – Phantom Read occurs when two same queries are executed, but the rows retrieved by the two, are different. For example, suppose transaction T1 retrieves a set of rows that satisfy some search criteria. Now, Transaction T2 generates some new rows that match the search criteria for transaction T1. If transaction T1 re-executes the statement that reads the rows, it gets a different set of rows this time. 45 | ###### Relative links: 46 | + https://www.geeksforgeeks.org/transaction-isolation-levels-dbms/ 47 | 48 | ## What are possible options for implementing transactions in microservices 49 | - ***Distributed transaction.*** A distributed transaction is a very complex process with a lot of moving parts that can fail. Also, if these parts run on different machines or even in different data centers, the process of committing a transaction could become very long and unreliable. 50 | - ***Two-Phase Commit Protocol.*** The problem with 2PC is that it is quite slow compared to the time for operation of a single microservice. Coordinating the transaction between microservices, even if they are on the same network, can really slow the system down. 51 | - ***Eventual Consistency and Compensation.*** By far, one of the most feasible models of handling consistency across microservices is eventual consistency. One way to solve it would be with a message-driven approach including compensation. The messaging platform could ensure that the messages sent by the microservices are persisted. Then they would be delivered at a later time if the receiver weren’t currently available 52 | ###### Relative links: 53 | + https://www.baeldung.com/transactions-across-microservices 54 | + https://habr.com/ru/company/nixsolutions/blog/321686/ 55 | + https://habr.com/ru/company/nixsolutions/blog/322214/ 56 | 57 | ## What is the difference between optimistic and pessimistic locking? 58 | + ***Optimistic Locking*** is a strategy where you read a record, take note of a version number (other methods to do this involve dates, timestamps or checksums/hashes) and check that the version hasn't changed before you write the record back. When you write the record back you filter the update on the version to make sure it's atomic. (i.e. hasn't been updated between when you check the version and write the record to the disk) and update the version in one hit. 59 | + ***Pessimistic Locking*** is when you lock the record for your exclusive use until you have finished with it. It has much better integrity than optimistic locking but requires you to be careful with your application design to avoid Deadlocks. To use pessimistic locking you need either a direct connection to the database (as would typically be the case in a two tier client server application) or an externally available transaction ID that can be used independently of the connection. 60 | ###### Relative links: 61 | + https://stackoverflow.com/questions/129329/optimistic-vs-pessimistic-locking 62 | 63 | ## Is it possible to use transaction for select statements? 64 | In a highly concurrent application it could (theoretically) happen that data you've read in the first select is modified before the other selects are executed. 65 | 66 | If that is a situation that could occur in your application you should use a transaction to wrap your selects. 67 | ###### Relative links: 68 | + https://stackoverflow.com/questions/5982517/use-transactions-for-select-statements 69 | 70 | ## What locks are made in the case of using Repeatable Read isolation level? 71 | The transaction holds read locks on all rows it references and writes locks on all rows it inserts, updates, or deletes. Since other transaction cannot read, update or delete these rows, consequently it avoids non-repeatable read. 72 | 73 | [Home Page](README.md) 74 | --------------------------------------------------------------------------------