I am a Javascript front-end developer, but need to write a simple Java program to write file and sent Email and HTTP request.
Here is the Java code that I use to write log to disk file:
@Override
public void log(String text) {
Date date = new Date();
DateFormat sdf = new SimpleDateFormat("yyyyMMdd");
DateFormat sdf1 = new SimpleDateFormat("HH:mm:ss");
String logDateString = sdf.format(date);
//System.out.println("logDateString: " + logDateString);
BufferedWriter bwToUse = null;
if(logDateString.compareTo(m_firstOpenDate) == 0) {
// use old buffer writer
bwToUse = this.m_bw;
} else {
// generate new buffer writer
// update m_firstOpenDate
m_firstOpenDate = logDateString;
try {
// close previous day log
this.m_bw.close();
this.m_fw = new FileWriter(m_path + logDateString + ".log", true);
this.m_bw = new BufferedWriter(this.m_fw);
bwToUse = this.m_bw;
} catch (IOException e) {
e.printStackTrace();
}
}
try {
bwToUse.write(sdf1.format(date) + ": " + text + "\n");
bwToUse.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
You can ignore the detail.
My real question is that for those heavy IO operation, e.g.: file reading, sending email and making HTTP request(post data to a web hook), how to do it in a non-blocking async way in Java? I know it is standard in Javascript to use callback, but in Java, how do you do async http request?
Thanks!
Simply taking a callback doesn't make a function asynchronous. There are many examples of functions that take a function argument but are not asynchronous.
The callback is a function that's accepted as an argument and executed by another function (the higher-order function). There are 2 kinds of callback functions: synchronous and asynchronous. The synchronous callbacks are executed at the same time as the higher-order function that uses the callback.
For JavaScript to know when an asynchronous operation has a result (a result being either returned data or an error that occurred during the operation), it points to a function that will be executed once that result is ready. This function is what we call a “callback function”.
A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.
The closest concept in Java is Future.
But you should be aware that Java has a multithreading concurrency model, as opposed to single-threaded JavaScript with asynchronous concurrency model. If you're new to this concept, then you better start with a Tutorial.
Also for IO-operations you should consider non-blocking IO API.
You can use FutureTask. You should implemets Callable
interface. Here is a sample
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With