Showing posts with label Spring Boot. Show all posts
Showing posts with label Spring Boot. Show all posts

Thursday, December 12, 2019

Spring Boot - parent pom when you already have a parent pom

   <dependencyManagement>
        <dependencies>
            <dependency>
                <!-- Import dependency management from Spring Boot -->
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${springframework.boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>


https://stackoverflow.com/questions/21317006/spring-boot-parent-pom-when-you-already-have-a-parent-pom

Wednesday, December 11, 2019

Configure Multiple Data Sources || Multiple Transaction Management

https://stackoverflow.com/questions/30337582/spring-boot-configure-and-use-two-datasources

https://springframework.guru/how-to-configure-multiple-data-sources-in-a-spring-boot-application/


Multiple Transaction Management:

https://stackoverflow.com/questions/48954763/spring-transactional-with-a-transaction-across-multiple-data-sources

Tuesday, December 10, 2019

Locking in Hibernate || JPA || Spring boot

https://www.baeldung.com/jpa-optimistic-locking

https://www.baeldung.com/jpa-pessimistic-locking

https://dzone.com/articles/concurrency-and-locking-with-jpa-everything-you-ne

Difference b/w Optimistic & Pessimistic Locking

It's good to know that in contrast to optimistic locking JPA gives us pessimistic locking. It's another mechanism for handling concurrent access for data.

We cover pessimistic locking in one of our previous articles – Pessimistic Locking in JPA. Let's find out what's the difference and how we can benefit from each type of locking.

As we've said before, optimistic locking is based on detecting changes on entities by checking their version attribute. If any concurrent update takes place, OptmisticLockException occurs. After that, we can retry updating the data.




We can imagine that this mechanism is suitable for applications which do much more reads than updates or deletes. What is more, it's useful in situations where entities must be detached for some time and locks cannot be held.

On the contrary, pessimistic locking mechanism involves locking entities on the database level.

Each transaction can acquire a lock on data. As long as it holds the lock, no transaction can read, delete or make any updates on the locked data. We can presume that using pessimistic locking may result in deadlocks. However, it ensures greater integrity of data than optimistic locking.


https://www.baeldung.com/java-jpa-transaction-locks

https://medium.com/slalom-engineering/optimistically-locking-your-spring-boot-web-services-187662eb8a91
In Spring Data, Optimistic Locking (last tutorial) is enabled by default given that @Version annotation is used in entities.

Thursday, December 5, 2019

Monday, December 2, 2019

How Spring Boot Works Internally || Spring Boot Initialization Steps

Below is the description of Spring Boot initialization steps that eventually register DispatcherServlet.

Example Code
@EnableAutoConfiguration
public class TestSpring {

    public static void main(String[] args) throws Exception {
        SpringApplication.run(TestSpring.class, args);
    }
}
Spring Boot Initialization Steps
Here are the steps:

SpringApplication.run() creates EmbeddedWebApplicationContext application context;
Calls its refresh() method;
Refresh process reads annotations of the starting class TestSpring. It looks for import annotations. EnableAutoConfiguration is one of them. For an import annotation the refresh process gets the corresponding class from the annotation value and invokes its selectImports() method;
In case of @EnableAutoConfiguration the corresponding class is EnableAutoConfigurationImportSelector whose selectImports() loads tons of other import selectors from the META-INF/spring.factories;
This process continues recursively. Also, all bean definitions, that are inside these import selectors, are read. I.e. it includes beans defined by a method with the @Bean annotation, i.e. beans that require the Spring context to call the corresponding method automatically to instantiate them;
The resfresh() continues and reaches onRefresh(), the createEmbeddedServletContainer() method is called inside;
Among read bean defitions at the previous step, beans implementing ServletContextInitializer are searched for and instantiated. One of them is the bean, defined by the DispatcherServletAutoConfiguration.DispatcherServletRegistrationConfiguration#dispatcherServletRegistration() method of ServletRegistrationBean type that extends ServletContextInitializer. As you can guess from the name of the class, such initializers add a given servlet (in this case DispatcherServlet) to a given ServletContext, when their onStartup() method is invoked;
A tomcat embedded server is created (not started completely yet). All found ServletContextInitializers at the previous step are passed to this tomcat initialization - this is where the onStartup() methods of those ServletContextInitializers are called and DispatcherServlet gets created and registered as servlet;
End of onRefresh() of application context;
The finishRefresh() is called where tomcat is finally started by TomcatEmbeddedServletContainer.start();
End of refresh() of application context and other final initialization steps;
The app is running.

After this read the following :


https://sivalabs.in/2016/03/how-springboot-autoconfiguration-magic/

https://medium.com/codeshake/spring-boot-auto-configuration-mystery-revealed-d734516dddfb

Wednesday, November 13, 2019

Common Application properties



1. Core Properties

debug=false Enable debug logs
logging.file.name=myapp.log Log file name (for instance, `myapp.log`). Names can be an exact location or relative to the current directory.
logging.level.* =DEBUG Log levels severity mapping. For instance, `logging.level.org.springframework=DEBUG`.

spring.aop.auto= true Add @EnableAspectJAutoProxy.
spring.application.name=xyz Application name.
spring.autoconfigure.exclude=* Auto-configuration classes to exclude.
spring.config.name=application Config file name.
spring.main.lazy-initialization=false Whether initialization should be performed lazily.
spring.main.web-application-type    Flag to explicitly request a specific type of web application. If not set, auto-detected based on the classpath. Ex : None
spring.profiles.active Comma-separated list of active profiles. Can be overridden by a command line switch.
trace=false Enable trace logs.

2. Cache properties

spring.cache.ehcache.config The location of the configuration file to use to initialize EhCache.

3. Data Properties

spring.datasource.driver-class-name Fully qualified name of the JDBC driver. Auto-detected based on the URL by default.
spring.datasource.name Name of the datasource. Default to "testdb" when using an embedded database.
spring.datasource.password Login password of the database.
spring.datasource.url JDBC URL of the database.
spring.datasource.username Login username of the database.
spring.jpa.generate-ddl=false Whether to initialize the schema on startup.
spring.jpa.hibernate.ddl-auto DDL mode. This is actually a shortcut for the "hibernate.hbm2ddl.auto" property. Defaults to "create-drop" when using an embedded database and no schema manager was detected. Otherwise, defaults to "none".
spring.jpa.show-sql=false Whether to enable logging of SQL statements.


4. Web properties

spring.http.encoding.charset=UTF-8 Charset of HTTP requests and responses. Added to the "Content-Type" header if not set explicitly.
spring.mvc.view.prefix Spring MVC view prefix.
spring.mvc.view.suffix Spring MVC view suffix.
spring.servlet.multipart.enabled=true Whether to enable support of multipart uploads.


5.Server properties

server.address Network address to which the server should bind.
server.compression.enabled=false Whether response compression is enabled.
server.error.path=/error Path of the error controller.
server.http2.enabled=false Whether to enable HTTP/2 support, if the current environment supports it.
server.max-http-header-size=8KB Maximum size of the HTTP message header.
server.port=8080 Server HTTP port.
server.servlet.application-display-name=application Display name of the application.
server.servlet.session.timeout=30m Session timeout. If a duration suffix is not specified, seconds will be used.
server.ssl.enabled=true Whether to enable SSL support.
server.tomcat.max-connections=10000 Maximum number of connections that the server accepts and processes at any given time. Once the limit has been reached, the operating system may still accept connections based on the "acceptCount" property.

6. Security properties

spring.security.user.name=user Default user name.
spring.security.user.password Password for the default user name.
spring.security.user.roles Granted roles for the default user name.
spring.session.timeout Session timeout. If a duration suffix is not specified, seconds will be used.

7. Actuator

management.endpoint.health.enabled=true Whether to enable the health endpoint.







Ref: https://docs.spring.io/spring-boot/docs/current/reference/html/appendix-application-properties.html#core-properties

Monday, November 11, 2019

Spring Boot with jwt with MySql

https://www.javainuse.com/spring/boot-jwt

Spring Boot Interview Questions - Part 2

How to enable debug logging?
To enable debug logging,

we can start the application with the --debug switch.
we can set the logging.level.root=debug property in application.properties file.
We can set the logging level of root logger in supplied logging configuration file.

How to enable HTTPS/SSL support in Spring boot?
The SSL support in spring boot project can be added via application.properties and by adding the below entries.

application.properties
server.port=8443
server.ssl.key-alias=selfsigned_localhost_sslserver
server.ssl.key-password=changeit
server.ssl.key-store=classpath:ssl-server.jks
server.ssl.key-store-provider=SUN
server.ssl.key-store-type=JKS

Datasource configuration

spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=secret
spring.datasource.driver-class-name=com.mysql.jdbc.Driver


Spring Boot Configure and Use Two DataSources

#Database
database1.datasource.url=jdbc:mysql://localhost/testdb
database1.datasource.username=root
database1.datasource.password=root
database1.datasource.driver-class-name=com.mysql.jdbc.Driver

database2.datasource.url=jdbc:mysql://localhost/testdb2
database2.datasource.username=root
database2.datasource.password=root
database2.datasource.driver-class-name=com.mysql.jdbc.Driver
Then define them as providers (@Bean) like this:

@Bean(name = "datasource1")
@ConfigurationProperties("database1.datasource")
@Primary
public DataSource dataSource(){
    return DataSourceBuilder.create().build();
}

@Bean(name = "datasource2")
@ConfigurationProperties("database2.datasource")
public DataSource dataSource2(){
    return DataSourceBuilder.create().build();
}
Note that I have @Bean(name="datasource1") and @Bean(name="datasource2"), then you can use it when we need datasource as @Qualifier("datasource1") and @Qualifier("datasource2") , for example

@Qualifier("datasource1")
@Autowired
private DataSource dataSource;
If you do care about transaction, you have to define DataSourceTransactionManager for both of them, like this:

@Bean(name="tm1")
@Autowired
@Primary
DataSourceTransactionManager tm1(@Qualifier ("datasource1") DataSource datasource) {
    DataSourceTransactionManager txm  = new DataSourceTransactionManager(datasource);
    return txm;
}

@Bean(name="tm2")
@Autowired
DataSourceTransactionManager tm2(@Qualifier ("datasource2") DataSource datasource) {
    DataSourceTransactionManager txm  = new DataSourceTransactionManager(datasource);
    return txm;
}
Then you can use it like

@Transactional //this will use the first datasource because it is @primary
or

@Transactional("tm2")


How Spring Auto Configuration Works

https://dzone.com/articles/how-springboot-autoconfiguration-magic-works

How can you enable auto reload of application with Spring Boot?
You can enable auto-reload/LiveReload of spring boot application by adding the spring-boot-devtools dependency in the pom.xml file.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <optional>true
</dependency>
Note: please restart your application for immediate effects.

How to enable HTTP/2 support in Spring Boot?
You can enable HTTP/2 support in Spring Boot as follows:
server.http2.enabled=true


How do you Enable HTTP response compression in spring boot?
To enable HTTP response compression in spring boot using GZIP you have to add below settings in your application.properties file.

# Enabling HTTP response compression in spring boot
server.compression.enabled=true
server.compression.min-response-size=2048
server.compression.mime-types=application/json,application/xml,text/html,text/xml,text/plain

How do you configure error logging/debugging in Spring boot application?
You can configure error logging/debugging in Spring boot application by applying the following settings in application.properties or application.yml file.

logging.level.org.springframework.web: DEBUG
logging.level.org.hibernate: ERROR

logging.level.org.springframework=DEBUG
logging.level.com.demo=INFO

 How to Register a Custom Auto-Configuration?
To register an auto-configuration class, we must have its fully-qualified name listed under the EnableAutoConfiguration key in the META-INF/spring.factories file:

1
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.baeldung.autoconfigure.CustomAutoConfiguration


How to Tell an Auto-Configuration to Back Away When a Bean Exists?
To instruct an auto-configuration class to back off when a bean is already existent, we can use the @ConditionalOnMissingBean annotation. The most noticeable attributes of this annotation are:

value: The types of beans to be checked
name: The names of beans to be checked
When placed on a method adorned with @Bean, the target type defaults to the method's return type:

@Configuration
public class CustomConfiguration {
    @Bean
    @ConditionalOnMissingBean
    public CustomService service() { ... }
}


How to Deploy Spring Boot Web Applications as Jar and War Files?
Traditionally, we package a web application as a WAR file, then deploy it into an external server. Doing this allows us to arrange multiple applications on the same server. During the time that CPU and memory were scarce, this was a great way to save resources.


However, things have changed. Computer hardware is fairly cheap now, and the attention has turned to server configuration. A small mistake in configuring the server during deployment may lead to catastrophic consequences.

Spring tackles this problem by providing a plugin, namely spring-boot-maven-plugin, to package a web application as an executable JAR. To include this plugin, just add a plugin element to pom.xml:

<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
With this plugin in place, we'll get a fat JAR after executing the package phase. This JAR contains all the necessary dependencies, including an embedded server. Thus, we no longer need to worry about configuring an external server.

We can then run the application just like we would an ordinary executable JAR.

Notice that the packaging element in the pom.xml file must be set to jar to build a JAR file:

<packaging>jar</packaging>
If we don't include this element, it also defaults to jar.

In case we want to build a WAR file, change the packaging element to war:

<packaging>war</packaging>
And leave the container dependency off the packaged file:


<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-tomcat</artifactId>
    <scope>provided</scope>
</dependency>
After executing the Maven package phase, we'll have a deployable WAR file.

What does it mean that Spring Boot supports relaxed binding?
Relaxed binding in Spring Boot is applicable to the type-safe binding of configuration properties.

With relaxed binding, the key of an environment 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.

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.

How to disable Actuator endpoint security in Spring Boot?
By default all sensitive HTTP endpoints are secured such that only users that have an ACTUATOR role may access them. Security is enforced using the standard HttpServletRequest.isUserInRole method.
We can disable security using -
management.security.enabled=false
It is suggested to disable security only if the actuator endpoints are accessed behind firewall.

Exception Handling

https://www.javainuse.com/spring/boot-exception-handling

For Handling Security in Actuators

management.security.enabled = true
management.security.roles = ADMIN

security.basic.enabled = true
security.user.name = admin
security.user.password = admin

Sunday, September 22, 2019

Spring Boot Interview Questions - Part 1

1. What does the @SpringBootApplication annotation do internally?

@SpringBootApplication annotation is equivalent to using @Configuration, @EnableAutoConfiguration, and @ComponentScan with their default attributes.

@Configuration :
Indicates that a class declares one or more @Bean methods and may be processed by the Spring container to generate bean definitions and service requests for those beans at runtime, for example:
 @Configuration
 public class AppConfig {

     @Bean
     public MyBean myBean() {
         // instantiate, configure and return bean ...
     }
 }

@EnableAutoConfiguration
Spring Boot auto-configuration attempts to automatically configure your Spring application based on the jar dependencies that you have added. For example, if HSQLDB is on your classpath, and you have not manually configured any database connection beans, then Spring Boot auto-configures an in-memory database.

@ComponentScan
Configures component scanning directives for use with @Configuration classes. Provides support parallel with Spring XML's <context:component-scan> element.
Either basePackageClasses() or basePackages() (or its alias value()) may be specified to define specific packages to scan. If specific packages are not defined, scanning will occur from the package of the class that declares this annotation.

2. How to disable a specific auto-configuration class or exclude any package?


//By using "exclude"- in classpath
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})


//By using "excludeName" - not in classpath
@EnableAutoConfiguration(excludeName={Foo.class})

//By using property file
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration

3.  What is Spring Actuator? What are its advantages?

It provides many features, i.e. what beans are created, the mapping in the controller, the CPU usage, etc. Automatically gathering and auditing health and metrics can then be applied to your application.

It provides a very easy way to access the few production-ready REST endpoints and fetch all kinds of information from the web. But by using these endpoints, you can do many things to see here the endpoint docs.

Enabling/disabling the actuator is easy; the simplest way is to enable features to add the dependency (Maven/Gradle) to the spring-boot-starter-actuator, i.e. Starter. If you don't want the actuator to be enabled, then don't add the dependency.

4. What is a shutdown in the actuator?

Shutdown is an endpoint that allows the application to be gracefully shutdown. This feature is not enabled by default. You can enable this by using management.endpoint.shutdown.enabled=true in your application.properties file. But be careful about this if you are using this.

5. Is this possible to change the port of Embedded Tomcat server in Spring boot?

Yes, it's possible to change the port. You can use the application.properties file to change the port. But you need to mention "server.port" (i.e. server.port=8081). Make sure you have application.properties in your project classpath; REST Spring framework will take care of the rest. If you mention server.port=0 , then it will automatically assign any available port.

6. Can we override or replace the Embedded Tomcat server in Spring Boot?

Yes, we can replace the Embedded Tomcat with any other servers by using the Starter dependencies. You can use spring-boot-starter-jetty  or spring-boot-starter-undertow as a dependency for each project as you need.

spring-boot-starter-web comes with Embedded Tomcat. We need to exclude this dependency.

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
  <exclusions>
    <exclusion>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-tomcat</artifactId>
    </exclusion>
  </exclusions>
</dependency>

Adding Dependencies
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-undertow</artifactId>
</dependency>

7.Can we disable the default web server in the Spring Boot application?

The major strong point in Spring is to provide flexibility to build your application loosely coupled. Spring provides features to disable the web server in a quick configuration. Yes, we can use the application.properties to configure the web application type, i.e.  spring.main.web-application-type=none.


8. How does it work? How does it know what to configure?

• Auto-configuration works by analyzing the classpath

The meat of the code is the use of the @ConditionalOnClass annotation

9. How to reload my changes on Spring Boot without having to restart server?

Include following maven dependency in the application.
<dependency>
 <groupId>org.springframework</groupId>
 <artifactId>springloaded</artifactId>
 <version>1.2.6.RELEASE</version>
</dependency>

Automatic restart

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>


10. How to implement Spring web using Spring boot?
Web Application Convenience
• Boot automatically configures
– A DispatcherServlet & ContextLoaderListener
– Spring MVC using same defaults as @EnableWebMvc
• Plus many useful extra features:
– Static resources served from classpath
• /static, /public, /resources or /META-INF/resources
– Templates served from /templates
• If Velocity, Freemarker, Thymeleaf, or Groovy on classpath
– Provides default /error mapping
• Easily overridden
– Default MessageSource for I18N

11. How to configure datasource using Spring boot?
• Use either spring-boot-starter-jdbc or spring-boot-starterdata-jpa and include a JDBC driver on classpath
• Declare properties

spring.datasource.url=jdbc:mysql://localhost/test
spring.datasource.username=dbuser
spring.datasource.password=dbpass
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
– Spring Boot will create a DataSource with properties set
– Will even use a connection pool if the library is found on the classpath!


12 How do you add Add a Servlet, Filter or Listener to an application?
There are two ways to add Servlet, Filter, ServletContextListener and the other listeners supported by the Servlet spec to your application. You can either provide Spring beans for them or enable scanning for Servlet components.

13. How do you Enable HTTP response compression in spring boot?
HTTP response compression is supported by Jetty, Tomcat, and Undertow. It can be enabled by adding server.compression.enabled=true in application.properties.

14. How to execute Spring Batch jobs on startup?
Spring Batch auto-configuration is enabled by adding @EnableBatchProcessing (from Spring Batch) somewhere in your context. By default, it executes all Jobs in the application context on startup.

15. How do you Create a deployable war file in spring boot?
Step 1: Extend SpringBootServletInitializer and override its configure method.
Step 2: Change packing type to war in pom.xml or in build.gradle.
Step 3: Mark the embedded servlet container dependency as provided.

16.  How to write custom log configuration in spring boot?
You can force Spring Boot to use a particular logging system using the org.springframework.boot.logging.LoggingSystem system property. The value should be the fully-qualified class name of a logging system implementation. You can also disable Spring Boot’s logging configuration entirely by using a value of none.

17. What are Profiles in spring boot?
Spring Profiles provide a way to segregate parts of your application configuration and make it only available in certain environments. Any @Component or @Configuration can be marked with @Profile to limit when it is loaded.

18. What is spring-boot-starter-parent?
The spring-boot-starter-parent is a special starter that makes Maven or Gradle dependency-management easier by adding jars to your classpath.
It adds a basic set of spring jars needed for any type of spring based applications.

19. Can you control logging with Spring Boot? How?
Yes, we can control logging with Spring Boot by specifying log levels on application.properties file. Spring Boot loads this file when it exists in the classpath and it can be used to configure both Spring Boot and application code.

Spring Boot uses Commons Logging for all internal logging and you can change log levels by adding following lines in the application.properties file:

logging.level.org.springframework=DEBUG
logging.level.com.demo=INFO

20. 

Multithreading | Concurrency Interview Questions (Along with JAVA 8 Enhancements)

1. How can a Java application access the current thread?



public class MainThread {

    public static void main(String[] args) {

        long id = Thread.currentThread().getId();

        String name = Thread.currentThread().getName();

        ...

    }

}



2. What properties does each Java thread have?

Each Java thread has the following properties:



an identifier of type long that is unique within the JVM

a name of type String

a priority of type int

a state of type java.lang.Thread.State

a thread group the thread belongs to



3. What states can a thread have and what is the meaning of each state?

4. Is it possible to start a thread twice?

No, after having started a thread by invoking its start() method, a second invocation of start() will throw an IllegalThreadStateException.

5. What is a daemon thread?

A daemon thread is a thread whose execution state is not evaluated when the JVM decides if it should stop or not. The JVM stops when all user threads (in contrast to the daemon threads) are terminated. Hence daemon threads can be used to implement for example monitoring functionality as the thread is stopped by the JVM as soon as all user threads have stopped:





public class Example {

    private static class MyDaemonThread extends Thread {

        public MyDaemonThread() {

            setDaemon(true);

        }

        @Override

        public void run() {

            while (true) {

                try {

                    Thread.sleep(1);

                } catch (InterruptedException e) {

                    e.printStackTrace();

                }

            }

        }

    }

    public static void main(String[] args) throws InterruptedException {

        Thread thread = new MyDaemonThread();

        thread.start();

    }

}

The example application above terminates even though the daemon thread is still running in its endless while loop.



6.How to take Thread Dump



You can generate a thread dump under Unix/Linux by running kill -QUIT <pid>, and under Windows by hitting Ctl + Break



7. What are differences between wait() and sleep() method in Java?

wait():

wait() method releases the lock.

wait() is the method of Object class.

wait() is the non-static method – public final void wait() throws InterruptedException { //…}

wait() should be notified by notify() or notifyAll() methods.

wait() method needs to be called from a loop in order to deal with false alarm.

wait() method must be called from synchronized context (i.e. synchronized method or block), otherwise it will throw IllegalMonitorStateException

sleep():



sleep() method doesn’t release the lock.

sleep() is the method of java.lang.Thread class.

sleep() is the static method – public static void sleep(long millis, int nanos) throws InterruptedException { //… }

after the specified amount of time, sleep() is completed.

sleep() better not to call from loop(i.e. see code below).

sleep() may be called from anywhere. there is no specific requirement.



8.  What happens when an uncaught exception leaves the run() method?

I can happen that an unchecked exception escapes from the run() method. In this case the thread is stopped by the Java Virtual Machine. It is possible to catch this exception by registering an instance that implements the interface UncaughtExceptionHandler as an exception handler.



This is either done by invoking the static method Thread.setDefaultUncaughtExceptionHandler(Thread.UncaughtExceptionHandler), which tells the JVM to use the provided handler in case there was no specific handler registerd on the thread itself, or by invoking setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler) on the thread instance itself.



9. What is the difference between the two interfaces Runnable and

Callable?



The interface Runnable defines the method run() without any return value whereas the interface Callable allows the method call() to return a value and to throw an exception.



10. What is a shutdown hook?

A shutdown hook is a thread that gets executed when the JVM shuts down. It can be registered by invoking addShutdownHook(Runnable) on the Runtime instance:



Runtime.getRuntime().addShutdownHook(new Thread() {

    @Override

    public void run() {

    }

});



11. Need for Callable



There are two ways of creating threads – one by extending the Thread class and other by creating a thread with a Runnable. However, one feature lacking in  Runnable is that we cannot make a thread return result when it terminates, i.e. when run() completes. For supporting this feature, the Callable interface is present in Java.



12. Callable vs Runnable



For implementing Runnable, the run() method needs to be implemented which does not return anything, while for a Callable, the call() method needs to be implemented which returns a result on completion. Note that a thread can’t be created with a Callable, it can only be created with a Runnable.

Another difference is that the call() method can throw an exception whereas run() cannot.



A Runnable, however, does not return a result and cannot throw a checked exception.



Method signature that has to overridden for implementing Callable.



public Object call() throws Exception;



13. Future

A Future represents the result of an asynchronous computation. Methods are provided to check if the computation is complete, to wait for its completion, and to retrieve the result of the computation. The result can only be retrieved using method get when the computation has completed, blocking if necessary until it is ready. Cancellation is performed by the cancel method. Additional methods are provided to determine if the task completed normally or was cancelled. Once a computation has completed, the computation cannot be cancelled.



Observe that Callable and Future do two different things – Callable is similar to Runnable, in that it encapsulates a task that is meant to run on another thread, whereas a Future is used to store a result obtained from a different thread. In fact, the Future can be made to work with Runnable as well, which is something that will become clear when Executors come into the picture.



 14. Shutting down exector



Finally, When you are done using the ExecutorService you should shut it down, so the threads do not keep running.



1

executor.shutdown();

For instance, if your application is started via a main() method and your main thread exits your application, the application will keep running if you have an active ExecutorService in your application. The active threads inside this ExecutorService prevents the JVM from shutting down.



To terminate the threads inside the ExecutorService you call its shutdown() method. The ExecutorService will not shut down immediately, but it will no longer accept new tasks, and once all threads have finished current tasks, the ExecutorService shuts down. All tasks submitted to the ExecutorService before shutdown() is called, are executed.



15.  Future Task Example :



CallableCalculater.java:


package com.jcg;

import java.util.concurrent.Callable;

/**
 * @author ashraf
 *
 */
public class CallableCalculater implements Callable {

    private long first;
    private long last;
    private long divisor;
   

    /**
     * Instantiates a new callable calculater.
     *
     * @param first the first
     * @param last the last
     * @param divisor the divisor
     */
    public CallableCalculater(long first, long last, long divisor) {
        this.first = first;
        this.last = last;
        this.divisor = divisor;
    }


    @Override
    public Long call() throws Exception {

        return Calculater.calculateNumberOfDivisible(first, last, divisor);
    }

}
CallableCalculater.java is wrapping the calculateNumberOfDivisible() of Calculater.java in a Callable task to be given to our FutureTask later on.

FutureTaskDemo.java:


package com.jcg;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;

/**
 * @author ashraf
 *
 */
public class FutureTaskDemo {
   
    // Maximum number to check
    public static final long MAX_NUMBER = 3000000000l;
   
    // DIVISOR to be used in calculation
    private static final long DIVISOR = 3;

    /**
     * @param args
     * @throws ExecutionException
     * @throws InterruptedException
     */
    public static void main(String[] args) {
       
        // Sequential execution
        System.out.println("Starting sequential execution ....");
        long timeStart = System.currentTimeMillis();
        long result = Calculater.calculateNumberOfDivisible(0, MAX_NUMBER, DIVISOR);
        long timeEnd = System.currentTimeMillis();
        long timeNeeded = timeEnd - timeStart;
        System.out.println("Result         : " + result + " calculated in " + timeNeeded + " ms");
       
       
        // Parallel execution
        System.out.println("Starting parallel execution ....");
        long timeStartFuture = System.currentTimeMillis();
       
        long resultFuture = 0;
       
        // Create a new ExecutorService with 2 thread to execute and store the Futures
        ExecutorService executor = Executors.newFixedThreadPool(2);
        List<FutureTask> taskList = new ArrayList<FutureTask>();

        // Start thread for the first half of the numbers
        FutureTask futureTask_1 = new FutureTask(new CallableCalculater(0, MAX_NUMBER / 2, DIVISOR));
        taskList.add(futureTask_1);
        executor.execute(futureTask_1);

        // Start thread for the second half of the numbers
        FutureTask futureTask_2 = new FutureTask(new CallableCalculater(MAX_NUMBER / 2 + 1, MAX_NUMBER, 3));
        taskList.add(futureTask_2);
        executor.execute(futureTask_2);

        // Wait until all results are available and combine them at the same time
        for (FutureTask futureTask : taskList) {
            try {
                resultFuture += futureTask.get();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
       
        // Shutdown the ExecutorService
        executor.shutdown();
       
        long timeEndFuture = System.currentTimeMillis();
        long timeNeededFuture = timeEndFuture - timeStartFuture;
        System.out.println("Result (Future): " + resultFuture + " calculated in " + timeNeededFuture + " ms");

    }

}


16.  Fork/Join Framework



The effective use of parallel cores in a Java program has always been a challenge. There were few home-grown frameworks that would distribute the work across multiple cores and then join them to return the result set. Java 7 has incorporated this feature as a Fork and Join framework.



Basically the Fork-Join breaks the task at hand into mini-tasks until the mini-task is simple enough that it can be solved without further breakups. It’s like a divide-and-conquer algorithm. One important concept to note in this framework is that ideally no worker thread is idle. They implement a work-stealing algorithm in that idle workers steal the work from those workers who are busy.



ForkJoinPool



The ForkJoinPool is basically a specialized implementation of ExecutorService implementing the work-stealing algorithm we talked about above. We create an instance of ForkJoinPool by providing the target parallelism level i.e. the number of processors as shown below:



ForkJoinPool pool = new ForkJoinPool(numberOfProcessors);



Where numberOfProcessors = Runtime.getRunTime().availableProcessors();



If you use a no-argument constructor, by default, it creates a pool of size that equals the number of available processors obtained using above technique.

Although you specify any initial pool size, the pool adjusts its size dynamically in an attempt to maintain enough active threads at any given point in time. Another important difference compared to other ExecutorService's is that this pool need not be explicitly shutdown upon program exit because all its threads are in daemon mode.



ForkJoinTask





This is an abstract class for creating tasks that run within a ForkJoinPool. The Recursiveaction and RecursiveTask are the only two direct, known subclasses of ForkJoinTask. The only difference between these two classes is that the RecursiveAction does not return a value while RecursiveTask does have a return value and returns an object of specified type.



In both cases, you would need to implement the compute method in your subclass that performs the main computation desired by the task.



The ForkJoinTask class provides several methods for checking the execution status of a task. The isDone() method returns true if a task completes in any way. The isCompletedNormally() method returns true if a task completes without cancellation or encountering an exception, and isCancelled() returns true if the task was cancelled. Lastly, isCompletedabnormally() returns true if the task was either cancelled or encountered an exception.



18 Example Implementations of Fork/Join Pool Framework

In this example, you will learn how to use the asynchronous methods provided by the ForkJoinPool and ForkJoinTask classes for the management of tasks. You are going to implement a program that will search for files with a determined extension inside a folder and its subfolders. The ForkJoinTask class you’re going to implement will process the content of a folder. For each subfolder inside that folder, it will send a new task to the ForkJoinPool class in an asynchronous way. For each file inside that folder, the task will check the extension of the file and add it to the result list if it proceeds.

The solution to above problem is implemented in FolderProcessor class, which is given below:

Implementation Sourcecode
FolderProcessor.java

package forkJoinDemoAsyncExample;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.RecursiveTask;

public class FolderProcessor extends RecursiveTask<List<String>>
{
   private static final long serialVersionUID = 1L;
   //This attribute will store the full path of the folder this task is going to process.
   private final String      path;
   //This attribute will store the name of the extension of the files this task is going to look for.
   private final String      extension;

   //Implement the constructor of the class to initialize its attributes
   public FolderProcessor(String path, String extension)
   {
      this.path = path;
      this.extension = extension;
   }

   //Implement the compute() method. As you parameterized the RecursiveTask class with the List<String> type,
   //this method has to return an object of that type.
   @Override
   protected List<String> compute()
   {
      //List to store the names of the files stored in the folder.
      List<String> list = new ArrayList<String>();
      //FolderProcessor tasks to store the subtasks that are going to process the subfolders stored in the folder
      List<FolderProcessor> tasks = new ArrayList<FolderProcessor>();
      //Get the content of the folder.
      File file = new File(path);
      File content[] = file.listFiles();
      //For each element in the folder, if there is a subfolder, create a new FolderProcessor object
      //and execute it asynchronously using the fork() method.
      if (content != null)
      {
         for (int i = 0; i < content.length; i++)
         {
            if (content[i].isDirectory())
            {
               FolderProcessor task = new FolderProcessor(content[i].getAbsolutePath(), extension);
               task.fork();
               tasks.add(task);
            }
            //Otherwise, compare the extension of the file with the extension you are looking for using the checkFile() method
            //and, if they are equal, store the full path of the file in the list of strings declared earlier.
            else
            {
               if (checkFile(content[i].getName()))
               {
                  list.add(content[i].getAbsolutePath());
               }
            }
         }
      }
      //If the list of the FolderProcessor subtasks has more than 50 elements,
      //write a message to the console to indicate this circumstance.
      if (tasks.size() > 50)
      {
         System.out.printf("%s: %d tasks ran.\n", file.getAbsolutePath(), tasks.size());
      }
      //add to the list of files the results returned by the subtasks launched by this task.
      addResultsFromTasks(list, tasks);
      //Return the list of strings
      return list;
   }

   //For each task stored in the list of tasks, call the join() method that will wait for its finalization and then will return the result of the task.
   //Add that result to the list of strings using the addAll() method.
   private void addResultsFromTasks(List<String> list, List<FolderProcessor> tasks)
   {
      for (FolderProcessor item : tasks)
      {
         list.addAll(item.join());
      }
   }

   //This method compares if the name of a file passed as a parameter ends with the extension you are looking for.
   private boolean checkFile(String name)
   {
      return name.endsWith(extension);
   }
}
And to use above FolderProcessor, follow below code:

Main.java

package forkJoinDemoAsyncExample;

import java.util.List;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.TimeUnit;

public class Main
{
   public static void main(String[] args)
   {
      //Create ForkJoinPool using the default constructor.
      ForkJoinPool pool = new ForkJoinPool();
      //Create three FolderProcessor tasks. Initialize each one with a different folder path.
      FolderProcessor system = new FolderProcessor("C:\\Windows", "log");
      FolderProcessor apps = new FolderProcessor("C:\\Program Files", "log");
      FolderProcessor documents = new FolderProcessor("C:\\Documents And Settings", "log");
      //Execute the three tasks in the pool using the execute() method.
      pool.execute(system);
      pool.execute(apps);
      pool.execute(documents);
      //Write to the console information about the status of the pool every second
      //until the three tasks have finished their execution.
      do
      {
         System.out.printf("******************************************\n");
         System.out.printf("Main: Parallelism: %d\n", pool.getParallelism());
         System.out.printf("Main: Active Threads: %d\n", pool.getActiveThreadCount());
         System.out.printf("Main: Task Count: %d\n", pool.getQueuedTaskCount());
         System.out.printf("Main: Steal Count: %d\n", pool.getStealCount());
         System.out.printf("******************************************\n");
         try
         {
            TimeUnit.SECONDS.sleep(1);
         } catch (InterruptedException e)
         {
            e.printStackTrace();
         }
      } while ((!system.isDone()) || (!apps.isDone()) || (!documents.isDone()));
      //Shut down ForkJoinPool using the shutdown() method.
      pool.shutdown();
      //Write the number of results generated by each task to the console.
      List<String> results;
      results = system.join();
      System.out.printf("System: %d files found.\n", results.size());
      results = apps.join();
      System.out.printf("Apps: %d files found.\n", results.size());
      results = documents.join();
      System.out.printf("Documents: %d files found.\n", results.size());
   }
}
Output of above program will look like this:

Main: Parallelism: 2
Main: Active Threads: 3
Main: Task Count: 1403
Main: Steal Count: 5551
******************************************
******************************************
Main: Parallelism: 2
Main: Active Threads: 3
Main: Task Count: 586
Main: Steal Count: 5551
******************************************
System: 337 files found.
Apps: 10 files found.
Documents: 0 files found.

How it works?
In the FolderProcessor class, Each task processes the content of a folder. As you know, this content has the following two kinds of elements:

Files
Other folders
If the task finds a folder, it creates another Task object to process that folder and sends it to the pool using the fork() method. This method sends the task to the pool that will execute it if it has a free worker-thread or it can create a new one. The method returns immediately, so the task can continue processing the content of the folder. For every file, a task compares its extension with the one it’s looking for and, if they are equal, adds the name of the file to the list of results.

Once the task has processed all the content of the assigned folder, it waits for the finalization of all the tasks it sent to the pool using the join() method. This method called in a task waits for the finalization of its execution and returns the value returned by the compute() method. The task groups the results of all the tasks it sent with its own results and returns that list as a return value of the compute() method.





19. Difference between Fork/Join Framework And ExecutorService



The main difference between the Fork/Join and the Executor frameworks is the work-stealing algorithm. Unlike the Executor framework, when a task is waiting for the finalization of the sub-tasks it has created using the join operation, the thread that is executing that task (called worker thread ) looks for other tasks that have not been executed yet and begins its execution. By this way, the threads take full advantage of their running time, thereby improving the performance of the application.



Existing Implementations in JDK

There are some generally useful features in Java SE which are already implemented using the fork/join framework.



1) One such implementation, introduced in Java SE 8, is used by the java.util.Arrays class for its parallelSort() methods. These methods are similar to sort(), but leverage concurrency via the fork/join framework. Parallel sorting of large arrays is faster than sequential sorting when run on multiprocessor systems.



2) Parallelism used in Stream.parallel(). Read more about this parallel stream operation in java 8.





20.  JAVA 8 Enhancements



Java JDK8 included the big fat interface called CompletionStage in the java.util.concurrent package. The same package also contains CompletableFuture which is a library implementation of CompletionStage. In this post we would see how CompletionStage and CompletableFuture provide piped asynchronous API thus enhancing reactive programming support in Java at the platform level.





21. CompletableFuture



CompletableFuture is a concrete implementation of a CompletionStage and it also implements the java.util.concurrent.Future interface as well. This is the class which models a task (which may or may not be asynchronous) and exposes various methods to interact with the task; for instance, we have methods to check if the task has completed; whether it has completed exceptionally; we even have APIs to chain dependencies between multiple tasks; cancelling uncompleted tasks, so on and so forth. We would be looking into some of these APIs soon.





A CompletableFuture can be instantiated and related methods can be called upon it, and we will see this in action in the subsequent section. However, there are convenient, static overloaded factory methods which provides further flexibility so that rather than worrying about harnessing CompletableFuture for a task, we can just concentrate on the task itself. I will explain this in a bit, but lets quickly have a look at the overloaded factory methods that I am talking about:

CompletableFuture supplyAsync() API


public static CompletableFuture supplyAsync(Supplier supplier)
public static CompletableFuture supplyAsync(Supplier supplier, Executor executor)
java.util.function.Supplier is a functional interface which accepts nothing and “supplies” an output. The supplyAsync() API expects that a result-producing task be wrapped in a Supplier instance and handed over to the supplyAsync() method, which would then return a CompletableFuture representing this task. This task would, by default, be executed with one of the threads from the standard java.util.concurrent.ForkJoinPool (public static ForkJoinPool commonPool()).

However, we can also provide custom thread pool by passing a java.util.concurrent.Executor instance and as such the Supplier tasks would be scheduled on threads from this Executor instance.

So to sum up the, the easiest way of using CompletableFuture API is to wrap the task you want to execute in a Supplier – you may additionally supply an Executor service as needed – and hand it over to the supplyAsync() method which would return you the CompletableFuture!

There is yet another variant API available for retrieving a CompletableFuture. Notice that while discussing supplyAsync() I wrote that this is to be used when task would be result-bearing, in other words, when we expect the task to return back some output. However, in all cases where the task might not return any output, we may use the runAsyn() API, instead:

CompletableFuture runAsync() API


public static CompletableFuture runAsync(Runnable runnable)
public static CompletableFuture runAsync(Runnable runnable, Executor executor)
Notice that runAsync() expects a java.lang.Runnable instance, and we know that Runnable.run() does not return any result! This is the reason that the returned CompletableFuture type erases itself to Void type.



22. Completing the CompletableFuturer manually



A CompletableFuture can be instantiated through its no-arg constructor. And then we can manually provide a Runnable instance to a custom thread; and then CompletableFuture API provides complete method using which the CompletableFuture can be manually completed:

How to manually complete a CompletableFuture


//1. Why named CompletableFuture?
        CompletableFuture completableFuture1 = new CompletableFuture();
        new Thread (()-> {
            try {
                Thread.sleep(4000L);
            } catch (Exception e) {
                completableFuture1.complete(-100.0);
            }
            /*
             * we can manually "complete" a CompletableFuture!!
             * this feature is not found with the classical Future interface
             */
            completableFuture1.complete(100.0);
        },"CompFut1-Thread").start();
       
        System.out.println("ok...waiting at: "+new Date());
        System.out.format("compFut value and received at: %f, %s \n", completableFuture1.join(), new Date());


23. More cases of Completable future



https://www.callicoder.com/java-8-completablefuture-tutorial/



https://examples.javacodegeeks.com/core-java/util/concurrent/completablefuture/java-completionstage-completablefuture-example/

Very Good Article for Completable future :

https://netjs.blogspot.com/2018/11/completablefuture-in-java-with-examples.html


24.