I have below code
public void addNames(){
List<String> names = new ArrayList<String>
names.parallelStream().foreach(name->add(name));
}
private void add(String name){
SQLSession session = SQLSessionFactory.getSession(config);
Connection con=Session.openConnection();
con.insert(name);
con.commit;
con.close
}
The problem here is “name->add(name)”
will execute for each name, there by I am opening and closing connections for each name. If I have millions of records then this is a problem.
I can’t open the connection outside “names.parallelStream().foreach(name->add(name, connection));”
and pass it as parameter, because all the threads will get blocked on one connection object.
So, I want to obtain the connection per thread, How can I do this using
“names.parallelStream().foreach(name->add(name));”
?
I want do following per thread
- Obtain connection
- Insert
- Insert
- Insert —— N Inserts
- Commit and close connection
If I am creating and starting a thread I can do this, How can we achieve this per thread using parallelStreams?
In short, I want the thread in parallelStream to obtain connection per thread and execute name->add(name)
and once done the thread should commit and close the connection. Is this possible ?