I am trying multithreading in java for the first time. My problem statement is to fetch the data from an api for multiple months together. Therefor I tried 2-3 things and stuck with the below code. I am getting null value while printing f.get(). Anyone who can explain why it is printing null value for all?
class StyleThreadDemo implements Callable<String>{
private Integer n;
public StyleThreadDemo(int a){
this.setN(a);
}
public String callApi() throws Exception {
String output=null;
try {
URL url = new URL("https://api.publicapis.org/entries");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
System.out.println("Data starting coming .... \n");
while ((output = br.readLine()) != null) {
System.out.println("result " n );
}
conn.disconnect();
}catch(Exception e) {
e.printStackTrace();
}
return output;
}
@Override
public String call() throws Exception {
String s=callApi();
return s;
}
public Integer getN() {
return n;
}
public void setN(Integer n) {
this.n = n;
}
}
public class StyleThread {
public static void shutdownAndAwaitTermination(ExecutorService executorService) {
executorService.shutdown();
try {
if (!executorService.awaitTermination(60, TimeUnit.SECONDS)) {
executorService.shutdownNow();
}
} catch (InterruptedException ie) {
executorService.shutdownNow();
Thread.currentThread().interrupt();
}
}
public static void main(String[] args) throws Exception
{
StyleThread styleThread = new StyleThread();
ExecutorService pool = Executors.newFixedThreadPool(30);
int n = 5; // Number of threads
List<StyleThreadDemo> tasks= new ArrayList<StyleThreadDemo>();
// List<Future<String>> futures = new ArrayList<>();
for (int i = 0; i < n; i ) {
// Future<String> result= pool.submit(new StyleThreadDemo(i));
// futures.add(result);
tasks.add(new StyleThreadDemo(i));
System.out.println("task added " i);
}
List<Future<String>> futures=pool.invokeAll(tasks);
shutdownAndAwaitTermination(pool);
for (Future<String> f : futures) {
System.out.println("printing : f.get());
}
}
}
CodePudding user response:
your probleme is here :
while ((output = br.readLine()) != null) {
System.out.println("result " n );
}
[...]
return output;
when you are getting out your loop output is null
solution
StringBuilder sb = new StringBuilder();
while ((output = br.readLine()) != null) {
System.out.println("result " n );
sb.append(output);
}
[...]
return sb.toString();
CodePudding user response:
br.readLine()
returns null when the end of the stream is reached. So you eventually assign null to output
.
try:
output = new String(conn.getInputStream().readAllBytes(), StandardCharsets.UTF_8);