I have to read Employee data from a text file(each record is separated by tab) into a ArrayList. Then I have to insert this employee objects from list to the Employee table in DB. For this, I am iterating the list elements one by one and inserting Employee details one at a time into DB. This approach is not recommended performance wise because we can have more than 100k records and it will take so much time to insert the whole data.
How can we use multi threading here while inserting data from list to db to improve performance. Also how can we use CountDownLatch and ExecutorService classes to optimize this scenario.
ReadWriteTest
public class ReadWriteTest {
public static void main(String... args) {
BufferedReader br = null;
String filePath = "C:\\Documents\\EmployeeData.txt";
try {
String sCurrentLine;
br = new BufferedReader(new FileReader(filePath));
List<Employee> empList = new ArrayList<Employee>();
while ((sCurrentLine = br.readLine()) != null) {
String[] record = sCurrentLine.split("\t");
Employee emp = new Employee();
emp.setId(record[0].trim());
emp.setName(record[1].trim());
emp.setAge(record[2].trim());
empList.add(emp);
}
System.out.println(empList);
writeData(empList);
} catch (IOException | SQLException e) {
e.printStackTrace();
}
}
public static void writeData(List<Employee> empList) throws SQLException {
Connection con =null;
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
for(Employee emp : empList)
{
PreparedStatement stmt=con.prepareStatement("insert into Employee values(?,?,?)");
stmt.setString(1,emp.getId());
stmt.setString(2,emp.getName());
stmt.setString(3,emp.getAge());
stmt.executeUpdate();
}
}catch(Exception e){
System.out.println(e);
}
finally{
con.close();
}
}
}
Employee Class
public class Employee {
String id;
String name;
String age;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", age=" + age + "]";
}
}
EmployeeData.txt
1 Sachin 20
2 Sunil 30
3 Saurav 25