MultiThread – How to Run Multiple Threads Concurrently in Java? ExecutorService Approach

Standard

Let’s take a look at this example again: How to get Ping Status of any HTTP End Point in Java?

Have you noticed the thread execution for that example? It’s sequential. What if you have 500 endpoints? I bet you have to wait for at least 5 mins to get result. Which I’m sure is not the best solution.

Now what? The correct question would be:

  • How to Run multiple threads concurrently?
  • How to implement multiple threads in Java?
  • How do I run different threads in Java?
  • Java – Where is Multithreading Programming Tutorial?
  • Thread: How to use multiple threads to speed processing?

ExecutorService Approach is your answer.

An Executor that provides methods to manage termination and methods that can produce a Future for tracking progress of one or more asynchronous tasks.

An ExecutorService can be shut down, which will cause it to reject new tasks. Two different methods are provided for shutting down an ExecutorService. The shutdown() method will allow previously submitted tasks to execute before terminating, while the shutdownNow()method prevents waiting tasks from starting and attempts to stop currently executing tasks.

Upon termination, an executor has no tasks actively executing, no tasks awaiting execution, and no new tasks can be submitted. An unused ExecutorService should be shut down to allow reclamation of its resources.

Method submit extends base method Executor.execute (java.lang.Runnable) by creating and returning a Future that can be used to cancel execution and/or wait for completion. Methods invokeAny and invokeAll perform the most commonly useful forms of bulk execution, executing a collection of tasks and then waiting for at least one, or all, to complete. (Class ExecutorCompletionService can be used to write customized variants of these methods.)

The Executors class provides factory methods for the executor services provided in this package.

  • java – ExecutorService, how to wait for all tasks to finish?
  • A Guide to the Java ExecutorService
  • Java Thread Pool – ExecutorService explanation

Below is a simple Java Example which explains the usage of ExecutorService.

Output:

Now checkout the result. It should be in just seconds. I hope you find this helpful. Try running this more than one time and you may see different result as all threads are executing in parallels and who ever gets fast result, you will see result posted in Eclipse console.

Install Oracle DB

Standard
  1. Download Oracle DB 12c :
    1. https://www.oracle.com/technetwork/database/enterprise-edition/downloads/oracle12c-windows-3633015.html
  2. Connect to sqlplus :
    1. Open cmd and type : CONN / AS SYSDBA
      1. And  if CONN / AS SYSDBA is not working then type : Sqlplus / as sysdba
    2. 1)      Create dump directory

      CREATE DIRECTORY dump_dir as ‘E:/dmp’

       

      GRANT READ, WRITE ON DIRECTORY dump_dir TO system;

       

      And place your dmp file in E:/dmp folder

      Now exit the sqlplus and run the below command directly on shell

      2)      Import dump file

      impdp system/<password>@ORCL directory=dump_dir  dumpfile=DB12c1.dmp logfile=imp_tab.log full=Y

       

      here DB12c1.dmp is your dmpfile name

Spring 4 MVC, Hibernate, MySQL Database, Maven CRUD Operations Integration using Annotation Tutorial

Standard

Follow the steps mentioned below to develop this application :

Setting up Database

Execute the following MySQL script in order to create a database named jack_rutorial_demo with a table named customer.

CREATE DATABASE `jack_rutorial_demo`;

CREATE TABLE `customer` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `firstname` varchar(45) NOT NULL DEFAULT '',
  `lastname` varchar(45) NOT NULL DEFAULT '',
  `gender` varchar(10) NOT NULL DEFAULT '',
  `address` varchar(200) NOT NULL DEFAULT '',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

 

Project Structure

The following screenshot shows final structure of the project.

Project Structure Spring 4 MVC Hibernate MySQL Database Maven CRUD Operations Integration

 

Create Maven Project

 

  • Launch Eclipse IDE.
  • Go to File-> New-> Others… Select Maven Project under Maven category then click Next.
  • In New Maven Project wizard, select “Create a simpel project(skip archetype selection)” and click on Next
  • In next wizard, type “com.jackrutorial” in the “Group ID:” field
  • Type “SpringMVCHibernateExample” in the “Artifact Id:” field
  • Packaging -> War
  • Click Finish.

 

Maven Dependencies

We will update pom.xml file to add the required dependencies for the following dependencies.

<project xmlns="http://maven.apache.org/POM/4.0.0" 
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>com.jackrutorial</groupId>
 <artifactId>SpringMVCHibernateExample</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <packaging>war</packaging>

 <dependencies>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-webmvc</artifactId>
   <version>4.3.0.RELEASE</version>
  </dependency>

  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-tx</artifactId>
   <version>4.3.0.RELEASE</version>
  </dependency>
  
  <dependency>
   <groupId>jstl</groupId>
   <artifactId>jstl</artifactId>
   <version>1.2</version>
  </dependency>
  
  <dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>javax.servlet-api</artifactId>
   <version>3.1.0</version>
   <scope>provided</scope>
  </dependency>
  
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-jdbc</artifactId>
   <version>4.3.0.RELEASE</version>
  </dependency>
  
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-orm</artifactId>
   <version>4.3.0.RELEASE</version>
  </dependency>
  
  <dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-core</artifactId>
   <version>4.3.6.Final</version>
  </dependency>
  
  <dependency>
   <groupId>javax.validation</groupId>
   <artifactId>validation-api</artifactId>
   <version>1.1.0.Final</version>
  </dependency>

 </dependencies>

 <build>
  <pluginManagement>
   <plugins>
    <plugin>
     <groupId>org.apache.maven.plugins</groupId>
     <artifactId>maven-war-plugin</artifactId>
     <version>2.4</version>
     <configuration>
      <warSourceDirectory>src/main/webapp</warSourceDirectory>
      <failOnMissingWebXml>false</failOnMissingWebXml>
     </configuration>
    </plugin>
   </plugins>
  </pluginManagement>
 </build>
</project>

 

Configure WebApp and Hibernate

To configure WebApp, we create class WebConfig, class WebInitializer in src folder with package name com.jackrutorial.config and write the following code in it.

WebConfig.java

package com.jackrutorial.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = { "com.jackrutorial" })
public class WebConfig extends WebMvcConfigurerAdapter {
 
 @Override
 public void addResourceHandlers(ResourceHandlerRegistry registry) {
  registry.addResourceHandler("resources/**").addResourceLocations("/resources/");
 }
 
 @Bean
 public InternalResourceViewResolver viewResolver(){
  InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
  viewResolver.setViewClass(JstlView.class);
  viewResolver.setPrefix("/WEB-INF/jsp/");
  viewResolver.setSuffix(".jsp");
  
  return viewResolver;
 }
 
}

WebInitializer.java

package com.jackrutorial.config;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer  {

 @Override
    protected Class[] getRootConfigClasses() {
        return new Class[] { WebConfig.class};
    }
  
    @Override
    protected Class[] getServletConfigClasses() {
        return null;
    }
  
    @Override
    protected String[] getServletMappings() {
        return new String[] { "/" };
    }

}

To configure hibernate, we create class HibernateConfig in src folder with package name com.jackrutorial.config and write the following code in it.

HibernateConfig.java 

package com.jackrutorial.config;

import java.util.Properties;
import javax.sql.DataSource;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
@ComponentScan({ "com.jackrutorial.config" })
@PropertySource(value = { "classpath:config.properties" })
public class HibernateConfig {
 
 @Autowired
 private Environment environment;
 
 @Bean
    public LocalSessionFactoryBean sessionFactory() {
        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        sessionFactory.setDataSource(dataSource());
        sessionFactory.setPackagesToScan(new String[] { "com.jackrutorial.model" });
        sessionFactory.setHibernateProperties(hibernateProperties());
        return sessionFactory;
     }
 
 @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
        dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
        dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));
        dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
        return dataSource;
    }
 
 private Properties hibernateProperties() {
        Properties properties = new Properties();
        properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
        properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
        properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
        return properties;        
    }
 
 @Bean
    @Autowired
    public HibernateTransactionManager transactionManager(SessionFactory s) {
       HibernateTransactionManager txManager = new HibernateTransactionManager();
       txManager.setSessionFactory(s);
       return txManager;
    }
}

We still have to configure config.properties file in classpath. We create a config.properties file in src/main/resources folder and write the following code in it.

jdbc.driverClassName = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/jack_rutorial_demo
jdbc.username = root
jdbc.password = root
hibernate.dialect = org.hibernate.dialect.MySQLDialect
hibernate.show_sql = true
hibernate.format_sql = false

MySQL Database Name: jack_rutorial_demo
Password for MySQL: root
Username for MySQL: root

Create Hibernate Entity Bean

Create a Customer class under com.jackrutorial.model package and write the following code in it.

Customer.java

package com.jackrutorial.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="customer")
public class Customer {

 @Id
 @GeneratedValue(strategy = GenerationType.IDENTITY)
 private int id;
 
 @Column(name = "firstname")
 private String firstname;
 
 @Column(name = "lastname")
 private String lastname;
 
 @Column(name = "gender")
 private String gender;
 
 @Column(name = "address")
 private String address;

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getFirstname() {
  return firstname;
 }

 public void setFirstname(String firstname) {
  this.firstname = firstname;
 }

 public String getLastname() {
  return lastname;
 }

 public void setLastname(String lastname) {
  this.lastname = lastname;
 }

 public String getGender() {
  return gender;
 }

 public void setGender(String gender) {
  this.gender = gender;
 }

 public String getAddress() {
  return address;
 }

 public void setAddress(String address) {
  this.address = address;
 }
}

In the above code, we are using JPA annotations in our entity bean class. Our entity bean maps to customer table in MySQL database.

Creating DAO Layer

Create a CustomerDao Interface under com.jackrutorial.dao package and write the following code in it.

CustomerDao.java

package com.jackrutorial.dao;

import java.util.List;

import com.jackrutorial.model.Customer;

public interface CustomerDao {
 
 public List listAllCustomers();
 
 public void saveOrUpdate(Customer customer);
 
 public Customer findCustomerById(int id);
 
 public void deleteCustomer(int id);
 
}

Create a CustomerDaoImpl class implements CustomerDao Interface under com.jackrutorial.dao package and write the following code in it.

CustomerDaoImpl.java

package com.jackrutorial.dao;

import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.jackrutorial.model.Customer;

@Repository
public class CustomerDaoImpl implements CustomerDao {

 @Autowired
 private SessionFactory sessionFactory;

 protected Session getSession(){
  return sessionFactory.getCurrentSession();
 }
 
 @SuppressWarnings("unchecked")
 public List listAllCustomers() {
  Criteria criteria = getSession().createCriteria(Customer.class);
  return (List) criteria.list();
 }

 public void saveOrUpdate(Customer customer) {
  getSession().saveOrUpdate(customer);
 }

 public Customer findCustomerById(int id) {
  Customer customer = (Customer) getSession().get(Customer.class, id);
  return customer;
 }

 public void deleteCustomer(int id) {
  Customer customer = (Customer) getSession().get(Customer.class, id);
  getSession().delete(customer);
 }
}

 

Creating Service Layer

Create a CustomerService Interface under package com.jackrutorial.service package and write the following code in it.

CustomerService.java 

package com.jackrutorial.service;

import java.util.List;

import com.jackrutorial.model.Customer;

public interface CustomerService {
 
 public List listAllCustomers();
 
 public void saveOrUpdate(Customer customer);
 
 public Customer findCustomerById(int id);
 
 public void deleteCustomer(int id);
}

Create a CustomerServiceImpl class implements CustomerService Interface under com.jackrutorial.service package and write the following code in it.

CustomerServiceImpl.java 

package com.jackrutorial.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jackrutorial.dao.CustomerDao;
import com.jackrutorial.model.Customer;

@Service
@Transactional
public class CustomerServiceImpl implements CustomerService {
 
 CustomerDao customerDao;
 
 @Autowired
 public void setCustomerDao(CustomerDao customerDao) {
  this.customerDao = customerDao;
 }

 public List listAllCustomers() {
  return customerDao.listAllCustomers();
 }

 public void saveOrUpdate(Customer customer) {
  customerDao.saveOrUpdate(customer);
 }

 public Customer findCustomerById(int id) {
  return customerDao.findCustomerById(id);
 }

 public void deleteCustomer(int id) {
  customerDao.deleteCustomer(id);
 }

}

 

Creating Controller Layer

Create a CustomerController class under package com.jackrutorial.controller package and write the following code in it.

CustomerController.java

package com.jackrutorial.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.jackrutorial.model.Customer;
import com.jackrutorial.service.CustomerService;

@Controller
@RequestMapping(value="/customer")
public class CustomerController {

 @Autowired
 CustomerService customerService;
 
 @RequestMapping(value="/list", method=RequestMethod.GET)
 public ModelAndView list(){
  ModelAndView model = new ModelAndView("customer/list");
  List list = customerService.listAllCustomers();
  model.addObject("list", list);
  
  return model;
 }
 
 @RequestMapping(value="/update/{id}", method=RequestMethod.GET)
 public ModelAndView update(@PathVariable("id") int id){
  ModelAndView model = new ModelAndView("customer/form");
  Customer customer = customerService.findCustomerById(id);
  model.addObject("customerForm", customer);
  
  return model;
 }
 
 @RequestMapping(value="/delete/{id}", method=RequestMethod.GET)
 public ModelAndView delete(@PathVariable("id") int id){
  customerService.deleteCustomer(id);
  
  return new ModelAndView("redirect:/customer/list");
 }
 
 @RequestMapping(value="/add", method=RequestMethod.GET)
 public ModelAndView add(){
  ModelAndView model = new ModelAndView("customer/form");
  Customer customer = new Customer();
  model.addObject("customerForm", customer);
  
  return model;
 }
 
 @RequestMapping(value="/save", method=RequestMethod.POST)
 public ModelAndView save(@ModelAttribute("customerForm") Customer customer){
  customerService.saveOrUpdate(customer);
  
  return new ModelAndView("redirect:/customer/list");
 }
}

 

Creating JSP Views

Create customer folder under src\main\webapp\WEB-INF\jsp\customer folder.
Create list.jsp file under src\main\webapp\WEB-INF\jsp\customer folder and write the following code in it.

list.jsp 

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" 
pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Customer</title>
</head>
<body>
 <spring:url value="/customer/add" var="addURL" />
 <a href="${addURL }">Add new Customer</a>
 
 <table width="100%" border="1">
  <tr>
   <td>ID</td>
   <td>Firstname</td>
   <td>Lastname</td>
   <td>Gender</td>
   <td>Address</td>
   <td colspan="2">Action</td>
  </tr>  
  <c:forEach items="${list }" var="customer" >
   <tr>
    <td>${customer.id }</td>
    <td>${customer.firstname }</td>
    <td>${customer.lastname }</td>
    <td>${customer.gender }</td>
    <td>${customer.address }</td>
    <td>
     <spring:url value="/customer/update/${customer.id }" var="updateURL" />
     <a href="${updateURL }">Update</a>
    </td>
    <td>
     <spring:url value="/customer/delete/${customer.id }" var="deleteURL" />
     <a href="${deleteURL }">Delete</a>
    </td>
   </tr>
  </c:forEach>
 </table>
</body>
</html>

Create form.jsp file under src\main\webapp\WEB-INF\jsp\customer folder and write the following code in it.

form.jsp 

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" 
pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Form</title>
</head>
<body>
 <spring:url value="/customer/save" var="saveURL" />
 
 <form:form action="${saveURL }" method="POST" modelAttribute="customerForm">
  <form:hidden path="id"/>
  <table>
   <tr>
    <td>Firstname</td>
    <td><form:input path="firstname"/></td>
   </tr>
   <tr>
    <td>Lastname</td>
    <td><form:input path="lastname"/></td>
   </tr>  
   <tr>
    <td>Gender: </td>
    <td>
     <form:radiobutton path="gender" value="Male" /> Male
     <form:radiobutton path="gender" value="Female" /> Female
    </td>
   </tr> 
   <tr>
    <td>Address</td>
    <td><form:textarea path="address" rows="3" /></td>
   </tr>
   <tr>
    <td></td>
    <td><button type="submit">Save</button></td>
   </tr>
  </table>
 </form:form>
</body>
</html>

 

Building

  • Right click this project
  • Select Run As -> Maven clean
  • Right click this project
  • Select Run As -> Maven install

JavaScript Date Functions

Standard
  • Get today date :

var today = new Date();

  • Set date :

var someday = new Date();
someday.setFullYear(2015, 7, 27);

  • Get date 30 days prior to current date :

var priorDate = new Date(new Date().setDate(new Date().getDate() – 30));

  • Compare date greater or less than other date :

if (someday < priorDate ) {
text = “Less than 30 days”;
} else {
text = “Not less than 30 days”;
}

Encoding and Decoding string in java and javascript

Standard
  • Encoding and Decoding string in java :

Library file need to import : import java.util.Base64;

Encoding :

String dataString = “Hello Java!”

String encodedString = Base64.getEncoder().encodeToString(dataString.getBytes());

Decoding :

byte[] decoded = Base64.getDecoder().decode(encodedString);
String decodedString = new String(decoded);

  • Encoding and Decoding string in javaScript :

     Example : var str = “Need tips? Visit W3Schools!”; var str_esc = escape(str); document.write(str_esc + “<br>”) document.write(unescape(str_esc)); Output : Need%20tips%3F%20Visit%20W3Schools%21 Need tips? Visit W3Schools!