Skip to content

Instantly share code, notes, and snippets.

@pablohdzvizcarra
Created December 3, 2023 19:50
Show Gist options
  • Save pablohdzvizcarra/56b873cb719e1cde44d928cc8a826d1a to your computer and use it in GitHub Desktop.
Save pablohdzvizcarra/56b873cb719e1cde44d928cc8a826d1a to your computer and use it in GitHub Desktop.
Tutorial: what is an executor in Java
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.concurrent.Executor;
import java.util.logging.Level;
import java.util.logging.Logger;
public class RunningTaskWithExecutor {
private static final Logger logger = Logger.getLogger("App");
public static void main(String[] args) {
RunningTaskWithExecutor app = new RunningTaskWithExecutor();
app.run();
}
private void run() {
logger.info("Starting Application");
BasicExecutor executor = new BasicExecutor();
executor.execute(this::makeHttpRequest);
executor.execute(this::makeHttpRequest);
executor.execute(this::makeHttpRequest);
logger.info("Finish Application");
}
private void makeHttpRequest() {
try {
URL urlToRequest = new URI("https://jsonplaceholder.typicode.com/todos/1").toURL();
HttpURLConnection connection = (HttpURLConnection) urlToRequest.openConnection();
connection.setRequestMethod("GET");
int responseCode = connection.getResponseCode();
logger.log(Level.INFO, "Response code: {0}", responseCode);
} catch (URISyntaxException | IOException e) {
logger.warning(e.getMessage());
}
}
class BasicExecutor implements Executor {
@Override
public void execute(Runnable runnable) {
new Thread(runnable).start();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment