Skip to content

Instantly share code, notes, and snippets.

@tasdemirbahadir
Last active July 28, 2016 07:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tasdemirbahadir/16e26949c89aa8aa44886d59c7695783 to your computer and use it in GitHub Desktop.
Save tasdemirbahadir/16e26949c89aa8aa44886d59c7695783 to your computer and use it in GitHub Desktop.
Using Threads Via Spring Services
/*
* By the design pattern below, you can easily run any code blocks on a Service in Spring MVC.
* This provides a easy usage way of threads, high code maintainability and readability.
*/
public class SpringServiceThread {
@Service
public class ThreadService {
public void runThread(GenericMethodInterface genericMethodInterface) {
GeneralPurposeRunnable runnable = new GeneralPurposeRunnable(genericMethodInterface);
Thread thread = new Thread(runnable);
thread.start();
}
}
public class GeneralPurposeRunnable implements Runnable {
private GenericMethodInterface genericMethodInterface;
public GeneralPurposeRunnable(GenericMethodInterface genericMethodInterface) {
this.genericMethodInterface = genericMethodInterface;
}
@Override
public void run() {
genericMethodInterface.genericMethod();
}
}
public interface GenericMethodInterface {
public void genericMethod();
}
/**
* Usage sample inside a controller
*/
@Controller
public class CustomController {
@Autowired
private ThreadService threadService;
@RequestMapping(value = "/save")
public void runViaThread(HttpServletRequest request) {
threadService.runThread(new GenericMethodInterface() {
@Override
public void genericMethod() {
//Start of code blocks
System.out.println("Runs in thread.");
System.out.println("Also this runs in thread.");
//End of code blocks
}
});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment