Last active
July 28, 2016 07:37
-
-
Save tasdemirbahadir/16e26949c89aa8aa44886d59c7695783 to your computer and use it in GitHub Desktop.
Using Threads Via Spring Services
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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