Skip to content

Instantly share code, notes, and snippets.

@FreeFly19
Created October 23, 2017 09:57
Show Gist options
  • Save FreeFly19/4dc00fb419bab56f80a935709483f970 to your computer and use it in GitHub Desktop.
Save FreeFly19/4dc00fb419bab56f80a935709483f970 to your computer and use it in GitHub Desktop.
Multithreading procedure calls
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.*;
public class Main {
static MysqlDataSource mysqlDataSource = new MysqlDataSource();
static ExecutorService executor = Executors.newFixedThreadPool(30);
public static void main(String[] args) throws SQLException, InterruptedException {
mysqlDataSource.setServerName("127.0.0.1");
mysqlDataSource.setDatabaseName("my_db");
mysqlDataSource.setUser("root");
mysqlDataSource.setPassword("root");
Connection c = mysqlDataSource.getConnection();
ResultSet rs = c.createStatement().executeQuery("select task_id from task order by task_id desc");
Queue<Long> taskIds = new LinkedList<>();
while (rs.next()) {
taskIds.add(rs.getLong("task_id"));
}
BlockingQueue<TaskInfo> taskInfos = new LinkedBlockingQueue<>();
taskIds.stream().map(Main::getFutureTaskInfo).forEach(f -> f.thenAccept(taskInfos::add));
executor.shutdown();
TaskInfo taskInfo;
while(true) {
taskInfo = taskInfos.poll(10, TimeUnit.SECONDS);
if (taskInfo == null) System.exit(0);
if (taskInfo.exception != null) {
System.err.println(taskInfo);
} else {
System.out.println(taskInfo);
}
}
}
public static CompletableFuture<TaskInfo> getFutureTaskInfo(Long taskId) {
return CompletableFuture.supplyAsync(() -> {
TaskInfo ti = new TaskInfo();
ti.taskId = taskId;
try {
Connection con = mysqlDataSource.getConnection();
CallableStatement callableStatement = con.prepareCall("CALL myProcedure(?)");
callableStatement.setLong(1, taskId);
ResultSet percRS = callableStatement.executeQuery();
percRS.first();
ti.percentage = percRS.getInt(1);
con.close();
} catch (SQLException e) {
ti.exception = e;
}
return ti;
}, executor);
}
static class TaskInfo {
long taskId;
int percentage;
Exception exception;
@Override
public String toString() {
return String.format("TaskInfo{taskId=%d, percentage=%d, exception=%s}", taskId, percentage, exception);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment