Skip to content

Instantly share code, notes, and snippets.

@mstephenson6
Created March 25, 2020 18:27
Show Gist options
  • Save mstephenson6/760a41b5d9c9a9601c86aa0ad369862d to your computer and use it in GitHub Desktop.
Save mstephenson6/760a41b5d9c9a9601c86aa0ad369862d to your computer and use it in GitHub Desktop.
package com.example.demo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadLocalRandom;
@Component
public class AsyncWorkers {
private final Logger logger = LoggerFactory.getLogger(AsyncWorkers.class);
@Async
public Future<String> longRunningTask(int n) {
logger.info("longRunningTask() has started");
try {
Thread.sleep(ThreadLocalRandom.current().nextInt(3000, 5000));
}
catch (InterruptedException ie) {
// do nothing!
}
String result = "";
for (int i=0; i<n; ++i) {
result += i + " ";
}
logger.info("longRunningTask() is returning");
return new AsyncResult<>(result);
}
}
package com.example.demo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Component
public class CmdLine implements CommandLineRunner {
private final Logger logger = LoggerFactory.getLogger(CmdLine.class);
@Autowired
private AsyncWorkers asyncWorkers;
@Override
public void run(String... args) throws Exception {
logger.info("run() has started");
asyncWorkers.longRunningTask(5);
logger.info("run() has finished");
}
}
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
@SpringBootApplication
@EnableAsync
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment