<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Be You on Medium]]></title>
        <description><![CDATA[Stories by Be You on Medium]]></description>
        <link>https://medium.com/@priyankalovesgaurav004?source=rss-7f8ef520f5f9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*SZ-dLLt2Xk0WQ47I</url>
            <title>Stories by Be You on Medium</title>
            <link>https://medium.com/@priyankalovesgaurav004?source=rss-7f8ef520f5f9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 08:37:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@priyankalovesgaurav004/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Spring Interview Ques]]></title>
            <link>https://medium.com/@priyankalovesgaurav004/spring-interview-ques-394df9bda2ba?source=rss-7f8ef520f5f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/394df9bda2ba</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java-interview-questions]]></category>
            <category><![CDATA[spring-framework]]></category>
            <dc:creator><![CDATA[Be You]]></dc:creator>
            <pubDate>Tue, 25 Jun 2024 11:11:59 GMT</pubDate>
            <atom:updated>2024-06-25T11:11:59.200Z</atom:updated>
            <content:encoded><![CDATA[<h3>Spring Interview Questions</h3><h3>Spring Boot questions</h3><h3>What Is Spring Boot and What Are Its Main Features?</h3><p>Spring Boot is essentially a framework for rapid application development built on top of the Spring Framework. With its auto-configuration and embedded application server support, combined with the extensive documentation and community support it enjoys, Spring Boot is one of the most popular technologies in the Java ecosystem as of date.</p><p>Here are a few salient features:</p><ul><li>Starters — a set of dependency descriptors to include relevant dependencies at a go</li><li>Auto-configuration — a way to automatically configure an application based on the dependencies present on the classpath</li><li>Actuator — to get production-ready features such as monitoring</li><li>Security</li><li>Logging</li></ul><h3>What Are the Differences Between Spring and Spring Boot?</h3><p>The Spring Framework provides multiple features that make the development of web applications easier. These features include dependency injection, data binding, aspect-oriented programming, data access and many more.</p><p>Over the years, Spring has been growing more and more complex, and the amount of configuration such application requires can be intimidating. This is where Spring Boot comes in handy — it makes configuring a Spring application a breeze.</p><p>Essentially, while Spring is unopinionated, Spring Boot takes an opinionated view of the platform and libraries, letting us get started quickly.</p><p>Here are two of the most important benefits Spring Boot brings in:</p><ul><li>Auto-configure applications based on the artifacts it finds on the classpath</li><li>Provide non-functional features common to applications in production, such as security or health checks</li></ul><h3>How to Disable a Specific Auto-Configuration?</h3><p>If we want to disable a specific auto-configuration, we can indicate it using the exclude attribute of the @EnableAutoConfiguration annotation.</p><p>For instance, this code snippet neutralizes DataSourceAutoConfiguration:</p><pre>// other annotations<br>@EnableAutoConfiguration(exclude = DataSourceAutoConfiguration.class)<br>public class MyConfiguration { }</pre><p>We can also disable an auto-configuration with the spring.autoconfigure.exclude environment property. This setting in the application.properties file does the same thing as before:</p><pre>spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration</pre><h3>How to Use Spring Boot for Command-Line Applications?</h3><p>Just like any other Java program, a Spring Boot command-line application must have a main method.</p><p>This method serves as an entry point, which invokes the SpringApplication#run method to bootstrap the application:</p><pre>@SpringBootApplication<br>public class MyApplication {<br>    public static void main(String[] args) {<br>        SpringApplication.run(MyApplication.class);<br>        // other statements<br>    }<br>}</pre><p>The SpringApplication class then fires up a Spring container and auto-configures beans.</p><p>Notice we must pass a configuration class to the run method to work as the primary configuration source. By convention, this argument is the entry class itself.</p><p>After calling the run method, we can execute other statements as in a regular program.</p><h3>What Are Possible Sources of External Configuration?</h3><p>Spring Boot provides support for external configuration, allowing us to run the same application in various environments. We can use properties files, YAML files, environment variables, system properties and command-line option arguments to specify configuration properties.</p><p>We can then gain access to those properties using the @Value annotation, a bound object via the @ConfigurationProperties annotation, or the Environment abstraction.</p><h3>What Does It Mean That Spring Boot Supports Relaxed Binding?</h3><p>Relaxed binding in Spring Boot is applicable to the type-safe binding of configuration properties.</p><p>With relaxed binding, the key of a property doesn’t need to be an exact match of a property name. Such an environment property can be written in camelCase, kebab-case, snake_case, or in uppercase with words separated by underscores.</p><p>For example, if a property in a bean class with the @ConfigurationProperties annotation is named myProp, it can be bound to any of these environment properties: myProp, my-prop, my_prop, or MY_PROP.</p><h3>How to Write Integration Tests?</h3><p>When running integration tests for a Spring application, we must have an ApplicationContext.</p><p>To make our life easier, Spring Boot provides a special annotation for testing — @SpringBootTest. This annotation creates an ApplicationContext from configuration classes indicated by its classes attribute.</p><p>In case the classes attribute isn’t set, Spring Boot searches for the primary configuration class. The search starts from the package containing the test until it finds a class annotated with @SpringBootApplication or @SpringBootConfiguration.</p><h3>What Is Spring Boot Actuator Used For?</h3><p>Essentially, Actuator brings Spring Boot applications to life by enabling production-ready features. These features allow us to monitor and manage applications when they’re running in production.</p><p>Here are some of the most common built-in endpoints Actuator provides:</p><ul><li>env exposes environment properties</li><li>health shows application health information</li><li>httptrace displays HTTP trace information</li><li>info displays arbitrary application information</li><li>metrics shows metrics information</li><li>loggers shows and modifies the configuration of loggers in the application</li><li>mappings displays a list of all @RequestMapping paths</li></ul><h3>What Basic Annotations Does Spring Boot Offer?</h3><p>The primary annotations that Spring Boot offers reside in its org.springframework.boot.autoconfigure and its sub-packages.</p><p>Here are a couple of basic ones:</p><ul><li>@EnableAutoConfiguration — to make Spring Boot look for auto-configuration beans on its classpath and automatically apply them</li><li>@SpringBootApplication — to denote the main class of a Boot Application. This annotation combines @Configuration, @EnableAutoConfiguration and @ComponentScan annotations with their default attributes.</li></ul><h3>Which Embedded Servers Does Spring Boot Support, and How to Change the Default?</h3><p>As of date, Spring MVC supports Tomcat, Jetty and Undertow. Tomcat is the default application server supported by Spring Boot’s web starter.</p><p>Spring WebFlux supports Reactor Netty, Tomcat, Jetty and Undertow with Reactor Netty as default.</p><p>In Spring MVC, to change the default, let’s say to Jetty, we need to exclude Tomcat and include Jetty in the dependencies.</p><h3>Spring Core</h3><h3>What Spring Sub-Projects Do You Know? Describe Them Briefly.</h3><ul><li>Core — a key module that provides fundamental parts of the framework, such as IoC or DI</li><li>JDBC — enables a JDBC-abstraction layer that removes the need to do JDBC coding for specific vendor databases</li><li>ORM integration — provides integration layers for popular object-relational mapping APIs, such as JPA, JDO and Hibernate</li><li>Web — a web-oriented integration module that provides multipart file upload, Servlet listeners and web-oriented application context functionalities</li><li>MVC framework — a web module implementing the Model View Controller design pattern</li><li>AOP module — aspect-oriented programming implementation allowing the definition of clean method-interceptors and pointcuts</li></ul><h3>What Is Dependency Injection?</h3><p>Dependency injection, an aspect of Inversion of Control (IoC), is a general concept stating that we do not create our objects manually but instead describe how they should be created. Then an IoC container will instantiate required classes if needed.</p><h3>How Can We Inject Beans in Spring?</h3><p>A few different options exist in order to inject Spring beans:</p><ul><li>Setter injection</li><li>Constructor injection</li><li>Field injection The configuration can be done using XML files or annotations.</li></ul><h3>Which Is the Best Way of Injecting Beans and Why?</h3><p>The recommended approach is to use constructor arguments for mandatory dependencies and setters for optional ones. This is because constructor injection allows injecting values to immutable fields and makes testing easier.</p><h3>What Is a Spring Bean?</h3><p>The Spring Beans are Java Objects that are initialized by the Spring IoC container.</p><h3>What Is the Default Bean Scope in Spring Framework?</h3><p>By default, a Spring Bean is initialized as a singleton.</p><h3>How to Define the Scope of a Bean?</h3><p>In order to set Spring Bean’s scope, we can use @Scope annotation or “scope” attribute in XML configuration files. Note that there are five supported scopes:</p><ul><li>Singleton</li><li>Prototype</li><li>Request</li><li>Session</li><li>Global-session</li></ul><h3>Are Singleton Beans Thread-Safe?</h3><p>No, singleton beans are not thread-safe, as thread safety is about execution, whereas the singleton is a design pattern focusing on creation. Thread safety depends only on the bean implementation itself.</p><h3>What Does the Spring Bean Life Cycle Look Like?</h3><p>First, a Spring bean needs to be instantiated based on Java or XML bean definition. It may also be required to perform some initialization to get it into a usable state. After that, when the bean is no longer required, it will be removed from the IoC container.</p><p>The whole cycle with all initialization methods is shown in the image</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/0*B-lxjnuLj7f28UYJ.jpg" /></figure><h3>What Is Spring Security?</h3><p>Spring Security is a separate module of the Spring framework that focuses on providing authentication and authorization methods in Java applications. It also takes care of most of the common security vulnerabilities such as CSRF attacks.</p><p>To use Spring Security in web applications, we can get started with the simple annotation @EnableWebSecurity.</p><h3>Name Some of the Design Patterns Used in the Spring Framework?</h3><ul><li>Singleton Pattern — singleton-scoped beans</li><li>Factory Pattern — Bean Factory classes</li><li>Prototype Pattern — prototype-scoped beans</li><li>Adapter Pattern — Spring Web and Spring MVC</li><li>Proxy Pattern — Spring Aspect-Oriented Programming support</li><li>Template Method Pattern — JdbcTemplate, HibernateTemplate, etc.</li><li>Front Controller — Spring MVC DispatcherServlet</li><li>Data Access Object — Spring DAO support</li><li>Model View Controller — Spring MVC</li></ul><h3>What Is the Role of the @Autowired Annotation?</h3><p>The @Autowired annotation can be used with fields or methods for injecting a bean by type. This annotation allows Spring to resolve and inject collaborating beans into your bean.</p><h3>What Is the Role of the @Qualifier Annotation?</h3><p>It is used simultaneously with the @Autowired annotation to avoid confusion when multiple instances of a bean type are present.</p><h3>What’s the Difference Between @Controller, @Component, @Repository, and @Service Annotations in Spring?</h3><ul><li>@Controller — indicates that the class serves the role of a controller, and detects @RequestMapping annotations within the class</li><li>@Service — indicates that the class holds business logic and calls methods in the repository layer</li><li>@Repository — indicates that the class defines a data repository; its job is to catch platform-specific exceptions and re-throw them as one of Spring’s unified unchecked exceptions</li></ul><h3>Spring Web MVC</h3><h3>What Is a Controller in Spring MVC?</h3><p>Simply put, all the requests processed by the DispatcherServlet are directed to classes annotated with @Controller. Each controller class maps one or more requests to methods that process and execute the requests with provided inputs.</p><h3>How Does the @RequestMapping Annotation Work?</h3><p>The @RequestMapping annotation is used to map web requests to Spring Controller methods. In addition to simple use cases, we can use it for mapping of HTTP headers, binding parts of the URI with @PathVariable, and working with URI parameters and the @RequestParam annotation.</p><h3>Explain the Difference Between @Controller and @RestController?</h3><p>The main difference between the @Controller and @RestController annotations is that the @ResponseBody annotation is automatically included in the @RestController. This means that we don’t need to annotate our handler methods with the @ResponseBody. We need to do this in a @Controller class if we want to write response type directly to the HTTP response body.</p><h3>Describe a PathVariable</h3><p>We can use the @PathVariable annotation as a handler method parameter in order to extract the value of a URI template variable.</p><p>For example, if we want to fetch a user by id from the <a href="http://www.mysite.com/user/123">www.mysite.com/user/123</a>, we should map our method in the controller as /user/{id}:</p><pre>@RequestMapping(&quot;/user/{id}&quot;)<br>public String handleRequest(@PathVariable(&quot;id&quot;) String userId, Model map) {}</pre><p>The @PathVariable has only one element named value. It’s optional and we use it to define the URI template variable name. If we omit the value element, then the URI template variable name must match the method parameter name.</p><p>It’s also allowed to have multiple @PathVariable annotations, either by declaring them one after another:</p><pre>@RequestMapping(&quot;/user/{userId}/name/{userName}&quot;)<br>public String handleRequest(@PathVariable String userId,<br>  @PathVariable String userName, Model map) {}</pre><p>or putting them all in a Map&lt;String, String&gt; or MultiValueMap&lt;String, String&gt;:</p><pre>@RequestMapping(&quot;/user/{userId}/name/{userName}&quot;)<br>public String handleRequest(@PathVariable Map&lt;String, String&gt; varsMap, Model map) {}</pre><p>varsMap, Model map) {}” tabindex=”0&quot; role=”button” style=”box-sizing: border-box; position: relative; display: flex !important; padding: 0px !important; font-size: 14px; font-weight: var( — base-text-weight-medium, 500); line-height: 20px; white-space: nowrap; vertical-align: middle; cursor: pointer; user-select: none; border: 0px; border-radius: 6px; appearance: none; color: var( — fgColor-accent, var( — color-accent-fg)); background-color: transparent; box-shadow: none; transition: color 80ms cubic-bezier(0.33, 1, 0.68, 1) 0s, background-color, box-shadow, border-color; justify-content: center !important; align-items: center !important; margin: var( — base-size-8, 8px) !important; width: var( — control-small-size, 28px); height: var( — control-small-size, 28px);”&gt;</p><h3>Validation Using Spring MVC</h3><p>Spring MVC supports JSR-303 specifications by default. We need to add JSR-303 and its implementation dependencies to our Spring MVC application. Hibernate Validator, for example, is one of the JSR-303 implementations at our disposal.</p><p>JSR-303 is a specification of the Java API for bean validation, part of Jakarta EE and JavaSE, which ensures that properties of a bean meet specific criteria, using annotations such as @NotNull, @Min, and @Max.</p><p>Spring offers the @Validator annotation and the BindingResult class. The Validator implementation will raise errors in the controller request handler method when we have invalid data. Then we may use the BindingResult class to get those errors.</p><h3>What Are the @RequestBody and the @ResponseBody Annotations?</h3><p>The @RequestBody annotation, used as a handler method parameter, binds the HTTP Request body to a transfer or a domain object. Spring automatically deserializes incoming HTTP Request to the Java object using Http Message Converters.</p><p>When we use the @ResponseBody annotation on a handler method in the Spring MVC controller, it indicates that we’ll write the return type of the method directly to the HTTP response body. We’ll not put it in a Model, and Spring won’t interpret as a view name.</p><h3>What Is the BindingResult?</h3><p>BindingResult is an interface from org.springframework.validation package that represents binding results. We can use it to detect and report errors in the submitted form. It’s easy to invoke — we just need to ensure that we put it as a parameter right after the form object we’re validating. The optional Model parameter should come after the BindingResult, as it can be seen in the custom validator tutorial:</p><pre>@PostMapping(&quot;/user&quot;)<br>public String submitForm(@Valid NewUserForm newUserForm, <br>  BindingResult result, Model model) {<br>    if (result.hasErrors()) {<br>        return &quot;userHome&quot;;<br>    }<br>    model.addAttribute(&quot;message&quot;, &quot;Valid form&quot;);<br>    return &quot;userHome&quot;;<br>}</pre><p>When Spring sees the @Valid annotation, it’ll first try to find the validator for the object being validated.</p><h3>Spring Data Access</h3><h3>What Is Spring JdbcTemplate Class and How to Use It?</h3><p>The Spring JDBC template is the primary API through which we can access database operations logic that we’re interested in:</p><p>Creation and closing of connections Executing statements and stored procedure calls Iterating over the ResultSet and returning results In order to use it, we’ll need to define the simple configuration of DataSource:</p><pre>@Configuration<br>@ComponentScan(&quot;org.baeldung.jdbc&quot;)<br>public class SpringJdbcConfig {<br>    @Bean<br>    public DataSource mysqlDataSource() {<br>        DriverManagerDataSource dataSource = new DriverManagerDataSource();<br>        dataSource.setDriverClassName(&quot;com.mysql.jdbc.Driver&quot;);<br>        dataSource.setUrl(&quot;jdbc:mysql://localhost:3306/springjdbc&quot;);<br>        dataSource.setUsername(&quot;guest_user&quot;);<br>        dataSource.setPassword(&quot;guest_password&quot;);<br> <br>        return dataSource;<br>    }<br>}</pre><h3>How to Enable Transactions in Spring and What Are Their Benefits?</h3><p>There are two distinct ways to configure Transactions — with annotations or by using Aspect-Oriented Programming (AOP) — each with their advantages.</p><p>Here are the benefits of using Spring Transactions, according to the official docs:</p><ul><li>Provide a consistent programming model across different transaction APIs such as JTA, JDBC, Hibernate, JPA and JDO</li><li>Support declarative transaction management</li><li>Provide a simpler API for programmatic transaction management than some complex transaction APIs such as JTA</li><li>Integrate very well with Spring’s various data access abstractions</li></ul><h3>What Is Spring DAO?</h3><p>Spring Data Access Object (DAO) is Spring’s support provided to work with data access technologies like JDBC, Hibernate and JPA in a consistent and easy way.</p><h3>Spring Reactive</h3><h3>What Is Reactive Programming?</h3><p>Reactive programming is about non-blocking, event-driven applications that scale with a small number of threads, with back pressure being a key ingredient that aims to ensure producers don’t overwhelm consumers.</p><p>These are the primary benefits of reactive programming:</p><ul><li>Increased utilization of computing resources on multicore and multi-CPU hardware</li><li>Increased performance by reducing serialization</li><li>Reactive programming is generally event-driven, in contrast to reactive systems, which are message-driven. So, using reactive programming does not mean we’re building a reactive system, which is an architectural style.</li></ul><p>However, reactive programming may be used as a means to implement reactive systems if we follow the Reactive Manifesto, which is quite vital to understand.</p><p>Based on this, reactive systems have four important characteristics:</p><ul><li>Responsive — The system should respond in a timely manner.</li><li>Resilient — In case the system faces any failure, it should stay responsive.</li><li>Elastic — Reactive systems can react to changes and stay responsive under varying workload.</li><li>Message-driven — Reactive systems need to establish a boundary between components by relying on asynchronous message passing.</li></ul><h3>What Is Spring WebFlux?</h3><p>Spring WebFlux is Spring’s reactive-stack web framework, and it’s an alternative to Spring MVC. In order to achieve this reactive model and be highly scalable, the entire stack is non-blocking.</p><h3>What Are the Mono and Flux Types?</h3><p>The WebFlux framework in Spring Framework 5 uses Reactor as its async foundation.</p><p>This project provides two core types: Mono to represent a single async value and Flux to represent a stream of async values. They both also implement the Publisher interface defined in the Reactive Streams specification.</p><p>Mono implements Publisher and returns 0 or 1 elements:</p><pre>public abstract class Mono&lt;T&gt; implements Publisher&lt;T&gt; {...}</pre><p>implements Publisher {…}” tabindex=”0&quot; role=”button” style=”box-sizing: border-box; position: relative; display: flex !important; padding: 0px !important; font-size: 14px; font-weight: var( — base-text-weight-medium, 500); line-height: 20px; white-space: nowrap; vertical-align: middle; cursor: pointer; user-select: none; border: 0px; border-radius: 6px; appearance: none; color: var( — fgColor-accent, var( — color-accent-fg)); background-color: transparent; box-shadow: none; transition: color 80ms cubic-bezier(0.33, 1, 0.68, 1) 0s, background-color, box-shadow, border-color; justify-content: center !important; align-items: center !important; margin: var( — base-size-8, 8px) !important; width: var( — control-small-size, 28px); height: var( — control-small-size, 28px);”&gt;</p><p>And Flux implements Publisher and returns N elements:</p><pre>public abstract class Flux&lt;T&gt; implements Publisher&lt;T&gt; {...}</pre><p>implements Publisher {…}” tabindex=”0&quot; role=”button” style=”box-sizing: border-box; position: relative; display: flex !important; padding: 0px !important; font-size: 14px; font-weight: var( — base-text-weight-medium, 500); line-height: 20px; white-space: nowrap; vertical-align: middle; cursor: pointer; user-select: none; border: 0px; border-radius: 6px; appearance: none; color: var( — fgColor-accent, var( — color-accent-fg)); background-color: transparent; box-shadow: none; transition: color 80ms cubic-bezier(0.33, 1, 0.68, 1) 0s, background-color, box-shadow, border-color; justify-content: center !important; align-items: center !important; margin: var( — base-size-8, 8px) !important; width: var( — control-small-size, 28px); height: var( — control-small-size, 28px);”&gt;</p><p>By definition, the two types represent streams, and so they’re both lazy. This means nothing is executed until we consume the stream using the subscribe() method. Both types are also immutable, so calling any method will return a new instance of Flux or Mono.</p><h3>What Are the Disadvantages of Using Reactive Streams?</h3><p>There are some major disadvantages to using reactive streams:</p><ul><li>Troubleshooting a Reactive application is a bit difficult, so be sure to check out our tutorial on debugging reactive streams for some handy debugging tips.</li><li>There is limited support for reactive data stores since traditional relational data stores have yet to embrace the reactive paradigm.</li><li>There’s an extra learning curve when implementing.</li></ul><h3>Exception Handling</h3><h3>Explain a Controller Advice</h3><p>The @ControllerAdvice annotation allows us to write global code applicable to a wide range of controllers. We can tie the range of controllers to a chosen package or a specific annotation.</p><p>By default, @ControllerAdvice applies to the classes annotated with @Controller (or @RestController). We also have a few properties that we use if we want to be more specific.</p><p>If we want to restrict applicable classes to a package, we should add the name of the package to the annotation:</p><pre>@ControllerAdvice(&quot;my.package&quot;)<br>@ControllerAdvice(value = &quot;my.package&quot;)<br>@ControllerAdvice(basePackages = &quot;my.package&quot;)</pre><p>It’s also possible to use multiple packages, but this time we need to use an array instead of the String.</p><p>Besides restricting to the package by its name, we can do it by using one of the classes or interfaces from that package:</p><pre>@ControllerAdvice(basePackageClasses = MyClass.class)</pre><p>The ‘assignableTypes‘ element applies the @ControllerAdvice to the specific classes, while ‘annotations‘ does it for particular annotations.</p><p>It’s noteworthy to remember that we should use it along with @ExceptionHandler. This combination will enable us to configure a global and more specific error handling mechanism without the need to implement it every time for every controller class.</p><h3>What Does the @ExceptionHandler Annotation Do?</h3><p>The @ExceptionHandler annotation allows us to define a method that will handle the exceptions. We may use the annotation independently, but it’s a far better option to use it together with the @ControllerAdvice. Thus, we can set up a global error handling mechanism. In this way, we don’t need to write the code for the exception handling within every controller.</p><p>Let’s take a look at the example from our article about Error Handling for REST with Spring:</p><pre>@ControllerAdvice<br>public class RestResponseEntityExceptionHandler<br>  extends ResponseEntityExceptionHandler {</pre><pre>    @ExceptionHandler(value = { IllegalArgumentException.class,<br>      IllegalStateException.class })<br>    protected ResponseEntity&lt;Object&gt; handleConflict(RuntimeException ex,<br>      WebRequest request) {<br>        String bodyOfResponse = &quot;This should be application specific&quot;;<br>        return handleExceptionInternal(ex, bodyOfResponse, new HttpHeaders(),<br>          HttpStatus.CONFLICT, request);<br>    }<br>}</pre><p>handleConflict(RuntimeException ex, WebRequest request) { String bodyOfResponse = “This should be application specific”; return handleExceptionInternal(ex, bodyOfResponse, new HttpHeaders(), HttpStatus.CONFLICT, request); } }” tabindex=”0&quot; role=”button” style=”box-sizing: border-box; position: relative; display: flex !important; padding: 0px !important; font-size: 14px; font-weight: var( — base-text-weight-medium, 500); line-height: 20px; white-space: nowrap; vertical-align: middle; cursor: pointer; user-select: none; border: 0px; border-radius: 6px; appearance: none; color: var( — fgColor-accent, var( — color-accent-fg)); background-color: transparent; box-shadow: none; transition: color 80ms cubic-bezier(0.33, 1, 0.68, 1) 0s, background-color, box-shadow, border-color; justify-content: center !important; align-items: center !important; margin: var( — base-size-8, 8px) !important; width: var( — control-small-size, 28px); height: var( — control-small-size, 28px);”&gt;</p><p>We should also note that this will provide @ExceptionHandler methods to all controllers that throw IllegalArgumentException or IllegalStateException. The exceptions declared with @ExceptionHandler should match the exception used as the argument of the method. Otherwise, the exception resolving mechanism will fail at runtime.</p><p>One thing to keep in mind here is that it’s possible to define more than one @ExceptionHandler for the same exception. We can’t do it in the same class though since Spring would complain by throwing an exception and failing on startup.</p><p>On the other hand, if we define those in two separate classes, the application will start, but it’ll use the first handler it finds, possibly the wrong one.</p><h3>Exception Handling in Web Applications</h3><p>We have three options for exceptions handling in Spring MVC:</p><ul><li>per exception</li><li>per controller</li><li>globally If an unhandled exception is thrown during web request processing, the server will return an HTTP 500 response. To prevent this, we should annotate any of our custom exceptions with the @ResponseStatus annotation. This kind of exceptions is resolved by HandlerExceptionResolver.</li></ul><p>This will cause the server to return an appropriate HTTP response with the specified status code when a controller method throws our exception. We should keep in mind that we shouldn’t handle our exception somewhere else for this approach to work.</p><p>Another way to handle the exceptions is by using the @ExceptionHandler annotation. We add @ExceptionHandler methods to any controller and use them to handle the exceptions thrown from inside that controller. These methods can handle exceptions without the @ResponseStatus annotation, redirect the user to a dedicated error view, or build a totally custom error response.</p><p>We can also pass in the servlet-related objects (HttpServletRequest, HttpServletResponse, HttpSession, and Principal) as the parameters of the handler methods. But, we should remember that we can’t put the Model object as the parameter directly.</p><p>The third option for handling errors is by @ControllerAdvice classes. It’ll allow us to apply the same techniques, only this time at the application level and not only to the particular controller. To enable this, we need to use the @ControllerAdvice and the @ExceptionHandler together. This way exception handlers will handle exceptions thrown by any controller.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=394df9bda2ba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creational Patterns]]></title>
            <link>https://medium.com/@priyankalovesgaurav004/creational-patterns-c90eba36414e?source=rss-7f8ef520f5f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/c90eba36414e</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[design-pattern-in-java]]></category>
            <category><![CDATA[java-interview-questions]]></category>
            <dc:creator><![CDATA[Be You]]></dc:creator>
            <pubDate>Tue, 25 Jun 2024 11:10:59 GMT</pubDate>
            <atom:updated>2024-06-25T11:10:59.659Z</atom:updated>
            <content:encoded><![CDATA[<h3>Design Pattern in Java</h3><p>Creational Design Patterns are concerned with the way in which objects are created. They reduce complexities and instability by creating objects in a controlled manner.</p><h3>Singleton Design Pattern</h3><p>The Singleton Design Pattern aims to keep a check on initialization of objects of a particular class by ensuring that only one instance of the object exists throughout the Java Virtual Machine.</p><p><em>lazy with static inner class</em></p><pre>public class Singleton  {    <br>    private Singleton() {}<br>    <br>    private static class SingletonHolder {    <br>        public static final Singleton instance = new Singleton();<br>    }</pre><pre>    public static Singleton getInstance() {    <br>        return SingletonHolder.instance;    <br>    }<br>}</pre><p><em>static final field (not lazy)</em></p><pre>public class Singleton {</pre><pre>    public static final Singleton INSTANCE = new Singleton();</pre><pre>    private Singleton() {}</pre><pre>}</pre><p>Problems With Serialization and Deserialization In order to serialize the above singleton classes, we must implement those classes with a Serializable interface. But doing that is not enough. When deserializing a class, new instances are created. Now it doesn’t matter the constructor is private or not. Now there can be more than one instance of the same singleton class inside the JVM, violating the singleton property.</p><p>Problems With Reflection An advanced user can change the private access modifier of the constructor to anything they want at runtime using reflection. If this happens, our only mechanism for non-instantiability breaks.</p><p>All of the above problems can be solved very easily by using the enum type to make singletons.</p><p><em>Singleton With Enum</em></p><p>The three lines above make a singleton without any of the problems discussed. Since enums are inherently serializable, we don’t need to implement it with a serializable interface. The reflection problem is also not there. Therefore, it is 100% guaranteed that only one instance of the singleton is present within a JVM. Thus, this method is recommended as the best method of making singletons in Java.</p><p>How to Use</p><pre>public enum SingletonEnum {<br>    INSTANCE;</pre><pre>    int value;</pre><pre>    public int getValue() {<br>        return value;<br>    }</pre><pre>    public void setValue(int value) {<br>        this.value = value;<br>    }<br>}</pre><p>Main class implementation:</p><pre>public class EnumDemo {</pre><pre>    public static void main(String[] args) {<br>        SingletonEnum singleton = SingletonEnum.INSTANCE;</pre><pre>        System.out.println(singleton.getValue());<br>        singleton.setValue(2);<br>        System.out.println(singleton.getValue());<br>    }<br>}</pre><p><em>When to Use Singleton Design Pattern</em></p><ul><li>For resources that are expensive to create (like database connection objects)</li><li>It’s good practice to keep all loggers as Singletons which increases performance</li><li>Classes which provide access to configuration settings for the application</li><li>Classes that contain resources that are accessed in shared mode</li></ul><h3>Factory Design Pattern</h3><p>The Factory Design Pattern or Factory Method Design Pattern is one of the most used design patterns in Java.</p><p>According to GoF, this pattern “defines an interface for creating an object, but let subclasses decide which class to instantiate. The Factory method lets a class defer instantiation to subclasses”.</p><p>In this example, we’ll create a Polygon interface which will be implemented by several concrete classes. A PolygonFactory will be used to fetch objects from this family</p><p>Let’s first create the Polygon interface</p><pre>public interface Polygon {<br>    String getType();<br>}</pre><p>Next, we’ll create a few implementations like Square, Triangle, etc. that implement this interface and return an object of Polygon type Now we can create a factory that takes the number of sides as an argument and returns the appropriate implementation of this interface</p><pre>public class PolygonFactory {<br>    public Polygon getPolygon(int numberOfSides) {<br>        if(numberOfSides == 3) {<br>            return new Triangle();<br>        }<br>        if(numberOfSides == 4) {<br>            return new Square();<br>        }<br>        if(numberOfSides == 5) {<br>            return new Pentagon();<br>        }<br>        if(numberOfSides == 7) {<br>            return new Heptagon();<br>        }<br>        else if(numberOfSides == 8) {<br>            return new Octagon();<br>        }<br>        return null;<br>    }<br>}</pre><p><em>When to Use Factory Method Design Pattern</em></p><ul><li>When the implementation of an interface or an abstract class is expected to change frequently</li><li>When the current implementation cannot comfortably accommodate new change</li><li>When the initialization process is relatively simple, and the constructor only requires a handful of parameters</li></ul><h3>Abstract Factory Design Pattern</h3><p>In the previous section, we saw how the Factory Method design pattern could be used to create objects related to a single family.</p><p>By contrast, the Abstract Factory Design Pattern is used to create families of related or dependent objects. It’s also sometimes called a factory of factories.</p><h3>Builder Design Pattern</h3><p>When the complexity of creating object increases, the Builder pattern can separate out the instantiation process by using another object (a builder) to construct the object.</p><p>Note that all the access modifiers on the fields are declared private since we don’t want outer objects to access them directly.</p><p>The constructor is also private so that only the Builder assigned to this class can access it. All of the properties set in the constructor are extracted from the builder object which we supply as an argument.</p><pre>public class BankAccount {<br>    <br>    private String name;<br>    private String accountNumber;<br>    private String email;<br>    private boolean newsletter;</pre><pre>    // constructors/getters<br>    <br>    public static class BankAccountBuilder {<br>            private String name;<br>            private String accountNumber;<br>            private String email;<br>            private boolean newsletter;<br>            <br>            public BankAccountBuilder(String name, String accountNumber) {<br>                this.name = name;<br>                this.accountNumber = accountNumber;<br>            }<br>        <br>            public BankAccountBuilder withEmail(String email) {<br>                this.email = email;<br>                return this;<br>            }<br>        <br>            public BankAccountBuilder wantNewsletter(boolean newsletter) {<br>                this.newsletter = newsletter;<br>                return this;<br>            }<br>            <br>            public BankAccount build() {<br>                return new BankAccount(this);<br>            }<br>    }<br>}</pre><p>Let’s see a quick example of the builder pattern in action</p><pre>BankAccount newAccount = new BankAccount<br>  .BankAccountBuilder(&quot;Jon&quot;, &quot;22738022275&quot;)<br>  .withEmail(&quot;jon@example.com&quot;)<br>  .wantNewsletter(true)<br>  .build();</pre><p><em>When to Use Builder Pattern</em></p><ul><li>When the process involved in creating an object is extremely complex, with lots of mandatory and optional parameters</li><li>When an increase in the number of constructor parameters leads to a large list of constructors</li><li>When client expects different representations for the object that’s constructed</li></ul><p>The Lombok library provides a great way of simplifying data objects. One of the key features of Project Lombok is the @Builder annotation, which automatically creates Builder classes for creating immutable objects.</p><h3>Structural Patterns</h3><p>Structural Patterns deal with the composition of classes and objects. They provide different ways of using object composition and inheritance to create some abstraction.</p><h3>Proxy Pattern</h3><p>With this pattern, we create an intermediary that acts as an interface to another resource, e.g., a file, a connection. This secondary access provides a surrogate for the real component and protects it from the underlying complexity.</p><p>Key Points of Differentiation:</p><ul><li>The proxy provides the same interface as the object it’s holding the reference to, and it doesn’t modify the data in any manner; it’s in contrast to Adapter and Decorator patterns which alter and decorate the functionalities of pre-existing instances respectively</li><li>The Proxy usually has the information about the real subject at the compile time itself whereas Decorator and Adapter get injected at runtime, knowing only the actual object’s interface</li></ul><p>Consider a heavy Java object (like a JDBC connection or a SessionFactory) that requires some initial configuration.</p><p>We only want such objects to be initialized on demand, and once they are, we’d want to reuse them for all calls. Let’s now create a simple interface and the configuration for this object:</p><pre>public interface ExpensiveObject {<br>    void process();<br>}</pre><p>And the implementation of this interface with a large initial configuration:</p><pre>public class ExpensiveObjectImpl implements ExpensiveObject {</pre><pre>    public ExpensiveObjectImpl() {<br>        heavyInitialConfiguration();<br>    }<br>    <br>    @Override<br>    public void process() {<br>        LOG.info(&quot;processing complete.&quot;);<br>    }<br>    <br>    private void heavyInitialConfiguration() {<br>        LOG.info(&quot;Loading initial configuration...&quot;);<br>    }<br>    <br>}</pre><p>We’ll now utilize the Proxy pattern and initialize our object on demand:</p><pre>public class ExpensiveObjectProxy implements ExpensiveObject {<br>    private static ExpensiveObject object;</pre><pre>    @Override<br>    public void process() {<br>        if (object == null) {<br>            object = new ExpensiveObjectImpl();<br>        }<br>        object.process();<br>    }<br>}</pre><p>Note that we’re calling the process() method twice. Behind the scenes, the settings part will occur only once — when the object is first initialized.</p><p>Let’s talk about when to use the Proxy pattern:</p><ul><li>When we want a simplified version of a complex or heavy object. In this case, we may represent it with a skeleton object which loads the original object on demand, also called as lazy initialization. This is known as the Virtual Proxy</li><li>When the original object is present in different address space, and we want to represent it locally. We can create a proxy which does all the necessary boilerplate stuff like creating and maintaining the connection, encoding, decoding, etc., while the client accesses it as it was present in their local address space. This is called the Remote Proxy</li><li>When we want to add a layer of security to the original underlying object to provide controlled access based on access rights of the client. This is called Protection Proxy</li></ul><h3>Decorator Pattern</h3><p>This pattern is useful for enhancing the behavior of an object. Key points of differentiation:</p><ul><li>Although Proxy and Decorator patterns have similar structures, they differ in intention; while Proxy’s prime purpose is to facilitate ease of use or controlled access, a Decorator attaches additional responsibilities</li><li>Both Proxy and Adapter patterns hold a reference to the original object</li><li>All the decorators from this pattern can be used recursively, an infinite number of times, which is not possible with other models</li></ul><p>Suppose we have a Christmas tree object and we want to decorate it. The decoration does not change the object itself; it’s just that in addition to the Christmas tree, we’re adding some decoration items like garland, tinsel, tree-topper, bubble lights, etc.</p><p>First, we’ll create a ChristmasTree interface and its implementation:</p><pre>public interface ChristmasTree {<br>    String decorate();<br>}</pre><p>The implementation of this interface will look like:</p><pre>public class ChristmasTreeImpl implements ChristmasTree {</pre><pre>    @Override<br>    public String decorate() {<br>        return &quot;Christmas tree&quot;;<br>    }<br>}</pre><p>We’ll now create an abstract TreeDecorator class for this tree. This decorator will implement the ChristmasTree interface as well as hold the same object. The implemented method from the same interface will simply call the decorate() method from our interface:</p><pre>public abstract class TreeDecorator implements ChristmasTree {<br>    private ChristmasTree tree;<br>    <br>    // standard constructors<br>    @Override<br>    public String decorate() {<br>        return tree.decorate();<br>    }<br>}</pre><p>We’ll now create some decorating element. These decorators will extend our abstract TreeDecorator class and will modify its decorate() method according to our requirement:</p><pre>public class BubbleLights extends TreeDecorator {</pre><pre>    public BubbleLights(ChristmasTree tree) {<br>        super(tree);<br>    }<br>    <br>    public String decorate() {<br>        return super.decorate() + decorateWithBubbleLights();<br>    }<br>    <br>    private String decorateWithBubbleLights() {<br>        return &quot; with Bubble Lights&quot;;<br>    }<br>}</pre><p>This is a good choice in the following cases:</p><ul><li>When we wish to add, enhance or even remove the behavior or state of objects</li><li>When we just want to modify the functionality of a single object of class and leave others unchanged</li></ul><h3>Adapter Pattern</h3><p>The Adapter pattern is used for connecting two incompatible interfaces that otherwise cannot be connected directly. An Adapter wraps an existing class with a new interface so that it becomes compatible with the interface needed.</p><p>The main differences between Adapter and Proxy patterns are:</p><ul><li>While proxy provides the same interface, Adapter provides a different interface that’s compatible with its client</li><li>Adapter pattern is used after the application components are designed so that we can use them without modifying the source code. This is in contrast to the Bridge pattern, which is used before the components are designed.</li></ul><p>Consider a scenario in which there is an app that’s developed in the US which returns the top speed of luxury cars in miles per hour (MPH). Now we need to use the same app for our client in the UK that wants the same results but in kilometers per hour (km/h).</p><p>To deal with this problem, we’ll create an adapter which will convert the values and give us the desired results</p><p>First, we’ll create the original interface Movable which is supposed to return the speed of some luxury cars in miles per hour:</p><pre>public interface Movable {<br>    // returns speed in MPH <br>    double getSpeed();<br>}</pre><p>We’ll now create one concrete implementation of this interface:</p><pre>public class BugattiVeyron implements Movable {<br> <br>    @Override<br>    public double getSpeed() {<br>        return 268;<br>    }<br>}</pre><p>Now we’ll create an adapter interface MovableAdapter that will be based on the same Movable class. It may be slightly modified to yield different results in different scenarios:</p><pre>public interface MovableAdapter {<br>    // returns speed in KM/H <br>    double getSpeed();<br>}</pre><p>The implementation of this interface will consist of private method convertMPHtoKMPH() that will be used for the conversion:</p><pre>public class MovableAdapterImpl implements MovableAdapter {<br>    private Movable luxuryCars;<br>    <br>    // standard constructors</pre><pre>    @Override<br>    public double getSpeed() {<br>        return convertMPHtoKMPH(luxuryCars.getSpeed());<br>    }<br>    <br>    private double convertMPHtoKMPH(double mph) {<br>        return mph * 1.60934;<br>    }<br>}</pre><p><em>When to Use Adapter Pattern</em></p><ul><li>When an outside component provides captivating functionality that we’d like to reuse, but it’s incompatible with our current application. A suitable Adapter can be developed to make them compatible with each other</li><li>When our application is not compatible with the interface that our client is expecting</li><li>When we want to reuse legacy code in our application without making any modification in the original code</li></ul><h3>Bridge Pattern</h3><p>The Bridge pattern is used to decouple an abstraction from its implementation so that the two can vary independently.</p><p>This means to create a bridge interface that uses OOP principles to separate out responsibilities into different abstract classes.</p><p>Key Points of Differentiation:</p><ul><li>A Bridge pattern can only be implemented before the application is designed.</li><li>Allows an abstraction and implementation to change independently whereas an Adapter pattern makes it possible for incompatible classes to work together</li></ul><p>For the Bridge pattern, we’ll consider two layers of abstraction; one is the geometric shape (like triangle and square) which is filled with different colors (our second abstraction layer)</p><p>First, we’ll define a color interface:</p><pre>public interface Color {<br>    String fill();<br>}</pre><p>Now we’ll create a concrete class for this interface:</p><pre>public class Blue implements Color {<br>    @Override<br>    public String fill() {<br>        return &quot;Color is Blue&quot;;<br>    }<br>}</pre><p>Let’s now create an abstract Shape class which consists a reference (bridge) to the Color object:</p><pre>public abstract class Shape {<br>    protected Color color;<br>    <br>    //standard constructors<br>    <br>    abstract public String draw();<br>}</pre><p>We’ll now create a concrete class of Shape interface which will utilize method from Color interface as well:</p><pre>public class Square extends Shape {</pre><pre>    public Square(Color color) {<br>        super(color);<br>    }</pre><pre>    @Override<br>    public String draw() {<br>        return &quot;Square drawn. &quot; + color.fill();<br>    }<br>}</pre><p>This is a good choice in the following cases:</p><ul><li>When we want a parent abstract class to define the set of basic rules, and the concrete classes to add additional rules</li><li>When we have an abstract class that has a reference to the objects, and it has abstract methods that will be defined in each of the concrete classes</li></ul><h3>Facade Pattern</h3><p>Simply put, a facade encapsulates a complex subsystem behind a simple interface. It hides much of the complexity and makes the subsystem easy to use.</p><p>Besides a much simpler interface, there’s one more benefit of using this design pattern. It decouples a client implementation from the complex subsystem. Thanks to this, we can make changes to the existing subsystem and don’t affect a client.</p><h3>Flyweight Pattern</h3><p>This pattern is used to reduce the memory footprint. It can also improve performance in applications where object instantiation is expensive.</p><p>The flyweight object’s state is made up of an invariant component shared with other similar objects (intrinsic) and a variant component which can be manipulated by the client code (extrinsic).</p><p>It’s very important that the flyweight objects are immutable: any operation on the state must be performed by the factory.</p><p>The main elements of the pattern are:</p><ul><li>an interface which defines the operations that the client code can perform on the flyweight object</li><li>one or more concrete implementations of our interface</li><li>a factory to handle objects instantiation and caching</li></ul><p>To begin with, we’ll create a Vehicle interface. Since this interface will be the return type of the factory method we need to make sure to expose all the relevant methods</p><pre>public void start();<br>public void stop();<br>public Color getColor();</pre><p>Next up, let’s make a Car class as a concrete Vehicle. Our car will implement all the methods of the vehicle interface. As for its state, it’ll have an engine and a color field:</p><pre>private Engine engine;<br>private Color color;</pre><p>Last but not least, we’ll create the VehicleFactory. Building a new vehicle is a very expensive operation so the factory will only create one vehicle per color.</p><p>In order to do that, we keep track of the created vehicles using a map as a simple cache:</p><pre>private static Map&lt;Color, Vehicle&gt; vehiclesCache<br>  = new HashMap&lt;&gt;();</pre><pre>public static Vehicle createVehicle(Color color) {<br>    Vehicle newVehicle = vehiclesCache.computeIfAbsent(color, newColor -&gt; { <br>        Engine newEngine = new Engine();<br>        return new Car(newEngine, newColor);<br>    });<br>    return newVehicle;<br>}</pre><p>vehiclesCache = new HashMap(); public static Vehicle createVehicle(Color color) { Vehicle newVehicle = vehiclesCache.computeIfAbsent(color, newColor -&gt; { Engine newEngine = new Engine(); return new Car(newEngine, newColor); }); return newVehicle; }” tabindex=”0&quot; role=”button” style=”box-sizing: border-box; position: relative; display: flex !important; padding: 0px !important; font-size: 14px; font-weight: var( — base-text-weight-medium, 500); line-height: 20px; white-space: nowrap; vertical-align: middle; cursor: pointer; user-select: none; border: 0px; border-radius: 6px; appearance: none; color: var( — fgColor-accent, var( — color-accent-fg)); background-color: transparent; box-shadow: none; transition: color 80ms cubic-bezier(0.33, 1, 0.68, 1) 0s, background-color, box-shadow, border-color; justify-content: center !important; align-items: center !important; margin: var( — base-size-8, 8px) !important; width: var( — control-small-size, 28px); height: var( — control-small-size, 28px);”&gt;</p><h3>Behavioral Patterns</h3><h3>Memento Pattern</h3><p>The Memento Design Pattern offers a solution to implement undoable actions. We can do this by saving the state of an object at a given instant and restoring it if the actions performed since need to be undone.</p><p>Practically, the object whose state needs to be saved is called an Originator. The Caretaker is the object triggering the save and restore of the state, which is called the Memento.</p><p>The Memento object should expose as little information as possible to the Caretaker. This is to ensure that we don’t expose the internal state of the Originator to the outside world, as it would break encapsulation principles. However, the Originator should access enough information in order to restore to the original state.</p><p>the Originator can produce and consume a Memento. Meanwhile, the Caretaker only keeps the state before restoring it. The internal representation of the Originator is kept hidden from the external world.</p><p>Typically, the Memento Design Pattern will be used in situations where some actions are undoable, therefore requiring to rollback to a previous state. However, if the state of the Originator is heavy, using the Memento Design Pattern can lead to an expensive creation process and increased use of memory.</p><p>Let’s now see an example of the Memento Design Pattern. Let’s imagine we have a text editor:</p><pre>public class TextEditor {</pre><pre>    private TextWindow textWindow;</pre><pre>    public TextEditor(TextWindow textWindow) {<br>        this.textWindow = textWindow;<br>    }<br>}</pre><p>It has a text window, which holds the currently entered text, and provides a way to add more text:</p><pre>public class TextWindow {</pre><pre>    private StringBuilder currentText;</pre><pre>    public TextWindow() {<br>        this.currentText = new StringBuilder();<br>    }</pre><pre>    public void addText(String text) {<br>        currentText.append(text);<br>    }<br>}</pre><p>Now, let’s imagine we want our text editor to implement some save and undo features. When saving, we want our current text to be saved. Thus, when undoing subsequent changes, we’ll have our saved text restored.</p><p>In order to do that, we’ll make use of the Memento Design Pattern. First, we’ll create an object holding the current text of the window:</p><pre>public class TextWindowState {</pre><pre>    private String text;</pre><pre>    public TextWindowState(String text) {<br>        this.text = text;<br>    }</pre><pre>    public String getText() {<br>        return text;<br>    }<br>}</pre><p>This object is our Memento. As we can see, we choose to use String instead of StringBuilder to prevent any update of the current text by outsiders.</p><p>After that, we’ll have to provide the TextWindow class with methods to create and consume the Memento object, making the TextWindow our Originator:</p><pre>public TextWindowState save() {<br>    return new TextWindowState(wholeText.toString());<br>}</pre><pre>public void restore(TextWindowState save) {<br>    currentText = new StringBuilder(save.getText());<br>}</pre><p>Finally, we have to update our TextEditor class. As the Caretaker, it will hold the state of the Originator and ask to restore it when needed:</p><pre>private TextWindowState savedTextWindow;</pre><pre>public void hitSave() {<br>    savedTextWindow = textWindow.save();<br>}</pre><pre>public void hitUndo() {<br>    textWindow.restore(savedTextWindow);<br>}</pre><p>Let’s see if it works through a sample run. Imagine we add some text to our editor, save it, then add some more and, finally, undo. In order to achieve that, we’ll add a print() method on our TextEditor that returns a String of the current text:</p><pre>TextEditor textEditor = new TextEditor(new TextWindow());<br>textEditor.write(&quot;The Memento Design Pattern\n&quot;);<br>textEditor.write(&quot;How to implement it in Java?\n&quot;);<br>textEditor.hitSave();<br> <br>textEditor.write(&quot;Buy milk and eggs before coming home\n&quot;);<br> <br>textEditor.hitUndo();</pre><pre>assertThat(textEditor.print()).isEqualTo(&quot;The Memento Design Pattern\nHow to implement it in Java?\n&quot;);</pre><h3>Mediator Pattern</h3><p>The intent of the Mediator Pattern is to reduce the complexity and dependencies between tightly coupled objects communicating directly with one another. This is achieved by creating a mediator object that takes care of the interaction between dependent objects. Consequently, all the communication goes through the mediator.</p><p>This promotes loose coupling, as a set of components working together no longer have to interact directly. Instead, they only refer to the single mediator object. This way, it is also easier to reuse these objects in other parts of the system.</p><p>Imagine we’re building a simple cooling system that consists of a fan, a power supply, and a button. Pressing the button will either turn on or turn off the fan. Before we turn the fan on, we need to turn on the power. Similarly, we have to turn off the power right after the fan is turned off.</p><p>Now, let’s implement the Mediator Pattern to reduce the dependencies between our classes and make the code more reusable.</p><p>First, let’s introduce the Mediator class:</p><pre>public class Mediator {<br>    private Button button;<br>    private Fan fan;<br>    private PowerSupplier powerSupplier;</pre><pre>    // constructor, getters and setters</pre><pre>    public void press() {<br>        if (fan.isOn()) {<br>            fan.turnOff();<br>        } else {<br>            fan.turnOn();<br>        }<br>    }</pre><pre>    public void start() {<br>        powerSupplier.turnOn();<br>    }</pre><pre>    public void stop() {<br>        powerSupplier.turnOff();<br>    }<br>}</pre><p>let’s modify the remaining classes:</p><pre>public class Button {<br>    private Mediator mediator;</pre><pre>    // constructor, getters and setters</pre><pre>    public void press() {<br>        mediator.press();<br>    }<br>}</pre><pre>public class Fan {<br>    private Mediator mediator;<br>    private boolean isOn = false;</pre><pre>    // constructor, getters and setters</pre><pre>    public void turnOn() {<br>        mediator.start();<br>        isOn = true;<br>    }</pre><pre>    public void turnOff() {<br>        isOn = false;<br>        mediator.stop();<br>    }<br>}</pre><p>Now that we’ve implemented the Mediator Pattern, none of the Button, Fan, or PowerSupplier classes communicate directly. They only have a single reference to the Mediator. If we need to add a second power supply in the future, all we have to do is to update Mediator’s logic; Button and Fan classes remain untouched.</p><p>This example shows how easily we can separate dependent objects and make our system easier to maintain.</p><p><em>When to Use the Mediator Pattern</em></p><ul><li>The Mediator Pattern is a good choice if we have to deal with a set of objects that are tightly coupled and hard to maintain. This way we can reduce the dependencies between objects and decrease the overall complexity.</li><li>Additionally, by using the mediator object, we extract the communication logic to the single component, therefore we follow the Single Responsibility Principle. Furthermore, we can introduce new mediators with no need to change the remaining parts of the system. Hence, we follow the Open-Closed Principle.</li><li>Sometimes, however, we may have too many tightly coupled objects due to the faulty design of the system. If this is a case, we should not apply the Mediator Pattern. Instead, we should take one step back and rethink the way we’ve modeled our classes.</li></ul><p>As with all other patterns, we need to consider our specific use case before blindly implementing the Mediator Pattern.</p><h3>State Pattern</h3><p>The main idea of State pattern is to allow the object for changing its behavior without changing its class. Also, by implementing it, the code should remain cleaner without many if/else statements.</p><p>Imagine we have a package which is sent to a post office, the package itself can be ordered, then delivered to a post office and finally received by a client. Now, depending on the actual state, we want to print its delivery status.</p><p>The simplest approach would be to add some boolean flags and apply simple if/else statements within each of our methods in the class. That won’t complicate it much in a simple scenario. However, it might complicate and pollute our code when we’ll get more states to process which will result in even more if/else statements.</p><p>Thanks to the State design pattern, we can encapsulate the logic in dedicated classes, apply the Single Responsibility Principle and Open/Closed Principle, have cleaner and more maintainable code.</p><p>First, let’s define our context, that’s going to be a Package class:</p><pre>public class Package {</pre><pre>    private PackageState state = new OrderedState();</pre><pre>    // getter, setter</pre><pre>    public void previousState() {<br>        state.prev(this);<br>    }</pre><pre>    public void nextState() {<br>        state.next(this);<br>    }</pre><pre>    public void printStatus() {<br>        state.printStatus();<br>    }<br>}</pre><p>As we can see, it contains a reference for managing the state, notice previousState(), nextState() and printStatus() methods where we delegate the job to the state object. The states will be linked to each other and every state will set another one based on this reference passed to both methods. Next, we’re going to have the PackageState which has three methods with the following signatures:</p><pre>public interface PackageState {</pre><pre>    void next(Package pkg);<br>    void prev(Package pkg);<br>    void printStatus();<br>}</pre><p>This interface will be implemented by each concrete state class.</p><p>The first concrete state will be OrderedState:</p><pre>public class OrderedState implements PackageState {</pre><pre>    @Override<br>    public void next(Package pkg) {<br>        pkg.setState(new DeliveredState());<br>    }</pre><pre>    @Override<br>    public void prev(Package pkg) {<br>        System.out.println(&quot;The package is in its root state.&quot;);<br>    }</pre><pre>    @Override<br>    public void printStatus() {<br>        System.out.println(&quot;Package ordered, not delivered to the office yet.&quot;);<br>    }<br>}</pre><p>Let’s have a look at the DeliveredState class:</p><pre>public class DeliveredState implements PackageState {</pre><pre>    @Override<br>    public void next(Package pkg) {<br>        pkg.setState(new ReceivedState());<br>    }</pre><pre>    @Override<br>    public void prev(Package pkg) {<br>        pkg.setState(new OrderedState());<br>    }</pre><pre>    @Override<br>    public void printStatus() {<br>        System.out.println(&quot;Package delivered to post office, not received yet.&quot;);<br>    }<br>}</pre><p>First, the strategy pattern defines a family of interchangeable algorithms. Generally, they achieve the same goal, but with a different implementation, for example, sorting or rendering algorithms.</p><p>In state pattern, the behavior might change completely, based on actual state.</p><p>Next, in strategy, the client has to be aware of the possible strategies to use and change them explicitly. Whereas in state pattern, each state is linked to another and create the flow as in Finite State Machine.</p><p>The state design pattern is great when we want to avoid primitive if/else statements. Instead, we extract the logic to separate classes and let our context object delegate the behavior to the methods implemented in the state class.</p><h3>Visitor Pattern</h3><p>The purpose of a Visitor pattern is to define a new operation without introducing the modifications to an existing object structure.</p><p>Imagine that we have a composite object which consists of components. The object’s structure is fixed — we either can’t change it, or we don’t plan to add new types of elements to the structure.</p><p>Now, how could we add new functionality to our code without modification of existing classes?</p><p>The Visitor design pattern might be an answer. Simply put, we’ll have to do is to add a function which accepts the visitor class to each element of the structure. That way our components will allow the visitor implementation to “visit” them and perform any required action on that element. In other words, we’ll extract the algorithm which will be applied to the object structure from the classes. Consequently, we’ll make good use of the Open/Closed principle as we won’t modify the code, but we’ll still be able to extend the functionality by providing a new Visitor implementation.</p><p>Our example will be custom Document object that consists of JSON and XML concrete elements; the elements have a common abstract superclass, the Element.</p><p>The Document class:</p><pre>public class Document extends Element {</pre><pre>    List&lt;Element&gt; elements = new ArrayList&lt;&gt;();</pre><pre>    // ...</pre><pre>    @Override<br>    public void accept(Visitor v) {<br>        for (Element e : this.elements) {<br>            e.accept(v);<br>        }<br>    }<br>}</pre><p>elements = new ArrayList(); // … @Override public void accept(Visitor v) { for (Element e : this.elements) { e.accept(v); } } }” tabindex=”0&quot; role=”button” style=”box-sizing: border-box; position: relative; display: flex !important; padding: 0px !important; font-size: 14px; font-weight: var( — base-text-weight-medium, 500); line-height: 20px; white-space: nowrap; vertical-align: middle; cursor: pointer; user-select: none; border: 0px; border-radius: 6px; appearance: none; color: var( — fgColor-accent, var( — color-accent-fg)); background-color: transparent; box-shadow: none; transition: color 80ms cubic-bezier(0.33, 1, 0.68, 1) 0s, background-color, box-shadow, border-color; justify-content: center !important; align-items: center !important; margin: var( — base-size-8, 8px) !important; width: var( — control-small-size, 28px); height: var( — control-small-size, 28px);”&gt;</p><p>The Element class has an abstract method which accepts the Visitor interface:</p><pre>public abstract void accept(Visitor v);</pre><p>Therefore, when creating the new element, name it the JsonElement, we’ll have to provide the implementation this method.</p><p>However, due to nature of the Visitor pattern, the implementation will be the same, so in most cases, it would require us to copy-paste the boilerplate code from other, already existing element:</p><pre>public class JsonElement extends Element {</pre><pre>    // ...</pre><pre>    public void accept(Visitor v) {<br>        v.visit(this);<br>    }<br>}</pre><p>Since our elements allow visiting them by any visitor, let’s say that we want to process our Document elements, but each of them in a different way, depending on its class type.</p><p>Therefore, our visitor will have a separate method for the given type:</p><pre>public class ElementVisitor implements Visitor {</pre><pre>    @Override<br>    public void visit(XmlElement xe) {<br>        System.out.println(<br>          &quot;processing an XML element with uuid: &quot; + xe.uuid);<br>    }</pre><pre>    @Override<br>    public void visit(JsonElement je) {<br>        System.out.println(<br>          &quot;processing a JSON element with uuid: &quot; + je.uuid);<br>    }<br>}</pre><p>For testing purpose, let’s have a look at VisitorDemoclass:</p><pre>public class VisitorDemo {</pre><pre>    public static void main(String[] args) {</pre><pre>        Visitor v = new ElementVisitor();</pre><pre>        Document d = new Document(generateUuid());<br>        d.elements.add(new JsonElement(generateUuid()));<br>        d.elements.add(new JsonElement(generateUuid()));<br>        d.elements.add(new XmlElement(generateUuid()));</pre><pre>        d.accept(v);<br>    }</pre><pre>    // ...<br>}</pre><p>As each design pattern, even the Visitor has its downsides, particularly, its usage makes it more difficult to maintain the code if we need to add new elements to the object’s structure.</p><p>For example, if we add new YamlElement, then we need to update all existing visitors with the new method desired for processing this element. Following this further, if we have ten or more concrete visitors, that might be cumbersome to update all of them.</p><p>The Visitor pattern is great to separate the algorithm from the classes on which it operates. Besides that, it makes adding new operation more easily, just by providing a new implementation of the Visitor.</p><p>Furthermore, we don’t depend on components interfaces, and if they are different, that’s fine, since we have a separate algorithm for processing per concrete element.</p><h3>Command Pattern</h3><p>Simply put, the pattern intends to encapsulate in an object all the data required for performing a given action (command), including what method to call, the method’s arguments, and the object to which the method belongs.</p><p>This model allows us to decouple objects that produce the commands from their consumers, so that’s why the pattern is commonly known as the producer-consumer pattern.</p><p>In a classic implementation, the command pattern requires implementing four components:</p><ul><li>the Command,</li><li>the Receiver,</li><li>the Invoker,</li><li>and the Client.</li></ul><p>To understand how the pattern works and the role that each component plays, let’s create a basic example. Let’s suppose that we want to develop a text file application. In such a case, we should implement all functionality required for performing some text-file related operations, such as opening, writing, saving a text file, and so forth.</p><p>A command is an object whose role is to store all the information required for executing an action, including the method to call, the method arguments, and the object (known as the receiver) that implements the method.</p><pre>@FunctionalInterface<br>public interface TextFileOperation {<br>    String execute();<br>}</pre><pre>public class OpenTextFileOperation implements TextFileOperation {</pre><pre>    private TextFile textFile;<br>    <br>    // constructors<br>    <br>    @Override<br>    public String execute() {<br>        return textFile.open();<br>    }<br>}</pre><pre>public class SaveTextFileOperation implements TextFileOperation {<br>    <br>    // same field and constructor as above<br>        <br>    @Override<br>    public String execute() {<br>        return textFile.save();<br>    }<br>}</pre><p>the TextFileOperation commands encapsulate all the information required for opening and saving a text file, including the receiver object, the methods to call, and the arguments (in this case, no arguments are required, but they could be).</p><p>A receiver is an object that performs a set of cohesive actions. It’s the component that performs the actual action when the command’s execute() method is called.</p><pre>public class TextFile {<br>    <br>    private String name;<br>    <br>    // constructor<br>    <br>    public String open() {<br>        return &quot;Opening file &quot; + name;<br>    }<br>    <br>    public String save() {  <br>        return &quot;Saving file &quot; + name;<br>    }<br>    <br>    // additional text file methods (editing, writing, copying, pasting)<br>}</pre><p>An invoker is an object that knows how to execute a given command but doesn’t know how the command has been implemented. It only knows the command’s interface.</p><pre>public class TextFileOperationExecutor {<br>    <br>    private final List&lt;TextFileOperation&gt; textFileOperations<br>     = new ArrayList&lt;&gt;();<br>    <br>    public String executeOperation(TextFileOperation textFileOperation) {<br>        textFileOperations.add(textFileOperation);<br>        return textFileOperation.execute();<br>    }<br>}</pre><p>textFileOperations = new ArrayList(); public String executeOperation(TextFileOperation textFileOperation) { textFileOperations.add(textFileOperation); return textFileOperation.execute(); } }” tabindex=”0&quot; role=”button” style=”box-sizing: border-box; position: relative; display: flex !important; padding: 0px !important; font-size: 14px; font-weight: var( — base-text-weight-medium, 500); line-height: 20px; white-space: nowrap; vertical-align: middle; cursor: pointer; user-select: none; border: 0px; border-radius: 6px; appearance: none; color: var( — fgColor-accent, var( — color-accent-fg)); background-color: transparent; box-shadow: none; transition: color 80ms cubic-bezier(0.33, 1, 0.68, 1) 0s, background-color, box-shadow, border-color; justify-content: center !important; align-items: center !important; margin: var( — base-size-8, 8px) !important; width: var( — control-small-size, 28px); height: var( — control-small-size, 28px);”&gt;</p><p>A client is an object that controls the command execution process by specifying what commands to execute and at what stages of the process to execute them.</p><pre>public static void main(String[] args) {<br>    TextFileOperationExecutor textFileOperationExecutor<br>      = new TextFileOperationExecutor();<br>    textFileOperationExecutor.executeOperation(<br>      new OpenTextFileOperation(new TextFile(&quot;file1.txt&quot;))));<br>    textFileOperationExecutor.executeOperation(<br>      new SaveTextFileOperation(new TextFile(&quot;file2.txt&quot;))));<br>}</pre><p>As the TextFileOperation interface is a functional interface, we can pass command objects in the form of lambda expressions to the invoker, without having to create the TextFileOperation instances explicitly:</p><pre>TextFileOperationExecutor textFileOperationExecutor<br> = new TextFileOperationExecutor();<br>textFileOperationExecutor.executeOperation(() -&gt; &quot;Opening file file1.txt&quot;);<br>textFileOperationExecutor.executeOperation(() -&gt; &quot;Saving file file1.txt&quot;);</pre><p>“Opening file file1.txt”); textFileOperationExecutor.executeOperation(() -&gt; “Saving file file1.txt”);” tabindex=”0&quot; role=”button” style=”box-sizing: border-box; position: relative; display: flex !important; padding: 0px !important; font-size: 14px; font-weight: var( — base-text-weight-medium, 500); line-height: 20px; white-space: nowrap; vertical-align: middle; cursor: pointer; user-select: none; border: 0px; border-radius: 6px; appearance: none; color: var( — fgColor-accent, var( — color-accent-fg)); background-color: transparent; box-shadow: none; transition: color 80ms cubic-bezier(0.33, 1, 0.68, 1) 0s, background-color, box-shadow, border-color; justify-content: center !important; align-items: center !important; margin: var( — base-size-8, 8px) !important; width: var( — control-small-size, 28px); height: var( — control-small-size, 28px);”&gt;</p><h3>Observer Pattern</h3><p>It specifies communication between objects: observable and observers. An observable is an object which notifies observers about the changes in its state.</p><p>For example, a news agency can notify channels when it receives news. Receiving news is what changes the state of the news agency, and it causes the channels to be notified.</p><p>Let’s see how we can implement it ourselves.</p><p>First, let’s define the NewsAgency class:</p><pre>public class NewsAgency {<br>    private String news;<br>    private List&lt;Channel&gt; channels = new ArrayList&lt;&gt;();</pre><pre>    public void addObserver(Channel channel) {<br>        this.channels.add(channel);<br>    }</pre><pre>    public void removeObserver(Channel channel) {<br>        this.channels.remove(channel);<br>    }</pre><pre>    public void setNews(String news) {<br>        this.news = news;<br>        for (Channel channel : this.channels) {<br>            channel.update(this.news);<br>        }<br>    }<br>}</pre><p>channels = new ArrayList(); public void addObserver(Channel channel) { this.channels.add(channel); } public void removeObserver(Channel channel) { this.channels.remove(channel); } public void setNews(String news) { this.news = news; for (Channel channel : this.channels) { channel.update(this.news); } } }” tabindex=”0&quot; role=”button” style=”box-sizing: border-box; position: relative; display: flex !important; padding: 0px !important; font-size: 14px; font-weight: var( — base-text-weight-medium, 500); line-height: 20px; white-space: nowrap; vertical-align: middle; cursor: pointer; user-select: none; border: 0px; border-radius: 6px; appearance: none; color: var( — fgColor-accent, var( — color-accent-fg)); background-color: transparent; box-shadow: none; transition: color 80ms cubic-bezier(0.33, 1, 0.68, 1) 0s, background-color, box-shadow, border-color; justify-content: center !important; align-items: center !important; margin: var( — base-size-8, 8px) !important; width: var( — control-small-size, 28px); height: var( — control-small-size, 28px);”&gt;</p><p>To be able to do that, the observable object needs to keep references to the observers, and in our case, it’s the channels variable.</p><h3>Template Method Pattern</h3><p>It makes it easier to implement complex algorithms by encapsulating logic in a single method.</p><p>The ComputerBuilder class is responsible for outlining the steps required to build a computer by declaring methods for adding and setting up different components, such as a motherboard and a processor.</p><pre>public abstract class ComputerBuilder {<br>    <br>    // ...<br>    <br>    public final Computer buildComputer() {<br>        addMotherboard();<br>        setupMotherboard();<br>        addProcessor();<br>        return new Computer(computerParts);<br>    }<br>   <br>    public abstract void addMotherboard();<br>    public abstract void setupMotherboard();<br>    public abstract void addProcessor();<br>    <br>    // ...<br>}</pre><p>Here, the build() method is the template method, which defines steps of the algorithm for assembling the computer parts and returns fully-initialized Computer instances.</p><p>Notice that it’s declared as final to prevent it from being overridden. With the base class already set, let’s try to use it by creating two subclasses. One which builds a “standard” computer, and the other that builds a “high-end” computer:</p><pre>public class StandardComputerBuilder extends ComputerBuilder {</pre><pre>    @Override<br>    public void addMotherboard() {<br>        computerParts.put(&quot;Motherboard&quot;, &quot;Standard Motherboard&quot;);<br>    }<br>    <br>    @Override<br>    public void setupMotherboard() {<br>        motherboardSetupStatus.add(<br>          &quot;Screwing the standard motherboard to the case.&quot;);<br>        motherboardSetupStatus.add(<br>          &quot;Pluging in the power supply connectors.&quot;);<br>        motherboardSetupStatus.forEach(<br>          step -&gt; System.out.println(step));<br>    }<br>    <br>    @Override<br>    public void addProcessor() {<br>        computerParts.put(&quot;Processor&quot;, &quot;Standard Processor&quot;);<br>    }<br>}</pre><p>System.out.println(step)); } @Override public void addProcessor() { computerParts.put(“Processor”, “Standard Processor”); } }” tabindex=”0&quot; role=”button” style=”box-sizing: border-box; position: relative; display: flex !important; padding: 0px !important; font-size: 14px; font-weight: var( — base-text-weight-medium, 500); line-height: 20px; white-space: nowrap; vertical-align: middle; cursor: pointer; user-select: none; border: 0px; border-radius: 6px; appearance: none; color: var( — fgColor-accent, var( — color-accent-fg)); background-color: transparent; box-shadow: none; transition: color 80ms cubic-bezier(0.33, 1, 0.68, 1) 0s, background-color, box-shadow, border-color; justify-content: center !important; align-items: center !important; margin: var( — base-size-8, 8px) !important; width: var( — control-small-size, 28px); height: var( — control-small-size, 28px);”&gt;</p><h3>Strategy Pattern</h3><p>Essentially, the strategy pattern allows us to change the behavior of an algorithm at runtime.</p><p>Typically, we would start with an interface which is used to apply an algorithm, and then implement it multiple times for each possible algorithm.</p><p>Let’s say we have a requirement to apply different types of discounts to a purchase, based on whether it’s a Christmas, Easter or New Year. First, let’s create a Discounter interface which will be implemented by each of our strategies:</p><pre>public interface Discounter {<br>    BigDecimal applyDiscount(BigDecimal amount);<br>}</pre><p>Then let’s say we want to apply a 50% discount at Easter and a 10% discount at Christmas. Let’s implement our interface for each of these strategies:</p><pre>public static class EasterDiscounter implements Discounter {<br>    @Override<br>    public BigDecimal applyDiscount(final BigDecimal amount) {<br>        return amount.multiply(BigDecimal.valueOf(0.5));<br>    }<br>}</pre><pre>public static class ChristmasDiscounter implements Discounter {<br>   @Override<br>   public BigDecimal applyDiscount(final BigDecimal amount) {<br>       return amount.multiply(BigDecimal.valueOf(0.9));<br>   }<br>}</pre><p>usage</p><pre>Discounter easterDiscounter = new EasterDiscounter();</pre><pre>BigDecimal discountedValue = easterDiscounter<br>  .applyDiscount(BigDecimal.valueOf(100));</pre><pre>assertThat(discountedValue)<br>  .isEqualByComparingTo(BigDecimal.valueOf(50));</pre><h3>Chain of Responsibility Pattern</h3><p>The Chain of Responsibility pattern is handy for:</p><ul><li>Decoupling a sender and receiver of a command</li><li>Picking a processing strategy at processing-time</li></ul><p>Let’s first create an abstract base class for our processors:</p><pre>public abstract class AuthenticationProcessor {</pre><pre>    public AuthenticationProcessor nextProcessor;<br>    <br>    // standard constructors</pre><pre>    public abstract boolean isAuthorized(AuthenticationProvider authProvider);<br>}</pre><p>Next, let’s create concrete processors which extend AuthenticationProcessor:</p><pre>public class OAuthProcessor extends AuthenticationProcessor {</pre><pre>    public OAuthProcessor(AuthenticationProcessor nextProcessor) {<br>        super(nextProcessor);<br>    }</pre><pre>    @Override<br>    public boolean isAuthorized(AuthenticationProvider authProvider) {<br>        if (authProvider instanceof OAuthTokenProvider) {<br>            return true;<br>        } else if (nextProcessor != null) {<br>            return nextProcessor.isAuthorized(authProvider);<br>        }<br>        <br>        return false;<br>    }<br>}</pre><pre>public class UsernamePasswordProcessor extends AuthenticationProcessor {</pre><pre>    public UsernamePasswordProcessor(AuthenticationProcessor nextProcessor) {<br>        super(nextProcessor);<br>    }</pre><pre>    @Override<br>    public boolean isAuthorized(AuthenticationProvider authProvider) {<br>        if (authProvider instanceof UsernamePasswordProvider) {<br>            return true;<br>        } else if (nextProcessor != null) {<br>            return nextProcessor.isAuthorized(authProvider);<br>        }<br>    return false;<br>    }<br>}</pre><p>Here, we created two concrete processors for our incoming authorization requests: UsernamePasswordProcessor and OAuthProcessor.</p><p>For each one, we overrode the isAuthorized method.</p><p>Now let’s create a couple of tests:</p><pre>public class ChainOfResponsibilityTest {</pre><pre>    private static AuthenticationProcessor getChainOfAuthProcessor() {<br>        AuthenticationProcessor oAuthProcessor = new OAuthProcessor(null);<br>        return new UsernamePasswordProcessor(oAuthProcessor);<br>    }</pre><pre>    @Test<br>    public void givenOAuthProvider_whenCheckingAuthorized_thenSuccess() {<br>        AuthenticationProcessor authProcessorChain = getChainOfAuthProcessor();<br>        assertTrue(authProcessorChain.isAuthorized(new OAuthTokenProvider()));<br>    }</pre><pre>    @Test<br>    public void givenSamlProvider_whenCheckingAuthorized_thenSuccess() {<br>        AuthenticationProcessor authProcessorChain = getChainOfAuthProcessor();<br> <br>        assertFalse(authProcessorChain.isAuthorized(new SamlTokenProvider()));<br>    }<br>}</pre><p>The example above creates a chain of authentication processors: UsernamePasswordProcessor -&gt; OAuthProcessor. In the first test, the authorization succeeds, and in the other, it fails.</p><p>First, UsernamePasswordProcessor checks to see if the authentication provider is an instance of UsernamePasswordProvider.</p><p>Not being the expected input, UsernamePasswordProcessor delegates to OAuthProcessor.</p><p>Last, the OAuthProcessor processes the command. In the first test, there is a match and the test passes. In the second, there are no more processors in the chain, and, as a result, the test fails.</p><p>We need to keep few important principles in mind while implementing Chain of Responsibility:</p><ul><li>Each processor in the chain will have its implementation for processing a command In our example above, all processors have their implementation of isAuthorized</li><li>Every processor in the chain should have reference to the next processor Above, UsernamePasswordProcessor delegates to OAuthProcessor</li><li>Each processor is responsible for delegating to the next processor so beware of dropped commands Again in our example, if the command is an instance of SamlProvider then the request may not get processed and will be unauthorized</li><li>Processors should not form a recursive cycle In our example, we don’t have a cycle in our chain: UsernamePasswordProcessor -&gt; OAuthProcessor. But, if we explicitly set UsernamePasswordProcessor as next processor of OAuthProcessor, then we end up with a cycle in our chain: UsernamePasswordProcessor -&gt; OAuthProcessor -&gt; UsernamePasswordProcessor. Taking the next processor in the constructor can help with this</li><li>Only one processor in the chain handles a given command In our example, if an incoming command contains an instance of OAuthTokenProvider, then only OAuthProcessor will handle the command</li></ul><p>Disadvantages And now that we’ve seen how interesting Chain of Responsibility is, let’s keep in mind some drawbacks:</p><p>Mostly, it can get broken easily:</p><ul><li>if a processor fails to call the next processor, the command gets dropped</li><li>if a processor calls the wrong processor, it can lead to a cycle</li><li>It can create deep stack traces, which can affect performance</li><li>It can lead to duplicate code across processors, increasing maintenance</li></ul><h3>Other Architectural Patterns</h3><h3>Service Locator Pattern</h3><p>The purpose of the Service Locator pattern is to return the service instances on demand. This is useful for decoupling service consumers from concrete classes.</p><p>An implementation will consist of the following components:</p><ul><li>Client — the client object is a service consumer. It’s responsible for invoking the request from the service locator</li><li>Service Locator — is a communication entry point for returning the services from the cache</li><li>Cache — an object for storing service references to reuse them later</li><li>Initializer — creates and registers references to services in the cache</li><li>Service — the Service component represents the original services or their implementation</li></ul><p>The original service object is looked up by the locator and returned on demand.</p><p>First, we’ll create a MessagingService interface for sending messages in different ways:</p><pre>public interface MessagingService {</pre><pre>    String getMessageBody();<br>    String getServiceName();<br>}</pre><p>Next, we’ll define two implementations of the interface above, that send messages through email and SMS:</p><pre>public class EmailService implements MessagingService {</pre><pre>    public String getMessageBody() {<br>        return &quot;email message&quot;;<br>    }</pre><pre>    public String getServiceName() {<br>        return &quot;EmailService&quot;;<br>    }<br>}</pre><p>The SMSService class definition is similar to the EmailService class.</p><p>After defining the two services, we have to define the logic to initialize them:</p><pre>public class InitialContext {<br>    public Object lookup(String serviceName) {<br>        if (serviceName.equalsIgnoreCase(&quot;EmailService&quot;)) {<br>            return new EmailService();<br>        } else if (serviceName.equalsIgnoreCase(&quot;SMSService&quot;)) {<br>            return new SMSService();<br>        }<br>        return null;<br>    }<br>}</pre><p>The last component we need before putting the service locator object together is the cache.</p><p>In our example, this is a simple class with a List property:</p><pre>public class Cache {<br>    private List&lt;MessagingService&gt; services = new ArrayList&lt;&gt;();</pre><pre>    public MessagingService getService(String serviceName) {<br>        // retrieve from the list<br>    }</pre><pre>    public void addService(MessagingService newService) {<br>        // add to the list<br>    }<br>}</pre><p>services = new ArrayList(); public MessagingService getService(String serviceName) { // retrieve from the list } public void addService(MessagingService newService) { // add to the list } }” tabindex=”0&quot; role=”button” style=”box-sizing: border-box; position: relative; display: flex !important; padding: 0px !important; font-size: 14px; font-weight: var( — base-text-weight-medium, 500); line-height: 20px; white-space: nowrap; vertical-align: middle; cursor: pointer; user-select: none; border: 0px; border-radius: 6px; appearance: none; color: var( — fgColor-accent, var( — color-accent-fg)); background-color: transparent; box-shadow: none; transition: color 80ms cubic-bezier(0.33, 1, 0.68, 1) 0s, background-color, box-shadow, border-color; justify-content: center !important; align-items: center !important; margin: var( — base-size-8, 8px) !important; width: var( — control-small-size, 28px); height: var( — control-small-size, 28px);”&gt;</p><p>Finally, we can implement our service locator class:</p><pre>public class ServiceLocator {</pre><pre>    private static Cache cache = new Cache();</pre><pre>    public static MessagingService getService(String serviceName) {</pre><pre>        MessagingService service = cache.getService(serviceName);</pre><pre>        if (service != null) {<br>            return service;<br>        }</pre><pre>        InitialContext context = new InitialContext();<br>        MessagingService service1 = (MessagingService) context<br>          .lookup(serviceName);<br>        cache.addService(service1);<br>        return service1;<br>    }<br>}</pre><p>The logic here is fairly simple.</p><p>The class holds an instance of the Cache. Then, in the getService() method, it will first check the cache for an instance of the service. Then, if that’s null, it will call the initializing logic and add the new object to the cache. Finally, let’s consider a few reasons to avoid using the Service Locator pattern.</p><p>One argument against it is that it makes unit testing difficult. With dependency injection, we can pass mock objects of the dependent class to the tested instance. On the other hand, this is a bottleneck with the Service Locator pattern.</p><p>Another issue is that it’s trickier to use APIs based on this pattern. The reason for this is that the dependencies are hidden inside the class and they’re only verified at runtime.</p><h3>Front Controller Pattern</h3><p>n this tutorial we’ll be digging deeper into the Front Controller Pattern, part of the Enterprise Patterns as defined in Martin Fowler‘s book “Patterns of Enterprise Application Architecture”.</p><p>Front Controller is defined as “a controller that handles all requests for a Web site”. It stands in front of a web-application and delegates requests to subsequent resources. It also provides an interface to common behavior such as security, internationalization and presenting particular views to certain users.</p><p>This enables an application to change its behavior at runtime. Furthermore it helps to read and maintain an application by preventing code duplication.</p><p>The Front Controller consolidates all request handling by channeling requests through a single handler object.</p><p>The Front Controller Pattern is mainly divided into two parts. A single dispatching controller and a hierarchy of commands. his single controller dispatches requests to commands in order to trigger behavior associated with a request.</p><h3>Intercepting Filter Pattern</h3><p>Intercepting Filters are filters that trigger actions before or after an incoming request is processed by a handler.</p><p>Intercepting filters represents centralized components in a web application, common to all requests and extensible without affecting existing handlers.</p><p>Let’s extend the example from the previous guide and implement an authentication mechanism, request logging, and a visitor counter. In addition, we want the ability to deliver our pages in various different encoding.</p><p>All these are use cases for intercepting filters because they are common to all requests and should be independent of the handlers.</p><h3>Null Object Pattern</h3><p>In most object-oriented programming languages, we’re not allowed to use a null reference. That’s why we’re often forced to write null checks:</p><pre>Command cmd = getCommand();<br>if (cmd != null) {<br>    cmd.execute();<br>}</pre><p>Sometimes, if the number of such if statements get high, the code may become ugly, hard to read and error-prone. This is when the Null Object Pattern may come in handy.</p><p>The intent of the Null Object Pattern is to minimize that kind of null check. Instead, we can identify the null behavior and encapsulate it in the type expected by the client code. More often then not, such neutral logic is very simple — do nothing. This way we no longer need to deal with special handling of null references.</p><p>We simply may treat null objects the same way we treat any other instance of a given type that actually contains some more sophisticated business logic. Consequently, the client code stays cleaner.</p><p>As null objects should not have any state, there’s no need to create identical instances multiple times. Thus, we’ll often implement null objects as singletons.</p><p>As we can see, we can identify the following participants:</p><p>Client requires an instance of AbstractObject</p><ul><li>AbstractObject defines the contract Client expects — it may also contain shared logic for the implementing classes</li><li>RealObject implements AbstractObject and provides real behavior</li><li>NullObject implements AbstractObject and provides neutral behavior</li></ul><p>Imagine we have a message router application. Each message should have a valid priority assigned. Our system is supposed to route high priority messages to an SMS gateway whereas messages with medium priority should be routed to a JMS queue.</p><p>From time to time, however, messages with “undefined” or empty priority might come to our application. Such messages should be discarded from further processing.</p><p>First, we’ll create the Router interface:</p><pre>public interface Router {<br>    void route(Message msg);<br>}</pre><p>Next, let’s create two implementations of the above interface — the one responsible for routing to an SMS gateway and the one that will route the messages to JMS queue:</p><pre>public class SmsRouter implements Router {<br>    @Override<br>    public void route(Message msg) {<br>        // implementation details<br>    }<br>}</pre><pre>public class JmsRouter implements Router {<br>    @Override<br>    public void route(Message msg) {<br>        // implementation details<br>    }<br>}</pre><p>Finally, let’s implement our null object:</p><pre>public class NullRouter implements Router {<br>    @Override<br>    public void route(Message msg) {<br>        // do nothing<br>    }<br>}</pre><p>We’re now ready to put all the pieces together. Let’s see how the example client code may look like:</p><pre>public class RoutingHandler {<br>    public void handle(Iterable&lt;Message&gt; messages) {<br>        for (Message msg : messages) {<br>            Router router = RouterFactory.getRouterForMessage(msg);<br>            router.route(msg);<br>        }<br>    }<br>}</pre><p>messages) { for (Message msg : messages) { Router router = RouterFactory.getRouterForMessage(msg); router.route(msg); } } }” tabindex=”0&quot; role=”button” style=”box-sizing: border-box; position: relative; display: flex !important; padding: 0px !important; font-size: 14px; font-weight: var( — base-text-weight-medium, 500); line-height: 20px; white-space: nowrap; vertical-align: middle; cursor: pointer; user-select: none; border: 0px; border-radius: 6px; appearance: none; color: var( — fgColor-accent, var( — color-accent-fg)); background-color: transparent; box-shadow: none; transition: color 80ms cubic-bezier(0.33, 1, 0.68, 1) 0s, background-color, box-shadow, border-color; justify-content: center !important; align-items: center !important; margin: var( — base-size-8, 8px) !important; width: var( — control-small-size, 28px); height: var( — control-small-size, 28px);”&gt;</p><p>As we can see, we treat all Router objects the same way, no matter what implementation is returned by the RouterFactory. This allows us to keep our code clean and readable. We should use the Null Object Pattern when a Client would otherwise check for null just to skip execution or perform a default action. In such cases, we may encapsulate the neutral logic within a null object and return that to the client instead of the null value. This way client’s code no longer needs to be aware if a given instance is null or not.</p><p>Most of the developers would return Collections.emptyList() from findByNameAndLastname() in case none of the customers matches the provided search criteria. This is a very good example of following the Null Object Pattern.</p><p>In contrast, the getById() should return the customer with the given id. Someone calling this method expects to get the specific customer entity. In case no such customer exists we should explicitly return null to signal there is something wrong with the provided id.</p><p>As with all other patterns, we need to consider our specific use case before blindly implementing the Null Object Pattern. Otherwise, we may unintentionally introduce some bugs in our code that will be hard to find.</p><h3>The Gateway Pattern</h3><p>How to use the Gateway pattern to retrieve data from multiple services with a single request. Spring Cloud now also provides the Spring Cloud Gateway project which implements this pattern. One common use case for the Gateway pattern is to have endpoints that encapsulate commonly called services. This can increase performance by reducing the number of client requests.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c90eba36414e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Memory Management in jav]]></title>
            <link>https://medium.com/@priyankalovesgaurav004/memory-management-in-jav-ac37efa699cd?source=rss-7f8ef520f5f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac37efa699cd</guid>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Be You]]></dc:creator>
            <pubDate>Tue, 25 Jun 2024 11:04:16 GMT</pubDate>
            <atom:updated>2024-06-25T11:04:16.246Z</atom:updated>
            <content:encoded><![CDATA[<h3>Memory Management in java</h3><h3>What Does the Statement “Memory Is Managed in Java” Mean?</h3><p>Memory is the key resource an application requires to run effectively and like any resource, it is scarce. As such, its allocation and deallocation to and from applications or different parts of an application require a lot of care and consideration.</p><p>However, in Java, a developer does not need to explicitly allocate and deallocate memory — the JVM and more specifically the Garbage Collector — has the duty of handling memory allocation so that the developer doesn’t have to.</p><p>This is contrary to what happens in languages like C where a programmer has direct access to memory and literally references memory cells in his code, creating a lot of room for memory leaks.</p><h3>What Is Garbage Collection and What Are Its Advantages?</h3><p>Garbage collection is the process of looking at heap memory, identifying which objects are in use and which are not, and deleting the unused objects.</p><p>An in-use object, or a referenced object, means that some part of your program still maintains a pointer to that object. An unused object, or unreferenced object, is no longer referenced by any part of your program. So the memory used by an unreferenced object can be reclaimed.</p><p>The biggest advantage of garbage collection is that it removes the burden of manual memory allocation/deallocation from us so that we can focus on solving the problem at hand.</p><h3>Are There Any Disadvantages of Garbage Collection?</h3><p>Yes. Whenever the garbage collector runs, it has an effect on the application’s performance. This is because all other threads in the application have to be stopped to allow the garbage collector thread to effectively do its work.</p><p>Depending on the requirements of the application, this can be a real problem that is unacceptable by the client. However, this problem can be greatly reduced or even eliminated through skillful optimization and garbage collector tuning and using different GC algorithms.</p><h3>What Is the Meaning of the Term “Stop-The-World”?</h3><p>When the garbage collector thread is running, other threads are stopped, meaning the application is stopped momentarily. This is analogous to house cleaning or fumigation where occupants are denied access until the process is complete.</p><p>Depending on the needs of an application, “stop the world” garbage collection can cause an unacceptable freeze. This is why it is important to do garbage collector tuning and JVM optimization so that the freeze encountered is at least acceptable.</p><h3>What Are Stack and Heap? What Is Stored in Each of These Memory Structures, and How Are They Interrelated?</h3><p>The stack is a part of memory that contains information about nested method calls down to the current position in the program. It also contains all local variables and references to objects on the heap defined in currently executing methods.</p><p>This structure allows the runtime to return from the method knowing the address whence it was called, and also clear all local variables after exiting the method. Every thread has its own stack.</p><p>The heap is a large bulk of memory intended for allocation of objects. When you create an object with the new keyword, it gets allocated on the heap. However, the reference to this object lives on the stack.</p><h3>What Is Generational Garbage Collection and What Makes It a Popular Garbage Collection Approach?</h3><p>Generational garbage collection can be loosely defined as the strategy used by the garbage collector where the heap is divided into a number of sections called generations, each of which will hold objects according to their “age” on the heap.</p><p>Whenever the garbage collector is running, the first step in the process is called marking. This is where the garbage collector identifies which pieces of memory are in use and which are not. This can be a very time-consuming process if all objects in a system must be scanned.</p><p>As more and more objects are allocated, the list of objects grows and grows leading to longer and longer garbage collection time. However, empirical analysis of applications has shown that most objects are short-lived.</p><p>With generational garbage collection, objects are grouped according to their “age” in terms of how many garbage collection cycles they have survived. This way, the bulk of the work spread across various minor and major collection cycles.</p><p>Today, almost all garbage collectors are generational. This strategy is so popular because, over time, it has proven to be the optimal solution.</p><h3>Describe in Detail How Generational Garbage Collection Works</h3><p>To properly understand how generational garbage collection works, it is important to first remember how Java heap is structured to facilitate generational garbage collection.</p><p>The heap is divided up into smaller spaces or generations. These spaces are Young Generation, Old or Tenured Generation, and Permanent Generation.</p><p>The young generation hosts most of the newly created objects. An empirical study of most applications shows that majority of objects are quickly short lived and therefore, soon become eligible for collection. Therefore, new objects start their journey here and are only “promoted” to the old generation space after they have attained a certain “age”.</p><p>The term “age” in generational garbage collection refers to the number of collection cycles the object has survived.</p><p>The young generation space is further divided into three spaces: an Eden space and two survivor spaces such as Survivor 1 (s1) and Survivor 2 (s2).</p><p>The old generation hosts objects that have lived in memory longer than a certain “age”. The objects that survived garbage collection from the young generation are promoted to this space. It is generally larger than the young generation. As it is bigger in size, the garbage collection is more expensive and occurs less frequently than in the young generation.</p><p>The permanent generation or more commonly called, PermGen, contains metadata required by the JVM to describe the classes and methods used in the application. It also contains the string pool for storing interned strings. It is populated by the JVM at runtime based on classes in use by the application. In addition, platform library classes and methods may be stored here.</p><p>First, any new objects are allocated to the Eden space. Both survivor spaces start out empty. When the Eden space fills up, a minor garbage collection is triggered. Referenced objects are moved to the first survivor space. Unreferenced objects are deleted.</p><p>During the next minor GC, the same thing happens to the Eden space. Unreferenced objects are deleted and referenced objects are moved to a survivor space. However, in this case, they are moved to the second survivor space (S2).</p><p>In addition, objects from the last minor GC in the first survivor space (S1) have their age incremented and are moved to S2. Once all surviving objects have been moved to S2, both S1 and Eden space are cleared. At this point, S2 contains objects with different ages.</p><p>At the next minor GC, the same process is repeated. However this time the survivor spaces switch. Referenced objects are moved to S1 from both Eden and S2. Surviving objects are aged. Eden and S2 are cleared.</p><p>After every minor garbage collection cycle, the age of each object is checked. Those that have reached a certain arbitrary age, for example, 8, are promoted from the young generation to the old or tenured generation. For all subsequent minor GC cycles, objects will continue to be promoted to the old generation space.</p><p>This pretty much exhausts the process of garbage collection in the young generation. Eventually, a major garbage collection will be performed on the old generation which cleans up and compacts that space. For each major GC, there are several minor GCs.</p><h3>When Does an Object Become Eligible for Garbage Collection? Describe How the Gc Collects an Eligible Object?</h3><p>An object becomes eligible for Garbage collection or GC if it is not reachable from any live threads or by any static references.</p><p>The most straightforward case of an object becoming eligible for garbage collection is if all its references are null. Cyclic dependencies without any live external reference are also eligible for GC. So if object A references object B and object B references Object A and they don’t have any other live reference then both Objects A and B will be eligible for Garbage collection.</p><p>Another obvious case is when a parent object is set to null. When a kitchen object internally references a fridge object and a sink object, and the kitchen object is set to null, both fridge and sink will become eligible for garbage collection alongside their parent, kitchen.</p><h3>How Do You Trigger Garbage Collection from Java Code?</h3><p>You, as Java programmer, can not force garbage collection in Java; it will only trigger if JVM thinks it needs a garbage collection based on Java heap size.</p><p>Before removing an object from memory garbage collection thread invokes finalize() method of that object and gives an opportunity to perform any sort of cleanup required. You can also invoke this method of an object code, however, there is no guarantee that garbage collection will occur when you call this method.</p><p>Additionally, there are methods like System.gc() and Runtime.gc() which is used to send request of Garbage collection to JVM but it’s not guaranteed that garbage collection will happen.</p><h3>What Happens When There Is Not Enough Heap Space to Accommodate Storage of New Objects?</h3><p>If there is no memory space for creating a new object in Heap, Java Virtual Machine throws OutOfMemoryError or more specifically java.lang.OutOfMemoryError heap space.</p><h3>Is It Possible to «Resurrect» an Object That Became Eligible for Garbage Collection?</h3><p>When an object becomes eligible for garbage collection, the GC has to run the finalize method on it. The finalize method is guaranteed to run only once, thus the GC flags the object as finalized and gives it a rest until the next cycle.</p><p>In the finalize method you can technically “resurrect” an object, for example, by assigning it to a static field. The object would become alive again and non-eligible for garbage collection, so the GC would not collect it during the next cycle.</p><p>The object, however, would be marked as finalized, so when it would become eligible again, the finalize method would not be called. In essence, you can turn this “resurrection” trick only once for the lifetime of the object. Beware that this ugly hack should be used only if you really know what you’re doing — however, understanding this trick gives some insight into how the GC works.</p><h3>Describe Strong, Weak, Soft and Phantom References and Their Role in Garbage Collection.</h3><p>Much as memory is managed in Java, an engineer may need to perform as much optimization as possible to minimize latency and maximize throughput, in critical applications. Much as it is impossible to explicitly control when garbage collection is triggered in the JVM, it is possible to influence how it occurs as regards the objects we have created.</p><p>Java provides us with reference objects to control the relationship between the objects we create and the garbage collector.</p><p>By default, every object we create in a Java program is strongly referenced by a variable:</p><pre>StringBuilder sb = new StringBuilder();</pre><p>In the above snippet, the new keyword creates a new StringBuilder object and stores it on the heap. The variable sb then stores a strong reference to this object. What this means for the garbage collector is that the particular StringBuilder object is not eligible for collection at all due to a strong reference held to it by sb. The story only changes when we nullify sb like this:</p><pre>sb = null;</pre><p>After calling the above line, the object will then be eligible for collection.</p><p>We can change this relationship between the object and the garbage collector by explicitly wrapping it inside another reference object which is located inside java.lang.ref package.</p><p>A soft reference can be created to the above object like this:</p><pre>StringBuilder sb = new StringBuilder();<br>SoftReference&lt;StringBuilder&gt; sbRef = new SoftReference&lt;&gt;(sb);<br>sb = null;</pre><p>sbRef = new SoftReference(sb); sb = null;” tabindex=”0&quot; role=”button” style=”box-sizing: border-box; position: relative; display: flex !important; padding: 0px !important; font-size: 14px; font-weight: var( — base-text-weight-medium, 500); line-height: 20px; white-space: nowrap; vertical-align: middle; cursor: pointer; user-select: none; border: 0px; border-radius: 6px; appearance: none; color: var( — fgColor-accent, var( — color-accent-fg)); background-color: transparent; box-shadow: none; transition: color 80ms cubic-bezier(0.33, 1, 0.68, 1) 0s, background-color, box-shadow, border-color; justify-content: center !important; align-items: center !important; margin: var( — base-size-8, 8px) !important; width: var( — control-small-size, 28px); height: var( — control-small-size, 28px);”&gt;</p><p>In the above snippet, we have created two references to the StringBuilder object. The first line creates a strong reference sb and the second line creates a soft reference sbRef. The third line should make the object eligible for collection but the garbage collector will postpone collecting it because of sbRef.</p><p>The story will only change when memory becomes tight and the JVM is on the brink of throwing an OutOfMemory error. In other words, objects with only soft references are collected as a last resort to recover memory.</p><p>A weak reference can be created in a similar manner using WeakReference class. When sb is set to null and the StringBuilder object only has a weak reference, the JVM’s garbage collector will have absolutely no compromise and immediately collect the object at the very next cycle.</p><p>A phantom reference is similar to a weak reference and an object with only phantom references will be collected without waiting. However, phantom references are enqueued as soon as their objects are collected. We can poll the reference queue to know exactly when the object was collected.</p><h3>Suppose We Have a Circular Reference (Two Objects That Reference Each Other). Could Such Pair of Objects Become Eligible for Garbage Collection and Why?</h3><p>Yes, a pair of objects with a circular reference can become eligible for garbage collection. This is because of how Java’s garbage collector handles circular references. It considers objects live not when they have any reference to them, but when they are reachable by navigating the object graph starting from some garbage collection root (a local variable of a live thread or a static field). If a pair of objects with a circular reference is not reachable from any root, it is considered eligible for garbage collection.</p><h3>How Are Strings Represented in Memory?</h3><p>A String instance in Java is an object with two fields: a char[] value field and an int hash field. The value field is an array of chars representing the string itself, and the hash field contains the hashCode of a string which is initialized with zero, calculated during the first hashCode() call and cached ever since. As a curious edge case, if a hashCode of a string has a zero value, it has to be recalculated each time the hashCode() is called.</p><p>Important thing is that a String instance is immutable: you can’t get or modify the underlying char[] array. Another feature of strings is that the static constant strings are loaded and cached in a string pool. If you have multiple identical String objects in your source code, they are all represented by a single instance at runtime.</p><h3>What Is a Stringbuilder and What Are Its Use Cases?</h3><p>StringBuilder allows manipulating character sequences by appending, deleting and inserting characters and strings. This is a mutable data structure, as opposed to the String class which is immutable.</p><p>When concatenating two String instances, a new object is created, and strings are copied. This could bring a huge garbage collector overhead if we need to create or modify a string in a loop. StringBuilder allows handling string manipulations much more efficiently.</p><p>StringBuffer is different from StringBuilder in that it is thread-safe. If you need to manipulate a string in a single thread, use StringBuilder instead.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac37efa699cd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hibernate Interview]]></title>
            <link>https://medium.com/@priyankalovesgaurav004/hibernate-interview-c5da0ff4c15d?source=rss-7f8ef520f5f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5da0ff4c15d</guid>
            <category><![CDATA[orm]]></category>
            <category><![CDATA[hibernate]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Be You]]></dc:creator>
            <pubDate>Tue, 25 Jun 2024 11:00:31 GMT</pubDate>
            <atom:updated>2024-06-25T11:00:31.259Z</atom:updated>
            <content:encoded><![CDATA[<h3>Hibernate Interview Questions</h3><h3>What is ORM in Hibernate?</h3><p>Hibernate ORM stands for Object Relational Mapping. This is a mapping tool pattern mainly used for converting data stored in a relational database to an object used in object-oriented programming constructs. This tool also helps greatly in simplifying data retrieval, creation, and manipulation.</p><h3>What are the advantages of Hibernate over JDBC?</h3><ul><li>Clean Readable Code: Using hibernate, helps in eliminating a lot of JDBC API-based boiler-plate codes, thereby making the code look cleaner and readable.</li><li>HQL (Hibernate Query Language): Hibernate provides HQL which is closer to Java and is object-oriented in nature. This helps in reducing the burden on developers for writing database independent queries. In JDBC, this is not the case. A developer has to know the database-specific codes.</li><li>Transaction Management: JDBC doesn’t support implicit transaction management. It is upon the developer to write transaction management code using commit and rollback methods. Whereas, Hibernate implicity provides this feature.</li><li>Exception Handling: Hibernate wraps the JDBC exceptions and throws unchecked exceptions like JDBCException or HibernateException. This along with the built-in transaction management system helps developers to avoid writing multiple try-catch blocks to handle exceptions. In the case of JDBC, it throws a checked exception called SQLException thereby mandating the developer to write try-catch blocks to handle this exception at compile time.</li><li>Special Features: Hibernate supports OOPs features like inheritance, associations and also supports collections. These are not available in JDBC.</li></ul><h3>What are some of the important interfaces of Hibernate framework?</h3><p>Hibernate core interfaces are:</p><ul><li>Configuration</li><li>SessionFactory</li><li>Session</li><li>Criteria</li><li>Query</li><li>Transaction</li></ul><h3>What is a Session in Hibernate?</h3><p>A session is an object that maintains the connection between Java object application and database. Session also has methods for storing, retrieving, modifying or deleting data from database using methods like persist(), load(), get(), update(), delete(), etc. Additionally, It has factory methods to return Query, Criteria, and Transaction objects.</p><h3>What is a SessionFactory?</h3><p>SessionFactory provides an instance of Session. It is a factory class that gives the Session objects based on the configuration parameters in order to establish the connection to the database. As a good practice, the application generally has a single instance of SessionFactory. The internal state of a SessionFactory which includes metadata about ORM is immutable, i.e once the instance is created, it cannot be changed.</p><p>This also provides the facility to get information like statistics and metadata related to a class, query executions, etc. It also holds second-level cache data if enabled.</p><h3>Can you explain what is lazy loading in hibernate?</h3><p>Lazy loading is mainly used for improving the application performance by helping to load the child objects on demand.</p><p>It is to be noted that, since Hibernate 3 version, this feature has been enabled by default. This signifies that child objects are not loaded until the parent gets loaded.</p><h3>What is the difference between first level cache and second level cache?</h3><p>Hibernate has 2 cache types. First level and second level cache for which the difference is given below:</p><p>First Level CacheSecond Level CacheThis is local to the Session object and cannot be shared between multiple sessions.This cache is maintained at the SessionFactory level and shared among all sessions in Hibernate.This cache is enabled by default and there is no way to disable it.This is disabled by default, but we can enable it through configuration.The first level cache is available only until the session is open, once the session is closed, the first level cache is destroyed.The second-level cache is available through the application’s life cycle, it is only destroyed and recreated when an application is restarted.</p><p>If an entity or object is loaded by calling the get() method then Hibernate first checked the first level cache, if it doesn’t find the object then it goes to the second level cache if configured. If the object is not found then it finally goes to the database and returns the object, if there is no corresponding row in the table then it returns null.</p><h3>Can you explain the concept behind Hibernate Inheritance Mapping?</h3><p>Java is an Object-Oriented Programming Language and Inheritance is one of the most important pillars of object-oriented principles. To represent any models in Java, inheritance is most commonly used to simplify and simplify the relationship. But, there is a catch. Relational databases do not support inheritance. They have a flat structure.</p><p>There are different inheritance mapping strategies available:</p><ul><li>Single Table Strategy</li><li>Table Per Class Strategy</li><li>Mapped Super Class Strategy</li><li>Joined Table Strategy</li></ul><h3>What are the most commonly used annotations available to support hibernate mapping?</h3><ul><li>javax.persistence.Entity: This annotation is used on the model classes by using “@Entity” and tells that the classes are entity beans.</li><li>javax.persistence.Table: This annotation is used on the model classes by using “@Table” and tells that the class maps to the table name in the database.</li><li>javax.persistence.Access: This is used as “@Access” and is used for defining the access type of either field or property. When nothing is specified, the default value taken is “field”.</li><li>javax.persistence.Id: This is used as “@Id” and is used on the attribute in a class to indicate that attribute is the primary key in the bean entity.</li><li>javax.persistence.EmbeddedId: Used as “@EmbeddedId” upon the attribute and indicates it is a composite primary key of the bean entity.</li><li>javax.persistence.Column: “@Column” is used for defining the column name in the database table.</li><li>javax.persistence.GeneratedValue: “@GeneratedValue” is used for defining the strategy used for primary key generation. This annotation is used along with javax.persistence.GenerationType enum.</li><li>javax.persistence.OneToOne: “@OneToOne” is used for defining the one-to-one mapping between two bean entities. Similarly, hibernate provides OneToMany, ManyToOne and ManyToMany annotations for defining different mapping types.</li><li>org.hibernate.annotations.Cascade: “@Cascade” annotation is used for defining the cascading action between two bean entities. It is used with org.hibernate.annotations.CascadeType enum to define the type of cascading.</li></ul><h3>Differentiate between get() and load() in Hibernate session</h3><p>get()load()This method gets the data from the database as soon as it is called.This method returns a proxy object and loads the data only when it is required.The database is hit every time the method is called.The database is hit only when it is really needed and this is called Lazy Loading which makes the method better.The method returns null if the object is not found.The method throws ObjectNotFoundException if the object is not found.This method should be used if we are unsure about the existence of data in the database.This method is to be used when we know for sure that the data is present in the database.</p><h3>What is criteria API in hibernate?</h3><p>Criteria API in Hibernate helps developers to build dynamic criteria queries on the persistence database. Criteria API is a more powerful and flexible alternative to HQL (Hibernate Query Language) queries for creating dynamic queries.</p><p>This API allows to programmatically development criteria query objects. The org.hibernate.Criteria interface is used for these purposes. The Session interface of hibernate framework has createCriteria() method that takes the persistent object’s class or its entity name as the parameters and returns persistence object instance the criteria query is executed.</p><p>It also makes it very easy to incorporate restrictions to selectively retrieve data from the database. It can be achieved by using the add() method which accepts the org.hibernate.criterion.Criterion object representing individual restriction.</p><p>To return all the data of InterviewBitEmployee entity class.</p><pre>Criteria criteria = session.createCriteria(InterviewBitEmployee.class);<br>List&lt;InterviewBitEmployee&gt; results = criteria.list();</pre><p>results = criteria.list();” tabindex=”0&quot; role=”button” style=”box-sizing: border-box; position: relative; display: flex !important; padding: 0px !important; font-size: 14px; font-weight: var( — base-text-weight-medium, 500); line-height: 20px; white-space: nowrap; vertical-align: middle; cursor: pointer; user-select: none; border: 0px; border-radius: 6px; appearance: none; color: var( — fgColor-accent, var( — color-accent-fg)); background-color: transparent; box-shadow: none; transition: color 80ms cubic-bezier(0.33, 1, 0.68, 1) 0s, background-color, box-shadow, border-color; justify-content: center !important; align-items: center !important; margin: var( — base-size-8, 8px) !important; width: var( — control-small-size, 28px); height: var( — control-small-size, 28px);”&gt;</p><p>To retrive objects whose property has value equal to the restriction, we use Restrictions.eq() method. For example, to fetch all records with name ‘Hibernate’:</p><pre>Criteria criteria= session.createCriteria(InterviewBitEmployee.class);<br>criteria.add(Restrictions.eq(&quot;fullName&quot;,&quot;Hibernate&quot;));<br>List&lt;InterviewBitEmployee&gt; results = criteria.list();</pre><p>results = criteria.list();” tabindex=”0&quot; role=”button” style=”box-sizing: border-box; position: relative; display: flex !important; padding: 0px !important; font-size: 14px; font-weight: var( — base-text-weight-medium, 500); line-height: 20px; white-space: nowrap; vertical-align: middle; cursor: pointer; user-select: none; border: 0px; border-radius: 6px; appearance: none; color: var( — fgColor-accent, var( — color-accent-fg)); background-color: transparent; box-shadow: none; transition: color 80ms cubic-bezier(0.33, 1, 0.68, 1) 0s, background-color, box-shadow, border-color; justify-content: center !important; align-items: center !important; margin: var( — base-size-8, 8px) !important; width: var( — control-small-size, 28px); height: var( — control-small-size, 28px);”&gt;</p><p>To get objects whose property has the value “not equal to” the restriction, we use Restrictions.ne() method. For example, to fetch all the records whose employee’s name is not Hibernate:</p><pre>Criteria criteria= session.createCriteria(InterviewBitEmployee.class);<br>criteria.add(Restrictions.ne(&quot;fullName&quot;,&quot;Hibernate&quot;));<br>List&lt;Employee&gt; results = criteria.list()</pre><p>results = criteria.list()” tabindex=”0&quot; role=”button” style=”box-sizing: border-box; position: relative; display: flex !important; padding: 0px !important; font-size: 14px; font-weight: var( — base-text-weight-medium, 500); line-height: 20px; white-space: nowrap; vertical-align: middle; cursor: pointer; user-select: none; border: 0px; border-radius: 6px; appearance: none; color: var( — fgColor-accent, var( — color-accent-fg)); background-color: transparent; box-shadow: none; transition: color 80ms cubic-bezier(0.33, 1, 0.68, 1) 0s, background-color, box-shadow, border-color; justify-content: center !important; align-items: center !important; margin: var( — base-size-8, 8px) !important; width: var( — control-small-size, 28px); height: var( — control-small-size, 28px);”&gt;</p><p>To retrieve all objects whose property matches a given pattern, we use Restrictions.like() (for case sensitivenes) and Restrictions.ilike()(for case insensitiveness)</p><pre>Criteria criteria= session.createCriteria(InterviewBitEmployee.class);<br>criteria.add(Restrictions.like(&quot;fullName&quot;,&quot;Hib%&quot;,MatchMode.ANYWHERE));<br>List&lt;InterviewBitEmployee&gt; results = criteria.list();</pre><p>results = criteria.list();” tabindex=”0&quot; role=”button” style=”box-sizing: border-box; position: relative; display: flex !important; padding: 0px !important; font-size: 14px; font-weight: var( — base-text-weight-medium, 500); line-height: 20px; white-space: nowrap; vertical-align: middle; cursor: pointer; user-select: none; border: 0px; border-radius: 6px; appearance: none; color: var( — fgColor-accent, var( — color-accent-fg)); background-color: transparent; box-shadow: none; transition: color 80ms cubic-bezier(0.33, 1, 0.68, 1) 0s, background-color, box-shadow, border-color; justify-content: center !important; align-items: center !important; margin: var( — base-size-8, 8px) !important; width: var( — control-small-size, 28px); height: var( — control-small-size, 28px);”&gt;</p><h3>What is HQL?</h3><p>Hibernate Query Language (HQL) is used as an extension of SQL. It is very simple, efficient, and very flexible for performing complex operations on relational databases without writing complicated queries. HQL is the object-oriented representation of query language, i.e instead of using table name, we make use of the class name which makes this language independent of any database.</p><pre>Query query=session.createQuery(&quot;from InterviewBitEmployee&quot;);  <br>List&lt;InterviewBitEmployee&gt; list=query.list();  <br>System.out.println(list.get(0));</pre><p>list=query.list(); System.out.println(list.get(0));” tabindex=”0&quot; role=”button” style=”box-sizing: border-box; position: relative; display: flex !important; padding: 0px !important; font-size: 14px; font-weight: var( — base-text-weight-medium, 500); line-height: 20px; white-space: nowrap; vertical-align: middle; cursor: pointer; user-select: none; border: 0px; border-radius: 6px; appearance: none; color: var( — fgColor-accent, var( — color-accent-fg)); background-color: transparent; box-shadow: none; transition: color 80ms cubic-bezier(0.33, 1, 0.68, 1) 0s, background-color, box-shadow, border-color; justify-content: center !important; align-items: center !important; margin: var( — base-size-8, 8px) !important; width: var( — control-small-size, 28px); height: var( — control-small-size, 28px);”&gt;</p><h3>Does Hibernate support Native SQL Queries?</h3><p>Yes, it does. Hibernate provides the createSQLQuery() method to let a developer call the native SQL statement directly and returns a Query object.</p><p>Consider the example where you want to get employee data with the full name “Hibernate”. We don’t want to use HQL-based features, instead, we want to write our own SQL queries. In this case, the code would be:</p><pre>Query query = session.createSQLQuery( &quot;select * from interviewbit_employee ibe where ibe.fullName = :fullName&quot;)<br>                   .addEntity(InterviewBitEmployee.class)<br>                   .setParameter(&quot;fullName&quot;, &quot;Hibernate&quot;); //named parameters<br>List result = query.list();</pre><p>Alternatively, native queries can also be supported when using NamedQueries.</p><h3>Can you tell something about the N+1 SELECT problem in Hibernate?</h3><p>N+1 SELECT problem is due to the result of using lazy loading and on-demand fetching strategy. Let’s take an example. If you have an N items list and each item from the list has a dependency on a collection of another object, say bid. In order to find the highest bid for each item while using the lazy loading strategy, hibernate has to first fire 1 query to load all items and then subsequently fire N queries to load big of each item. Hence, hibernate actually ends up executing N+1 queries.</p><h3>How to solve N+1 SELECT problem in Hibernate?</h3><p>Some of the strategies followed for solving the N+1 SELECT problem are:</p><ul><li>Pre-fetch the records in batches which helps us to reduce the problem of N+1 to (N/K) + 1 where K refers to the size of the batch.</li><li>Subselect the fetching strategy</li><li>As last resort, try to avoid or disable lazy loading altogether.</li></ul><h3>What is Single Table Strategy?</h3><p>Single Table Strategy is a hibernate’s strategy for performing inheritance mapping. This strategy is considered to be the best among all the other existing ones. Here, the inheritance data hierarchy is stored in the single table by making use of a discriminator column which determines to what class the record belongs.</p><pre>@Entity<br>@Table(name = &quot;InterviewBitEmployee&quot;)<br>@Inheritance(strategy = InheritanceType.SINGLE_TABLE)<br>@DiscriminatorColumn(name = &quot;employee_type&quot;)<br>@NoArgsConstructor<br>@AllArgsConstructor<br>public class InterviewBitEmployee {<br>   @Id<br>   @Column(name = &quot;employee_id&quot;)<br>   private String employeeId;<br>   private String fullName;<br>   private String email;<br>}</pre><h3>Can you tell something about Table Per Class Strategy.</h3><p>Table Per Class Strategy is another type of inheritance mapping strategy where each class in the hierarchy has a corresponding mapping database table. Hibernate provides @Inheritance annotation which takes strategy as the parameter. This is used for defining what strategy we would be using. By giving them value, InheritanceType.TABLE_PER_CLASS, it signifies that we are using a table per class strategy for mapping.</p><pre>@Entity(name = &quot;interviewbit_employee&quot;)<br>@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)<br>@NoArgsConstructor<br>@AllArgsConstructor<br>public class InterviewBitEmployee {<br>   @Id<br>   @Column(name = &quot;employee_id&quot;)<br>   private String employeeId;<br>   private String fullName;<br>   private String email;<br>}</pre><h3>Can you tell something about Named SQL Query</h3><p>A named SQL query is an expression represented in the form of a table. Here, SQL expressions to select/retrieve rows and columns from one or more tables in one or more databases can be specified. This is like using aliases to the queries.</p><p>In hibernate, we can make use of @NameQueries and @NameQuery annotations.</p><p>@NameQueries annotation is used for defining multiple named queries. @NameQuery annotation is used for defining a single named query.</p><pre>@NamedQueries(  <br>   {  <br>       @NamedQuery(  <br>       name = &quot;findIBEmployeeByFullName&quot;,  <br>       query = &quot;from InterviewBitEmployee e where e.fullName = :fullName&quot;  <br>       )  <br>   }  <br>)</pre><p>usage</p><pre>TypedQuery query = session.getNamedQuery(&quot;findIBEmployeeByFullName&quot;);    <br>query.setParameter(&quot;fullName&quot;,&quot;Hibernate&quot;);   <br>List&lt;InterviewBitEmployee&gt; ibEmployees = query.getResultList();</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5da0ff4c15d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Git Interview]]></title>
            <link>https://medium.com/@priyankalovesgaurav004/git-interview-9a00bf0bf991?source=rss-7f8ef520f5f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a00bf0bf991</guid>
            <category><![CDATA[github]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[git]]></category>
            <dc:creator><![CDATA[Be You]]></dc:creator>
            <pubDate>Tue, 25 Jun 2024 10:57:25 GMT</pubDate>
            <atom:updated>2024-06-25T10:57:25.670Z</atom:updated>
            <content:encoded><![CDATA[<h3>Git Interview Questions</h3><h3>Difference between git commit and git push command.</h3><p>git commit records changes to the local repository while git push updates the changes to the remote repository and the changes be visible to the other users.</p><h3>Difference between git pull and fetch.</h3><p>Git fetch gathers any commits from the target branch that do not exist in your current branch and stores them in your local repository. However, it does not merge them with your current branch.</p><p>Git pull update your current HEAD branch with the latest changes from the remote server. This means that pull not only downloads new data and also directly integrates it into your current working copy files.</p><h3>What is Git stash?</h3><p>git stash temporarily shelves (or stashes) changes you have made to your working copy so you can work on something else, and then come back and re-apply them later on.</p><h3>Explain git status command.</h3><p>The git status command displays the state of the working directory and the staging area. It lets you see which changes have been staged, which haven’t, and which files aren’t being tracked by Git.</p><h3>Explain git revert command.</h3><p>The git revert command is used for undoing changes to a repository’s commit history. Git revert expects a commit ref passed in. To revert the latest commit use git revert HEAD command.</p><p>git revert simply creates a new commit that is the opposite of an existing commit. So a git push need to be followed to update in remote repository.</p><h3>How to view the commit history in git?</h3><p>git log command lists the commits made in that repository in reverse chronological so that most recent commits show up first.</p><h3>Difference between git merge vs rebase.</h3><p>Both does the same thing (integrate branches) in slightly different way.</p><p>The major benefit of rebasing is that you get a much cleaner project history. First, it eliminates the unnecessary merge commits required by git merge. Rebasing is the process of moving or combining a sequence of commits to a new base commit.</p><h3>What is cherry-pick in GIT?</h3><p>Cherry picking means to choose a specific commit from one branch and apply it onto another.</p><p>It is a 2 step process where you need to check-out to the branch where you want to apply the commit and then apply the commit by its commit-hash.</p><pre>git checkout master<br>git cherry-pick &lt;commit-hash&gt;</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a00bf0bf991" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Concurrency Interview Questions]]></title>
            <link>https://medium.com/@priyankalovesgaurav004/java-concurrency-interview-questions-c2fc3b0b82b6?source=rss-7f8ef520f5f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2fc3b0b82b6</guid>
            <category><![CDATA[java-interview-questions]]></category>
            <dc:creator><![CDATA[Be You]]></dc:creator>
            <pubDate>Tue, 25 Jun 2024 10:51:19 GMT</pubDate>
            <atom:updated>2024-06-25T10:51:19.348Z</atom:updated>
            <content:encoded><![CDATA[<h3>What Is the Difference Between a Process and a Thread?</h3><p>Both processes and threads are units of concurrency, but they have a fundamental difference: processes do not share a common memory, while threads do.</p><p>From the operating system’s point of view, a process is an independent piece of software that runs in its own virtual memory space. Any multitasking operating system (which means almost any modern operating system) has to separate processes in memory so that one failing process wouldn’t drag all other processes down by scrambling common memory.</p><p>The processes are thus usually isolated, and they cooperate by the means of inter-process communication which is defined by the operating system as a kind of intermediate API.</p><p>On the contrary, a thread is a part of an application that shares a common memory with other threads of the same application. Using common memory allows to shave off lots of overhead, design the threads to cooperate and exchange data between them much faster.</p><h3>How Can You Create a Thread Instance and Run It?</h3><p>To create an instance of a thread, you have two options. First, pass a Runnable instance to its constructor and call start(). Runnable is a functional interface, so it can be passed as a lambda expression:</p><pre>Thread thread1 = new Thread(() -&gt;<br>  System.out.println(&quot;Hello World from Runnable!&quot;));<br>thread1.start();</pre><p>System.out.println(“Hello World from Runnable!”)); thread1.start();” tabindex=”0&quot; role=”button” style=”box-sizing: border-box; position: relative; display: flex !important; padding: 0px !important; font-size: 14px; font-weight: var( — base-text-weight-medium, 500); line-height: 20px; white-space: nowrap; vertical-align: middle; cursor: pointer; user-select: none; border: 0px; border-radius: 6px; appearance: none; color: var( — fgColor-accent, var( — color-accent-fg)); background-color: transparent; box-shadow: none; transition: color 80ms cubic-bezier(0.33, 1, 0.68, 1) 0s, background-color, box-shadow, border-color; justify-content: center !important; align-items: center !important; margin: var( — base-size-8, 8px) !important; width: var( — control-small-size, 28px); height: var( — control-small-size, 28px);”&gt;</p><p>Thread also implements Runnable, so another way of starting a thread is to create an anonymous subclass, override its run() method, and then call start():</p><pre>Thread thread2 = new Thread() {<br>    @Override<br>    public void run() {<br>        System.out.println(&quot;Hello World from subclass!&quot;);<br>    }<br>};<br>thread2.start();</pre><h3>Describe the Different States of a Thread and When Do the State Transitions Occur.</h3><p>The state of a Thread can be checked using the Thread.getState() method. Different states of a Thread are described in the Thread.State enum. They are:</p><ul><li>NEW — a new Thread instance that was not yet started via Thread.start()</li><li>RUNNABLE — a running thread. It is called runnable because at any given time it could be either running or waiting for the next quantum of time from the thread scheduler. A NEW thread enters the RUNNABLE state when you call Thread.start() on it</li><li>BLOCKED — a running thread becomes blocked if it needs to enter a synchronized section but cannot do that due to another thread holding the monitor of this section</li><li>WAITING — a thread enters this state if it waits for another thread to perform a particular action. For instance, a thread enters this state upon calling the Object.wait() method on a monitor it holds, or the Thread.join() method on another thread</li><li>TIMED_WAITING — same as the above, but a thread enters this state after calling timed versions of Thread.sleep(), Object.wait(), Thread.join() and some other methods</li><li>TERMINATED — a thread has completed the execution of its Runnable.run() method and terminated</li></ul><h3>What Is the Difference Between the Runnable and Callable Interfaces? How Are They Used?</h3><p>The Runnable interface has a single run method. It represents a unit of computation that has to be run in a separate thread. The Runnable interface does not allow this method to return value or to throw unchecked exceptions.</p><p>The Callable interface has a single call method and represents a task that has a value. That’s why the call method returns a value. It can also throw exceptions. Callable is generally used in ExecutorService instances to start an asynchronous task and then call the returned Future instance to get its value.</p><h3>What Is a Daemon Thread, What Are Its Use Cases? How Can You Create a Daemon Thread?</h3><p>A daemon thread is a thread that does not prevent JVM from exiting. When all non-daemon threads are terminated, the JVM simply abandons all remaining daemon threads. Daemon threads are usually used to carry out some supportive or service tasks for other threads, but you should take into account that they may be abandoned at any time.</p><p>To start a thread as a daemon, you should use the setDaemon() method before calling start():</p><pre>Thread daemon = new Thread(()<br>  -&gt; System.out.println(&quot;Hello from daemon!&quot;));<br>daemon.setDaemon(true);<br>daemon.start();</pre><p>System.out.println(“Hello from daemon!”));</p><p>daemon.setDaemon(true);</p><p>daemon.start();”</p><p>tabindex=”0&quot; role=”button” style=”box-sizing: border-box;</p><p>position: relative; display: flex !important; padding: 0px !important; font-size: 14px; font-weight: var( — base-text-weight-medium, 500); line-height: 20px; white-space: nowrap; vertical-align: middle; cursor: pointer; user-select: none; border: 0px; border-radius: 6px; appearance: none; color: var( — fgColor-accent, var( — color-accent-fg)); background-color: transparent; box-shadow: none; transition: color 80ms cubic-bezier(0.33, 1, 0.68, 1) 0s, background-color, box-shadow, border-color; justify-content: center !important; align-items: center !important; margin: var( — base-size-8, 8px) !important; width: var( — control-small-size, 28px); height: var( — control-small-size, 28px);”&gt;</p><p>Curiously, if you run this as a part of the main() method, the message might not get printed. This could happen if the main() thread would terminate before the daemon would get to the point of printing the message. You generally should not do any I/O in daemon threads, as they won’t even be able to execute their finally blocks and close the resources if abandoned.</p><h3>What Is the Thread’s Interrupt Flag? How Can You Set and Check It? How Does It Relate to the Interruptedexception?</h3><p>The interrupt flag, or interrupt status, is an internal Thread flag that is set when the thread is interrupted. To set it, simply call thread.interrupt() on the thread object.</p><p>If a thread is currently inside one of the methods that throw InterruptedException (wait, join, sleep etc.), then this method immediately throws InterruptedException. The thread is free to process this exception according to its own logic.</p><p>If a thread is not inside such method and thread.interrupt() is called, nothing special happens. It is thread’s responsibility to periodically check the interrupt status using static Thread.interrupted() or instance isInterrupted() method. The difference between these methods is that the static Thread.interrupted() clears the interrupt flag, while isInterrupted() does not.</p><h3>What Are Executor and Executorservice? What Are the Differences Between These Interfaces?</h3><p>Executor and ExecutorService are two related interfaces of java.util.concurrent framework. Executor is a very simple interface with a single execute method accepting Runnable instances for execution. In most cases, this is the interface that your task-executing code should depend on.</p><p>ExecutorService extends the Executor interface with multiple methods for handling and checking the lifecycle of a concurrent task execution service (termination of tasks in case of shutdown) and methods for more complex asynchronous task handling including Futures.</p><h3>What Are the Available Implementations of Executorservice in the Standard Library?</h3><p>The ExecutorService interface has three standard implementations:</p><ul><li>ThreadPoolExecutor — for executing tasks using a pool of threads. Once a thread is finished executing the task, it goes back into the pool. If all threads in the pool are busy, then the task has to wait for its turn.</li><li>ScheduledThreadPoolExecutor allows to schedule task execution instead of running it immediately when a thread is available. It can also schedule tasks with fixed rate or fixed delay.</li><li>ForkJoinPool is a special ExecutorService for dealing with recursive algorithms tasks. If you use a regular ThreadPoolExecutor for a recursive algorithm, you will quickly find all your threads are busy waiting for the lower levels of recursion to finish. The ForkJoinPool implements the so-called work-stealing algorithm that allows it to use available threads more efficiently.</li></ul><h3>What Is Java Memory Model (Jmm)? Describe Its Purpose and Basic Ideas.</h3><p>Java Memory Model is a part of Java language specification described in Chapter 17.4. It specifies how multiple threads access common memory in a concurrent Java application, and how data changes by one thread are made visible to other threads. While being quite short and concise, JMM may be hard to grasp without strong mathematical background.</p><p>The need for memory model arises from the fact that the way your Java code is accessing data is not how it actually happens on the lower levels. Memory writes and reads may be reordered or optimized by the Java compiler, JIT compiler, and even CPU, as long as the observable result of these reads and writes is the same.</p><p>This can lead to counter-intuitive results when your application is scaled to multiple threads because most of these optimizations take into account a single thread of execution (the cross-thread optimizers are still extremely hard to implement). Another huge problem is that the memory in modern systems is multilayered: multiple cores of a processor may keep some non-flushed data in their caches or read/write buffers, which also affects the state of the memory observed from other cores.</p><p>To make things worse, the existence of different memory access architectures would break the Java’s promise of “write once, run everywhere”. Happily for the programmers, the JMM specifies some guarantees that you may rely upon when designing multithreaded applications. Sticking to these guarantees helps a programmer to write multithreaded code that is stable and portable between various architectures.</p><p>The main notions of JMM are:</p><ul><li>Actions, these are inter-thread actions that can be executed by one thread and detected by another thread, like reading or writing variables, locking/unlocking monitors and so on</li><li>Synchronization actions, a certain subset of actions, like reading/writing a volatile variable, or locking/unlocking a monitor</li><li>Program Order (PO), the observable total order of actions inside a single thread</li><li>Synchronization Order (SO), the total order between all synchronization actions — it has to be consistent with Program Order, that is, if two synchronization actions come one before another in PO, they occur in the same order in SO</li><li>synchronizes-with (SW) relation between certain synchronization actions, like unlocking of monitor and locking of the same monitor (in another or the same thread)</li><li>Happens-before Order — combines PO with SW (this is called transitive closure in set theory) to create a partial ordering of all actions between threads. If one action happens-before another, then the results of the first action are observable by the second action (for instance, write of a variable in one thread and read in another)</li><li>Happens-before consistency — a set of actions is HB-consistent if every read observes either the last write to that location in the happens-before order, or some other write via data race</li><li>Execution — a certain set of ordered actions and consistency rules between them</li></ul><p>For a given program, we can observe multiple different executions with various outcomes. But if a program is correctly synchronized, then all of its executions appear to be sequentially consistent, meaning you can reason about the multithreaded program as a set of actions occurring in some sequential order. This saves you the trouble of thinking about under-the-hood reorderings, optimizations or data caching.</p><h3>What Is a Volatile Field and What Guarantees Does the Jmm Hold for Such Field?</h3><p>A volatile field has special properties according to the Java Memory Model (see Q9). The reads and writes of a volatile variable are synchronization actions, meaning that they have a total ordering (all threads will observe a consistent order of these actions). A read of a volatile variable is guaranteed to observe the last write to this variable, according to this order.</p><p>If you have a field that is accessed from multiple threads, with at least one thread writing to it, then you should consider making it volatile, or else there is a little guarantee to what a certain thread would read from this field.</p><p>Another guarantee for volatile is atomicity of writing and reading 64-bit values (long and double). Without a volatile modifier, a read of such field could observe a value partly written by another thread.</p><h3>Which of the Following Operations Are Atomic?</h3><ul><li>writing to a non-volatile int;</li><li>writing to a volatile int;</li><li>writing to a non-volatile long;</li><li>writing to a volatile long;</li><li>incrementing a volatile long?</li></ul><p>A write to an int (32-bit) variable is guaranteed to be atomic, whether it is volatile or not. A long (64-bit) variable could be written in two separate steps, for example, on 32-bit architectures, so by default, there is no atomicity guarantee. However, if you specify the volatile modifier, a long variable is guaranteed to be accessed atomically.</p><p>The increment operation is usually done in multiple steps (retrieving a value, changing it and writing back), so it is never guaranteed to be atomic, wether the variable is volatile or not. If you need to implement atomic increment of a value, you should use classes AtomicInteger, AtomicLong etc.</p><h3>What Special Guarantees Does the Jmm Hold for Final Fields of a Class?</h3><p>JVM basically guarantees that final fields of a class will be initialized before any thread gets hold of the object. Without this guarantee, a reference to an object may be published, i.e. become visible, to another thread before all the fields of this object are initialized, due to reorderings or other optimizations. This could cause racy access to these fields.</p><p>This is why, when creating an immutable object, you should always make all its fields final, even if they are not accessible via getter methods.</p><h3>What Is the Meaning of a Synchronized Keyword in the Definition of a Method? of a Static Method? Before a Block?</h3><p>The synchronized keyword before a block means that any thread entering this block has to acquire the monitor (the object in brackets). If the monitor is already acquired by another thread, the former thread will enter the BLOCKED state and wait until the monitor is released.</p><pre>synchronized(object) {<br>    // ...<br>}</pre><p>A synchronized instance method has the same semantics, but the instance itself acts as a monitor.</p><pre>synchronized void instanceMethod() {<br>    // ...<br>}</pre><p>For a static synchronized method, the monitor is the Class object representing the declaring class.</p><pre>static synchronized void staticMethod() {<br>    // ...<br>}</pre><h3>If Two Threads Call a Synchronized Method on Different Object Instances Simultaneously, Could One of These Threads Block? What If the Method Is Static?</h3><p>If the method is an instance method, then the instance acts as a monitor for the method. Two threads calling the method on different instances acquire different monitors, so none of them gets blocked.</p><p>If the method is static, then the monitor is the Class object. For both threads, the monitor is the same, so one of them will probably block and wait for another to exit the synchronized method.</p><h3>What Is the Purpose of the Wait, Notify and Notifyall Methods of the Object Class?</h3><p>A thread that owns the object’s monitor (for instance, a thread that has entered a synchronized section guarded by the object) may call object.wait() to temporarily release the monitor and give other threads a chance to acquire the monitor. This may be done, for instance, to wait for a certain condition.</p><p>When another thread that acquired the monitor fulfills the condition, it may call object.notify() or object.notifyAll() and release the monitor. The notify method awakes a single thread in the waiting state, and the notifyAll method awakes all threads that wait for this monitor, and they all compete for re-acquiring the lock.</p><p>The following BlockingQueue implementation shows how multiple threads work together via the wait-notify pattern. If we put an element into an empty queue, all threads that were waiting in the take method wake up and try to receive the value. If we put an element into a full queue, the put method waits for the call to the get method. The get method removes an element and notifies the threads waiting in the put method that the queue has an empty place for a new item.</p><pre>public class BlockingQueue&lt;T&gt; {</pre><pre>    private List&lt;T&gt; queue = new LinkedList&lt;T&gt;();</pre><pre>    private int limit = 10;</pre><pre>    public synchronized void put(T item) {<br>        while (queue.size() == limit) {<br>            try {<br>                wait();<br>            } catch (InterruptedException e) {}<br>        }<br>        if (queue.isEmpty()) {<br>            notifyAll();<br>        }<br>        queue.add(item);<br>    }</pre><pre>    public synchronized T take() throws InterruptedException {<br>        while (queue.isEmpty()) {<br>            try {<br>                wait();<br>            } catch (InterruptedException e) {}<br>        }<br>        if (queue.size() == limit) {<br>            notifyAll();<br>        }<br>        return queue.remove(0);<br>    }<br>    <br>}</pre><p>{ private List queue = new LinkedList(); private int limit = 10; public synchronized void put(T item) { while (queue.size() == limit) { try { wait(); } catch (InterruptedException e) {} } if (queue.isEmpty()) { notifyAll(); } queue.add(item); } public synchronized T take() throws InterruptedException { while (queue.isEmpty()) { try { wait(); } catch (InterruptedException e) {} } if (queue.size() == limit) { notifyAll(); } return queue.remove(0); } }” tabindex=”0&quot; role=”button” style=”box-sizing: border-box; position: relative; display: flex !important; padding: 0px !important; font-size: 14px; font-weight: var( — base-text-weight-medium, 500); line-height: 20px; white-space: nowrap; vertical-align: middle; cursor: pointer; user-select: none; border: 0px; border-radius: 6px; appearance: none; color: var( — fgColor-accent, var( — color-accent-fg)); background-color: transparent; box-shadow: none; transition: color 80ms cubic-bezier(0.33, 1, 0.68, 1) 0s, background-color, box-shadow, border-color; justify-content: center !important; align-items: center !important; margin: var( — base-size-8, 8px) !important; width: var( — control-small-size, 28px); height: var( — control-small-size, 28px);”&gt;</p><h3>Describe the Conditions of Deadlock, Livelock, and Starvation. Describe the Possible Causes of These Conditions.</h3><ul><li>Deadlock is a condition within a group of threads that cannot make progress because every thread in the group has to acquire some resource that is already acquired by another thread in the group. The most simple case is when two threads need to lock both of two resources to progress, the first resource is already locked by one thread, and the second by another. These threads will never acquire a lock to both resources and thus will never progress.</li><li>Livelock is a case of multiple threads reacting to conditions, or events, generated by themselves. An event occurs in one thread and has to be processed by another thread. During this processing, a new event occurs which has to be processed in the first thread, and so on. Such threads are alive and not blocked, but still, do not make any progress because they overwhelm each other with useless work.</li><li>Starvation is a case of a thread unable to acquire resource because other thread (or threads) occupy it for too long or have higher priority. A thread cannot make progress and thus is unable to fulfill useful work.</li></ul><h3>Describe the Purpose and Use-Cases of the Fork/Join Framework.</h3><p>The fork/join framework allows parallelizing recursive algorithms. The main problem with parallelizing recursion using something like ThreadPoolExecutor is that you may quickly run out of threads because each recursive step would require its own thread, while the threads up the stack would be idle and waiting.</p><p>The fork/join framework entry point is the ForkJoinPool class which is an implementation of ExecutorService. It implements the work-stealing algorithm, where idle threads try to “steal” work from busy threads. This allows to spread the calculations between different threads and make progress while using fewer threads than it would require with a usual thread pool.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2fc3b0b82b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Collection Interview Questions]]></title>
            <link>https://medium.com/@priyankalovesgaurav004/java-collection-interview-questions-63acb6690893?source=rss-7f8ef520f5f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/63acb6690893</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[collection]]></category>
            <category><![CDATA[java-interview-questions]]></category>
            <dc:creator><![CDATA[Be You]]></dc:creator>
            <pubDate>Tue, 25 Jun 2024 10:30:56 GMT</pubDate>
            <atom:updated>2024-06-25T10:30:56.544Z</atom:updated>
            <content:encoded><![CDATA[<h3>Describe the Collections Type Hierarchy. What Are the Main Interfaces, and What Are the Differences Between Them?</h3><p>The Iterable interface represents any collection that can be iterated using the for-each loop. The Collection interface inherits from Iterable and adds generic methods for checking if an element is in a collection, adding and removing elements from the collection, determining its size etc.</p><p>The List, Set, and Queue interfaces inherit from the Collection interface.</p><ul><li>List is an ordered collection, and its elements can be accessed by their index in the list.</li><li>Set is an unordered collection with distinct elements, similar to the mathematical notion of a set.</li><li>Queue is a collection with additional methods for adding, removing and examining elements, useful for holding elements prior to processing.</li><li>Map interface is also a part of the collection framework, yet it does not extend Collection. This is by design, to stress the difference between collections and mappings which are hard to gather under a common abstraction. The Map interface represents a key-value data structure with unique keys and no more than one value for each key.</li></ul><h3>Describe Various Implementations of the Map Interface and Their Use Case Differences.</h3><p>One of the most often used implementations of the Map interface is the HashMap. It is a typical hash map data structure that allows accessing elements in constant time, or O(1), but does not preserve order and is not thread-safe.</p><p>To preserve insertion order of elements, you can use the LinkedHashMap class which extends the HashMap and additionally ties the elements into a linked list, with foreseeable overhead.</p><p>The TreeMap class stores its elements in a red-black tree structure, which allows accessing elements in logarithmic time, or O(log(n)). It is slower than the HashMap for most cases, but it allows keeping the elements in order according to some Comparator.</p><p>The ConcurrentHashMap is a thread-safe implementation of a hash map. It provides full concurrency of retrievals (as the get operation does not entail locking) and high expected concurrency of updates.</p><p>The Hashtable class has been in Java since version 1.0. It is not deprecated but is mostly considered obsolete. It is a thread-safe hash map, but unlike ConcurrentHashMap, all its methods are simply synchronized, which means that all operations on this map block, even retrieval of independent values.</p><h3>Explain the Difference Between Linkedlist and Arraylist.</h3><p>ArrayList is an implementation of the List interface that is based on an array. ArrayList internally handles resizing of this array when the elements are added or removed. You can access its elements in constant time by their index in the array. However, inserting or removing an element infers shifting all consequent elements which may be slow if the array is huge and the inserted or removed element is close to the beginning of the list.</p><p>LinkedList is a doubly-linked list: single elements are put into Node objects that have references to previous and next Node. This implementation may appear more efficient than ArrayList if you have lots of insertions or deletions in different parts of the list, especially if the list is large.</p><p>In most cases, however, ArrayList outperforms LinkedList. Even elements shifting in ArrayList, while being an O(n) operation, is implemented as a very fast System.arraycopy() call. It can even appear faster than the LinkedList‘s O(1) insertion which requires instantiating a Node object and updating multiple references under the hood. LinkedList also can have a large memory overhead due to a creation of multiple small Node objects.</p><h3>What Is the Difference Between Hashset and Treeset?</h3><p>Both HashSet and TreeSet classes implement the Set interface and represent sets of distinct elements. Additionally, TreeSet implements the NavigableSet interface. This interface defines methods that take advantage of the ordering of elements.</p><p>HashSet is internally based on a HashMap, and TreeSet is backed by a TreeMap instance, which defines their properties: HashSet does not keep elements in any particular order. Iteration over the elements in a HashSet produces them in a shuffled order. TreeSet, on the other hand, produces elements in order according to some predefined Comparator.</p><h3>How Is Hashmap Implemented in Java?</h3><p>The HashMap class represents a typical hash map data structure with certain design choices.</p><p>The HashMap is backed by a resizable array that has a size of power-of-two. When the element is added to a HashMap, first its hashCode is calculated (an int value). Then a certain number of lower bits of this value are used as an array index. This index directly points to the cell of the array (called a bucket) where this key-value pair should be placed. Accessing an element by its index in an array is a very fast O(1) operation, which is the main feature of a hash map structure.</p><p>A hashCode is not unique, however, and even for different hashCodes, we may receive the same array position. This is called a collision. There is more than one way of resolving collisions in the hash map data structures. In Java’s HashMap, each bucket actually refers not to a single object, but to a red-black tree of all objects that landed in this bucket (prior to Java 8, this was a linked list).</p><p>So when the HashMap has determined the bucket for a key, it has to traverse this tree to put the key-value pair in its place. If a pair with such key already exists in the bucket, it is replaced with a new one.</p><p>To retrieve the object by its key, the HashMap again has to calculate the hashCode for the key, find the corresponding bucket, traverse the tree, call equals on keys in the tree and find the matching one.</p><p>HashMap has O(1) complexity, or constant-time complexity, of putting and getting the elements. Of course, lots of collisions could degrade the performance to O(log(n)) time complexity in the worst case, when all elements land in a single bucket. This is usually solved by providing a good hash function with a uniform distribution.</p><p>When the HashMap internal array is filled (more on that in the next question), it is automatically resized to be twice as large. This operation infers rehashing (rebuilding of internal data structures), which is costly, so you should plan the size of your HashMap beforehand.</p><h3>What Is the Purpose of the Initial Capacity and Load Factor Parameters of a Hashmap?</h3><p>The initialCapacity argument of the HashMap constructor affects the size of the internal data structure of the HashMap, but reasoning about the actual size of a map is a bit tricky. The HashMap‘s internal data structure is an array with the power-of-two size. So the initialCapacity argument value is increased to the next power-of-two (for instance, if you set it to 10, the actual size of the internal array will be 16).</p><p>The load factor of a HashMap is the ratio of the element count divided by the bucket count (i.e. internal array size). For instance, if a 16-bucket HashMap contains 12 elements, its load factor is 12/16 = 0.75. A high load factor means a lot of collisions, which in turn means that the map should be resized to the next power of two. So the loadFactor argument is a maximum value of the load factor of a map. When the map achieves this load factor, it resizes its internal array to the next power-of-two value.</p><p>The initialCapacity is 16 by default, and the loadFactor is 0.75 by default, so you could put 12 elements in a HashMap that was instantiated with the default constructor, and it would not resize. The same goes for the HashSet, which is backed by a HashMap instance internally.</p><p>Consequently, it is not trivial to come up with initialCapacity that satisfies your needs. This is why the Guava library has Maps.newHashMapWithExpectedSize() and Sets.newHashSetWithExpectedSize() methods that allow you to build a HashMap or a HashSet that can hold the expected number of elements without resizing.</p><h3>Describe Special Collections for Enums.</h3><p>EnumSet and EnumMap are special implementations of Set and Map interfaces correspondingly. You should always use these implementations when you’re dealing with enums because they are very efficient.</p><p>An EnumSet is just a bit vector with “ones” in the positions corresponding to ordinal values of enums present in the set. To check if an enum value is in the set, the implementation simply has to check if the corresponding bit in the vector is a “one”, which is a very easy operation. Similarly, an EnumMap is an array accessed with enum’s ordinal value as an index. In the case of EnumMap, there is no need to calculate hash codes or resolve collisions.</p><h3>What Is the Difference Between Fail-Fast and Fail-Safe Iterators?</h3><p>Iterators for different collections are either fail-fast or fail-safe, depending on how they react to concurrent modifications. The concurrent modification is not only a modification of collection from another thread but also modification from the same thread but using another iterator or modifying the collection directly.</p><ul><li>Fail-fast iterators (those returned by HashMap, ArrayList, and other non-thread-safe collections) iterate over the collection’s internal data structure, and they throw ConcurrentModificationException as soon as they detect a concurrent modification.</li><li>Fail-safe iterators (returned by thread-safe collections such as ConcurrentHashMap, CopyOnWriteArrayList) create a copy of the structure they iterate upon. They guarantee safety from concurrent modifications. Their drawbacks include excessive memory consumption and iteration over possibly out-of-date data in case the collection was modified.</li></ul><h3>How Can You Use Comparable and Comparator Interfaces to Sort Collections?</h3><p>The Comparable interface is an interface for objects that can be compared according to some order. Its single method is compareTo, which operates on two values: the object itself and the argument object of the same type. For instance, Integer, Long, and other numeric types implement this interface. String also implements this interface, and its compareTo method compares strings in lexicographical order.</p><p>The Comparable interface allows to sort lists of corresponding objects with the Collections.sort() method and uphold the iteration order in collections that implement SortedSet and SortedMap. If your objects can be sorted using some logic, they should implement the Comparable interface.</p><p>The Comparable interface usually is implemented using natural ordering of the elements. For instance, all Integer numbers are ordered from lesser to greater values. But sometimes you may want to implement another kind of ordering, for instance, to sort the numbers in descending order. The Comparator interface can help here.</p><p>The class of the objects you want to sort does not need to implement this interface. You simply create an implementing class and define the compare method which receives two objects and decides how to order them. You may then use the instance of this class to override the natural ordering of the Collections.sort() method or SortedSet and SortedMap instances.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63acb6690893" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Gradle Interview Questions]]></title>
            <link>https://medium.com/@priyankalovesgaurav004/gradle-interview-questions-cdd9442b40d6?source=rss-7f8ef520f5f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/cdd9442b40d6</guid>
            <category><![CDATA[java-interview-questions]]></category>
            <category><![CDATA[gradle]]></category>
            <category><![CDATA[backend-development]]></category>
            <dc:creator><![CDATA[Be You]]></dc:creator>
            <pubDate>Tue, 25 Jun 2024 10:14:25 GMT</pubDate>
            <atom:updated>2024-06-25T10:14:25.713Z</atom:updated>
            <content:encoded><![CDATA[<h3>Advantages of using Gradle.</h3><p>Gradle provides support for multi-project builds. It allows to use existing Maven/Ivy repositories.</p><h3>What is Gradle wrapper?</h3><p>A wrapper is a batch script and it is one of the ways to perform Gradle build. When executed the first time, it automatically downloads Gradle and then initiate the build.</p><p>It helps to setup Gradle workspace quickly for first-time users (Zero installation) and also ensure all the developers use the same version of Gradle.</p><h3>What is the Gradle build script file name?</h3><p>build.gradle.</p><h3>What are the core components of Gradle build script?</h3><p>Project and task are the core compoents. Groovy organizes projects as a list of tasks.</p><p>To view the list of available projects, use the command gradle projects, for the tasks list the command is gradle tasks.</p><h3>How do I force Gradle to download dependencies always?</h3><p>you may refresh dependencies in your cache using the command line option — refresh-dependencies. Also deleting the cached files under ~/.gradle/caches would get the next Gradle build to download them again.</p><h3>What is Gradle build language?</h3><p>Gradle provides a domain specific language (DSL) for describing builds. This build language is available in Groovy and Kotlin. It is build.gradle. Kotlin DSL script files use the .gradle.kts file name extension.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cdd9442b40d6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Interview Questions]]></title>
            <link>https://medium.com/@priyankalovesgaurav004/java-interview-questions-ce0bd8adb385?source=rss-7f8ef520f5f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce0bd8adb385</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[java-interview]]></category>
            <category><![CDATA[java-interview-questions]]></category>
            <dc:creator><![CDATA[Be You]]></dc:creator>
            <pubDate>Tue, 25 Jun 2024 10:12:14 GMT</pubDate>
            <atom:updated>2024-06-25T10:12:14.367Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. What is Java. What are features of Java?</h3><p>Java is a high-level programming language and is platform-independent.</p><ul><li>Java is also an object-oriented language. However, everything (except fundamental types) is an object in Java</li><li>Platform independent: A single program works on different platforms without any modification.</li><li>High Performance: JIT (Just In Time compiler) enables high performance in Java. JIT converts the bytecode into machine language and then JVM starts the execution.</li><li>Multi-threaded. We can write Java programs that deal with many tasks at once by defining multiple threads.</li><li>Java doesn’t support multiple inheritance through class. It can be achieved by interfaces in java.</li><li>Secured: Java is secured because it doesn’t use explicit pointers.</li><li>Java is a strong programming language as it uses strong memory management. The concepts like Automatic garbage collection.</li></ul><h3>2. What are the OOPs concepts?</h3><p>OOPs concepts include:</p><ul><li>Inheritance</li><li>Inheritance means one class can extend to another class. So that the codes can be reused from one class to another class. The existing class is known as the Super class whereas the derived class is known as a sub class. Inheritance is only applicable to the public and protected members only. Private members can’t be inherited.</li><li>Encapsulation</li><li>Protects the code from others. Code maintainability. For encapsulation, we need to make all the instance variables private and create setter and getter for those variables. Which in turn will force others to call the setters rather than access the data directly.</li><li>Polymorphism</li><li>A single object can refer to the super-class or sub-class depending on the reference type which is called polymorphism. Polymorphism is applicable for overriding</li><li>Abstraction</li><li>Abstraction in object-oriented programming means hiding complex internals but to expose only essential characteristics and behavior with respect to context.</li><li>Interface</li><li>Multiple inheritances cannot be achieved in java. To overcome this problem the Interface concept is introduced. An interface is a template which has only method declarations and not the method implementation.</li></ul><h3>3. What are different access modifiers in Java?</h3><ul><li>Default access modifier is without any access specifier data members, class and methods, and are accessible within the same package.</li><li>Private access modifiers are marked with the keyword private, and are accessible only within class, and not even accessible by class from the same package.</li><li>Protected access modifiers can be accessible within the same package or subclasses from different packages.</li><li>Public access modifiers are accessible from everywhere.</li></ul><h3>4. What is the meaning of SOLID?</h3><p>Solid represents five principles of java which are:</p><ul><li>S: Single responsibility principle. One class should have only one and only responsibility.</li><li>O: Open-closed principle. Software components should be open for extension, but closed for modification. Hence, the browser is a perfect example of functionality that is open for extension but is closed for modification.</li><li>L: Liskov substitution principle. Types must be completely substitutable for their base types.</li><li>I: Interface segregation principle. Clients should not be forced to implement unnecessary methods which they will not use.</li><li>D: Dependency inversion principle. it depends on abstractions not on concretions. According to it, the high-level module must never rely on any low-level module. You go to a local store to buy something, and you decide to pay for it by using your debit card. So, when you give your card to the clerk for making the payment, the clerk doesn’t bother to check what kind of card you have given. The type of credit card or debit card that you have for paying does not even matter; they will simply swipe it.</li></ul><h3>5. What are primitive data types?</h3><ul><li>byte — 1 byte (8 bits). Min -2⁷ Max 2⁷-1</li><li>short — 2 byte (16 bits). Min -2¹⁵ Max 2¹⁵-1</li><li>char — 2 byte (16 bits). 2¹⁶-1</li><li>int — 4 byte (32 bits). Min -2³¹-1 Max 2³¹</li><li>long — 8 byte (64 bits). Min -2⁶³-1 Max 2⁶³</li><li>float — 4 byte (32 bits). Min -2³¹-1 Max 2³¹</li><li>double — 8 byte (64 bits). Min -2⁶³-1 Max 2⁶³</li><li>boolean — NA usualy 1 byte</li></ul><h3>6. Order of execution of Initialization blocks and Constructors in Java.</h3><ul><li>Static initialization blocks will run whenever the class is loaded first time in JVM</li><li>Initialization blocks run in the same order in which they appear in the program.</li><li>Instance Initialization blocks are executed whenever the class is initialized and before constructors are invoked. They are typically placed above the constructors within braces.</li></ul><h3>7. Differences between Lambda Expressions and Closures in Java.</h3><p>Java supports lambda expressions but not the Closures. A lambda expression is an anonymous function and can be defined as a parameter. The Closures are like code fragments or code blocks that can be used without being a method or a class. It means that Closures can access variables not defined in its parameter list and also assign it to a variable.</p><p><a href="https://github.com/a11exe/java-interview/blob/main/questions/basic.md#basic-java-interview-questions">back to the top</a></p><h3>8. Give the list of Java Object class methods.</h3><ul><li>clone() — Creates and returns a copy of this object.</li><li>equals() — Indicates whether some other object is “equal to” this one.</li><li>finalize() — Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.</li><li>getClass() — Returns the runtime class of an object.</li><li>hashCode() — Returns a hash code value for the object.</li><li>notify() — Wakes up a single thread that is waiting on this object’s monitor.</li><li>notifyAll() — Wakes up all threads that are waiting on this object’s monitor.</li><li>toString() — Returns a string representation of the object.</li><li>wait() — Causes current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object.</li></ul><h3>9. What is the difference between atomic, volatile, synchronized?</h3><p>It basically reads value from memory, increments it and puts back to memory. This works in single thread but nowadays, in the era of multi-core, multi-CPU, multi-level caches it won’t work correctly. First of all it introduces race condition (several threads can read the value at the same time), but also visibility problems. The value might only be stored in “local” CPU memory (some cache) and not be visible for other CPUs/cores (and thus — threads). Volatile Declaring a variable as volatile means that modifying its value immediately affects the actual memory storage for the variable. The compiler cannot optimize away any references made to the variable. This guarantees that when one thread modifies the variable, all other threads see the new value immediately.</p><p>AtomicInteger</p><pre>private AtomicInteger counter = new AtomicInteger();<br><br>public int getNextUniqueIndex() {<br>  return counter.getAndIncrement();<br>}</pre><p>The AtomicInteger class uses CAS (compare-and-swap) low-level CPU operations (no synchronization needed!) Declaring an atomic variable guarantees that operations made on the variable occur in an atomic fashion, i.e., that all of the substeps of the operation are completed within the thread they are executed and are not interrupted by other threads.</p><p>Synchronizing all accesses to a variable allows only a single thread at a time to access the variable, and forces all other threads to wait for that accessing thread to release its access to the variable.</p><p>Synchronization occurs on an object. This means that calling a synchronized method of a class will lock the this object of the call. Static synchronized methods will lock the Class object itself.</p><p>Likewise, entering a synchronized block requires locking the this object of the method.</p><p>Synchronized access to a variable is usually implemented using a monitor or semaphore. These are low-level mutex (mutual exclusion) mechanisms that allow a thread to acquire control of a variable or block of code exclusively, forcing all other threads to wait if they also attempt to acquire the same mutex.</p><p>This means that a synchronized method (or block) can be executing in multiple threads at the same time if they are locking on different objects, but only one thread can execute a synchronized method (or block) at a time for any given single object.</p><h3>10. Explain object finalization</h3><p>Called by the garbage collector on an object when garbage collection determines that there are no more references to the object. If an object can not be accessed from any live object, this means that it can be safely garbage collected.</p><h3>11. What is Serialization in Java?</h3><p>Object Serialization in Java is a process used to convert Object into a binary format which can be persisted into a disk or sent over the network to any other running Java virtual machine; the reverse process of creating object from the binary stream is called deserialization in Java. Java provides Serialization API for serializing and deserializing object which includes java.io.Serializable, java.io.Externalizable, ObjectInputStream and ObjectOutputStream etc.</p><p>Serializable is marker interface.Marker interface in Java is interfaces with no field or methods or in simple word empty interface in java is called marker interface.</p><p>Making a class Serializable in Java is very easy, Your Java class just needs to implements java.io.Serializable interface and JVM will take care of serializing objects in the default format.</p><p>If you don’t explicitly declare SerialVersionUID then JVM generates it based upon the structure of class which depends upon interfaces a class implements and several other factors which is subject to change</p><p>serialVersionUID is used to ensure that same class(That was used during Serialization) is loaded during Deserialization.serialVersionUID is used for version control of object.</p><p>You can customize Serialization process by defining writeObject and readObject method.</p><p>To avoid serialization some variable, you can mark that variable as either static or transient.</p><p>Externalizable interface has more control over serialization process and it is mandatory to override writeExternal and readExternal.</p><h3>12. Concept Of Java Cloning</h3><p>Java supports two type of cloning: — Deep and shallow cloning. By default shallow clone is used in Java. Object class has a method clone() which does shallow cloning. Shallow copies duplicate as little as possible. The memory usage is lower.</p><ol><li>If the class has only primitive data type members then a completely new copy of the object will be created and the reference to the new object copy will be returned.</li><li>If the class contains members of any class type then only the object references to those members are copied and hence the member references in both the original object as well as the cloned object refer to the same object.</li></ol><p>In deep copy is the copy of object itself. A new memory is allocated for the object and contents are copied. When a deep copy of the object is done new references are created. One solution is to simply implement your own custom method (e.g., deepCopy()) that returns a deep copy of an instance of one of your classes. Other common solution to the deep copy problem is to use Java Object Serialization.</p><h3>13. StringBuffer vs StringBuilder</h3><p>StringBuffer is synchronized, StringBuilder is not. StringBuilder is faster than StringBuffer because it’s not synchronized</p><h3>14. Name some of the parsers which are commonly used to parse XML documents.</h3><ul><li>Dom Parser — Parses the document by loading the complete contents of the document and creating its complete hiearchical tree in memory. Using DOM parser, we can parse, modify or create a XML document.</li><li>SAX Parser — Parses the document on event based triggers. Does not load the complete document into the memory. You are processing a very large XML document whose DOM tree would consume too much memory. We have no random access to an XML document since it is processed in a forward-only manner. Using SAX parser, we can only parse or modify a XML document.</li><li>StAX Parser — Parses the document in similar fashion to SAX parser does, but StAX is a PULL API where as SAX is a PUSH API. It means in case of StAX parser, client application need to ask StAX parser to get information from XML whenever it needs but in case of SAX parser, client application is required to get information when SAX parser notifies the client application that information is available. Using StAX parser, we can parse, modify and create a XML document.</li></ul><h3>15. What New Features Were Added in Java 8?</h3><p>Java 8 ships with several new features, but the most significant are the following:</p><ul><li>Lambda Expressions − a new language feature allowing us to treat actions as objects</li><li>Method References − enable us to define Lambda Expressions by referring to methods directly using their names</li><li>Optional − special wrapper class used for expressing optionality</li><li>Functional Interface — an interface with maximum one abstract method; implementation can be provided using a Lambda Expression</li><li>Default methods − give us the ability to add full implementations in interfaces besides abstract methods</li><li>Nashorn, JavaScript Engine − Java-based engine for executing and evaluating JavaScript code</li><li>Stream API − a special iterator class that allows us to process collections of objects in a functional manner</li><li>Date API − an improved, immutable JodaTime-inspired Date API</li></ul><h3>16. What New Features Were Added in Java 11?</h3><p>Java 11 ships with several new features, but the most significant are the following:</p><ul><li>New methods to the String class: isBlank, lines, strip, stripLeading, stripTrailing, and repeat.</li><li>New File Methods − readString and writeString static methods from the Files class.</li><li>The new HTTP client − improves overall performance and provides support for both HTTP/1.1 and HTTP/2</li><li>Modular System — since Java 9</li></ul><h3>17. What Is a Lambda Expression and What Is It Used For?</h3><p>In very simple terms, a lambda expression is a function that we can reference and pass around as an object.</p><p>Moreover, lambda expressions introduce functional style processing in Java, and facilitate the writing of compact and easy-to-read code.</p><p>As a result, lambda expressions are a natural replacement for anonymous classes such as method arguments. One of their main uses is to define inline implementations of functional interfaces.</p><h3>18. What Is an Exception?</h3><p>An exception is an abnormal event that occurs during the execution of a program and disrupts the normal flow of the program’s instructions. The throws keyword is used to specify that a method may raise an exception during its execution. The throw keyword allows us to throw an exception object to interrupt the normal flow of the program. We can handle exception by using a try-catch-finally statement. The block of code in which an exception may occur is enclosed in a try block. This block is also called “protected” or “guarded” code. If an exception occurs, the catch block that matches the exception being thrown is executed, if not, all catch blocks are ignored. The finally block is always executed after the try block exits, whether an exception was thrown or not inside it. A checked exception must be handled within a try-catch block or declared in a throws clause; whereas an unchecked exception is not required to be handled nor declared. An exception is an event that represents a condition from which is possible to recover, whereas error represents an external situation usually impossible to recover from.</p><h3>19. How to Generate OutOfMemoryError and StackOverflowException?</h3><p>OutOfMemoryError</p><pre>List&lt;long[]&gt; list = new LinkedList&lt;long[]&gt;();<br>while (true) {<br>  list.add(new long[65536]); // an arbitrary number<br>  // sleep(1) perhaps?<br>}</pre><p>list = new LinkedList(); while (true) { list.add(new long[65536]); // an arbitrary number // sleep(1) perhaps? }” tabindex=”0&quot; role=”button” style=”box-sizing: border-box; position: relative; display: flex !important; padding: 0px !important; font-size: 14px; font-weight: var( — base-text-weight-medium, 500); line-height: 20px; white-space: nowrap; vertical-align: middle; cursor: pointer; user-select: none; border: 0px; border-radius: 6px; appearance: none; color: var( — fgColor-accent, var( — color-accent-fg)); background-color: transparent; box-shadow: none; transition: color 80ms cubic-bezier(0.33, 1, 0.68, 1) 0s, background-color, box-shadow, border-color; justify-content: center !important; align-items: center !important; margin: var( — base-size-8, 8px) !important; width: var( — control-small-size, 28px); height: var( — control-small-size, 28px);”&gt;</p><p>StackOverflowException</p><pre>public class StackOverflowErrorExample {</pre><pre>    public static void recursivePrint(int num) {<br>        System.out.println(&quot;Number: &quot; + num);</pre><pre>        if(num == 0)<br>            return;<br>        else<br>            recursivePrint(++num);<br>    }</pre><pre>    public static void main(String[] args) {<br>        StackOverflowErrorExample.recursivePrint(1);<br>    }<br>}</pre><h3>20. What Are Annotations? What Are Their Typical Use Cases?</h3><p>Annotations are metadata bound to elements of the source code of a program and have no effect on the operation of the code they operate.</p><p>Their typical uses cases are:</p><ul><li>Information for the compiler — with annotations, the compiler can detect errors or suppress warnings</li><li>Compile-time and deployment-time processing — software tools can process annotations and generate code, configuration files, etc.</li><li>Runtime processing — annotations can be examined at runtime to customize the behavior of a program</li></ul><p>Annotations are a form of an interface where the keyword interface is preceded by @, and whose body contains annotation type element declarations that look very similar to methods:</p><pre>public @interface SimpleAnnotation {<br>    String value();<br>    int[] types();<br>}</pre><p>After the annotation is defined, yon can start using it in through your code:</p><pre>@SimpleAnnotation(value = &quot;an element&quot;, types = 1)<br>public class Element {<br>    @SimpleAnnotation(value = &quot;an attribute&quot;, types = { 1, 2 })<br>    public Element nextElement;<br>}</pre><h3>21. What is immutable class?</h3><p>Immutable objects are those objects whose state can not be changed once created. Class whose objects possess this characteristic can be termed as immutable class. For example : String , Integer. Immutable classes are thread safe because you can not change state of immutable objects, so even if two thread access immutable object in parallel, it won’t create any issue.</p><p>To create an immutable class in java, you have to do following steps.</p><ul><li>Declare the class as final so it can’t be extended.</li><li>Make all fields private so that direct access is not allowed.</li><li>Don’t provide setter methods for variables</li><li>Make all mutable fields final so that it’s value can be assigned only once.</li><li>Initialize all the fields via a constructor performing deep copy.</li><li>Perform cloning of objects in the getter methods to return a copy rather than returning the actual object reference.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce0bd8adb385" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>