How to hit 1000 endpoints using multi threading in groovy? - multithreading

I have a requirement to hit endpoints more than 1000 times to fetch some data from website. So i read some tutorials to use Multi Threading to achieving it. But at a time i want to use only 13 threads on same method.
So basically i am using ExecutorService to run 13 threads at one time:
ExecutorService threadPool = Executors.newFixedThreadPool(13);
for (int itLocation = 0; itLocation < locationList.size(); itLocation++) {
//some code like
ScraperService obj = new ScraperService(threadName,url)
threadPool.submit(obj);
}
threadPool.shutdown();
My Groovy Class named as ScraperService is implementing the Runnable interface.
#Override
void run() {
println("In run method...................")
try {
Thread.sleep(5000);
someMethod()
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Problem:
My problem is that my ExecutorService.submit(obj) and ExecutorService.execute(obj) is not calling my run() method of Runnable interface.
In Groovy/Grails:
There is also a executor plugin Executor Plugin in grails but i didn't found any appropriate example how to use it.

GPars is excellent for this type of thing.
Your ScraperService can just be responsible for handling the scraped data like below or maybe fetching it too, whatever.
import groovyx.gpars.GParsPool
def theEndpoint = 'http://www.bbc.co.uk'
def scraperService
GParsPool.withPool( 13 ) {
(1..1000).eachParallel {
scraperService.scrape theEndpoint.toURL().text
}
}

First of all i think there is problem in groovy service class with #Transnational annotation which doesn't allow to call run() method of Runnable interface. If you'll remove the #Transnational then it will call the run() method. It happened also in my case. But i am not sure, there may be some another reason. You can directly use:
ExecutorService threadPool = Executors.newFixedThreadPool(13)
threadPool.execute(new Runnable() {
#Override
void run() {
Thread.sleep(5000);
someMethod()
}
})
Extra (As i read your question)
If you are using multiple threads on same method then it can be complex as all threads will use the same local variables of that method which can occurs problems. It is better to use multiple threads for different different work.
But if you want to use same method for executing multiple threads then in my scenario it is better to use Executors.newSingleThreadExecutor().
ExecutorService threadPool = Executors.newSingleThreadExecutor();
newSingleThreadExecutor() calls a single thread so if you want to execute multiple tasks on it then it does not create multiple threads. Instead, it waits for one task to complete before starting the next task on the same thread.
Speed: newSingleThreadExecutor in comparison of multi threads will be slow but safer to use.

the threadPool.submit does not execute task
use threadPool.execute(obj) or threadPool.submit(obj).get()
instead of threadPool.submit(obj)
check the documentation for details:
https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html#submit(java.util.concurrent.Callable)
example:
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
ExecutorService pool=Executors.newFixedThreadPool(3)
for(int i=0;i<7;i++){
int x=i;
Thread.sleep(444);
pool.execute{
println "start $x"
Thread.sleep(3000+x*100);
println "end $x"
}
}
println "done cycle"
pool.shutdown() //all tasks submitted
while (!pool.isTerminated()){} //waitfor termination
println 'Finished all threads'

Related

Thread thread = new Thread(() -> { /code } and Executorservice.submit(thread). How to write junit on this using powermock

Please help me write Junit for this piece of code using Mockito /Powermock, Finding it difficult due to lamda expression and executor service.
public class myClass {
ExecutorService executorService;
public void testMethod(String a){
Thread thread = new Thread(() -> {
//logic
a= testDAo.getStatus();
while (true) {
if (Thread.interrupted()) {
break;
}
if (a() != "done" || a() != "fail") {
Thread.yield();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
}
} else {
break;
}
}
}
Future task = executorService.submit(thread);
while (!task.isDone()) {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
}
}
}
}
Various things here:
first of all: for testing executors and parallel execution, using a same thread executor can be extremely helpful (because it takes out the parallel aspect)
you have difficulties writing a unit test - because your production code is way too complicated.
Thus the real answer is: step back and improve your production code. Why again are you pushing a thread into an executor service?
The executor service is already doing things on a thread pool (at least that is how you normally use them). So you push a thread into a thread pool, and then you have code that waits "two" times (first within that thread, and then outside on the future). That just adds a ton of complexity for small gain.
Long story short:
I would get rid of that "inner thread" - just have the executor task wait until the result becomes available
Then: if lambda's give you trouble - then don't use them. Just create a named small class that implements that code. And then you can write unit tests for that small class. In other words: don't create huge "units" that do 5 different things. The essence of a good unit is to one thing (single responsibility principle!). And as soon as you follow that idea testing becomes much easier, too.

New Thread doesn't open scene [duplicate]

I'm trying to understand how threads works in java. This is a simple database request that returns a ResultSet. I'm using JavaFx.
package application;
import java.sql.ResultSet;
import java.sql.SQLException;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
public class Controller{
#FXML
private Button getCourseBtn;
#FXML
private TextField courseId;
#FXML
private Label courseCodeLbl;
private ModelController mController;
private void requestCourseName(){
String courseName = "";
Course c = new Course();
c.setCCode(Integer.valueOf(courseId.getText()));
mController = new ModelController(c);
try {
ResultSet rs = mController.<Course>get();
if(rs.next()){
courseCodeLbl.setText(rs.getString(1));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// return courseName;
}
public void getCourseNameOnClick(){
try {
// courseCodeLbl.setText(requestCourseName());
Thread t = new Thread(new Runnable(){
public void run(){
requestCourseName();
}
}, "Thread A");
t.start();
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
This returns an exception:
Exception in thread "Thread A" java.lang.IllegalStateException: Not on FX application thread; currentThread = Thread A
How do I correctly implement threading so that every database request is executed in a second thread instead of the main thread?
I've heard of implementing Runnable but then how do I invoke different methods in run method?
Never worked with threading before but I thought it's time for it.
Threading Rules for JavaFX
There are two basic rules for threads and JavaFX:
Any code that modifies or accesses the state of a node that is part of a scene graph must be executed on the JavaFX application thread. Certain other operations (e.g. creating new Stages) are also bound by this rule.
Any code that may take a long time to run should be executed on a background thread (i.e. not on the FX Application Thread).
The reason for the first rule is that, like most UI toolkits, the framework is written without any synchronization on the state of elements of the scene graph. Adding synchronization incurs a performance cost, and this turns out to be a prohibitive cost for UI toolkits. Thus only one thread can safely access this state. Since the UI thread (FX Application Thread for JavaFX) needs to access this state to render the scene, the FX Application Thread is the only thread on which you can access "live" scene graph state. In JavaFX 8 and later, most methods subject to this rule perform checks and throw runtime exceptions if the rule is violated. (This is in contrast to Swing, where you can write "illegal" code and it may appear to run fine, but is in fact prone to random and unpredictable failure at arbitrary time.) This is the cause of the IllegalStateException you are seeing: you are calling courseCodeLbl.setText(...) from a thread other than the FX Application Thread.
The reason for the second rule is that the FX Application Thread, as well as being responsible for processing user events, is also responsible for rendering the scene. Thus if you perform a long-running operation on that thread, the UI will not be rendered until that operation is complete, and will become unresponsive to user events. While this won't generate exceptions or cause corrupt object state (as violating rule 1 will), it (at best) creates a poor user experience.
Thus if you have a long-running operation (such as accessing a database) that needs to update the UI on completion, the basic plan is to perform the long-running operation in a background thread, returning the results of the operation when it is complete, and then schedule an update to the UI on the UI (FX Application) thread. All single-threaded UI toolkits have a mechanism to do this: in JavaFX you can do so by calling Platform.runLater(Runnable r) to execute r.run() on the FX Application Thread. (In Swing, you can call SwingUtilities.invokeLater(Runnable r) to execute r.run() on the AWT event dispatch thread.) JavaFX (see later in this answer) also provides some higher-level API for managing the communication back to the FX Application Thread.
General Good Practices for Multithreading
The best practice for working with multiple threads is to structure code that is to be executed on a "user-defined" thread as an object that is initialized with some fixed state, has a method to perform the operation, and on completion returns an object representing the result. Using immutable objects, in particular, a record, for the initialized state and computation result is highly desirable. The idea here is to eliminate the possibility of any mutable state being visible from multiple threads as far as possible. Accessing data from a database fits this idiom nicely: you can initialize your "worker" object with the parameters for the database access (search terms, etc). Perform the database query and get a result set, use the result set to populate a collection of domain objects, and return the collection at the end.
In some cases it will be necessary to share mutable state between multiple threads. When this absolutely has to be done, you need to carefully synchronize access to that state to avoid observing the state in an inconsistent state (there are other more subtle issues that need to be addressed, such as liveness of the state, etc). The strong recommendation when this is needed is to use a high-level library to manage these complexities for you.
Using the javafx.concurrent API
JavaFX provides a concurrency API that is designed for executing code in a background thread, with API specifically designed for updating the JavaFX UI on completion of (or during) the execution of that code. This API is designed to interact with the java.util.concurrent API, which provides general facilities for writing multithreaded code (but with no UI hooks). The key class in javafx.concurrent is Task, which represents a single, one-off, unit of work intended to be performed on a background thread. This class defines a single abstract method, call(), which takes no parameters, returns a result, and may throw checked exceptions. Task implements Runnable with its run() method simply invoking call(). Task also has a collection of methods which are guaranteed to update state on the FX Application Thread, such as updateProgress(...), updateMessage(...), etc. It defines some observable properties (e.g. state and value): listeners to these properties will be notified of changes on the FX Application Thread. Finally, there are some convenience methods to register handlers (setOnSucceeded(...), setOnFailed(...), etc); any handlers registered via these methods will also be invoked on the FX Application Thread.
So the general formula for retrieving data from a database is:
Create a Task to handle the call to the database.
Initialize the Task with any state that is needed to perform the database call.
Implement the task's call() method to perform the database call, returning the results of the call.
Register a handler with the task to send the results to the UI when it is complete.
Invoke the task on a background thread.
For database access, I strongly recommend encapsulating the actual database code in a separate class that knows nothing about the UI (Data Access Object design pattern). Then just have the task invoke the methods on the data access object.
So you might have a DAO class like this (note there is no UI code here):
public class WidgetDAO {
// In real life, you might want a connection pool here, though for
// desktop applications a single connection often suffices:
private Connection conn ;
public WidgetDAO() throws Exception {
conn = ... ; // initialize connection (or connection pool...)
}
public List<Widget> getWidgetsByType(String type) throws SQLException {
try (PreparedStatement pstmt = conn.prepareStatement("select * from widget where type = ?")) {
pstmt.setString(1, type);
ResultSet rs = pstmt.executeQuery();
List<Widget> widgets = new ArrayList<>();
while (rs.next()) {
Widget widget = new Widget();
widget.setName(rs.getString("name"));
widget.setNumberOfBigRedButtons(rs.getString("btnCount"));
// ...
widgets.add(widget);
}
return widgets ;
}
}
// ...
public void shutdown() throws Exception {
conn.close();
}
}
Retrieving a bunch of widgets might take a long time, so any calls from a UI class (e.g a controller class) should schedule this on a background thread. A controller class might look like this:
public class MyController {
private WidgetDAO widgetAccessor ;
// java.util.concurrent.Executor typically provides a pool of threads...
private Executor exec ;
#FXML
private TextField widgetTypeSearchField ;
#FXML
private TableView<Widget> widgetTable ;
public void initialize() throws Exception {
widgetAccessor = new WidgetDAO();
// create executor that uses daemon threads:
exec = Executors.newCachedThreadPool(runnable -> {
Thread t = new Thread(runnable);
t.setDaemon(true);
return t ;
});
}
// handle search button:
#FXML
public void searchWidgets() {
final String searchString = widgetTypeSearchField.getText();
Task<List<Widget>> widgetSearchTask = new Task<List<Widget>>() {
#Override
public List<Widget> call() throws Exception {
return widgetAccessor.getWidgetsByType(searchString);
}
};
widgetSearchTask.setOnFailed(e -> {
widgetSearchTask.getException().printStackTrace();
// inform user of error...
});
widgetSearchTask.setOnSucceeded(e ->
// Task.getValue() gives the value returned from call()...
widgetTable.getItems().setAll(widgetSearchTask.getValue()));
// run the task using a thread from the thread pool:
exec.execute(widgetSearchTask);
}
// ...
}
Notice how the call to the (potentially) long-running DAO method is wrapped in a Task which is run on a background thread (via the accessor) to prevent blocking the UI (rule 2 above). The update to the UI (widgetTable.setItems(...)) is actually executed back on the FX Application Thread, using the Task's convenience callback method setOnSucceeded(...) (satisfying rule 1).
In your case, the database access you are performing returns a single result, so you might have a method like
public class MyDAO {
private Connection conn ;
// constructor etc...
public Course getCourseByCode(int code) throws SQLException {
try (PreparedStatement pstmt = conn.prepareStatement("select * from course where c_code = ?")) {
pstmt.setInt(1, code);
ResultSet results = pstmt.executeQuery();
if (results.next()) {
Course course = new Course();
course.setName(results.getString("c_name"));
// etc...
return course ;
} else {
// maybe throw an exception if you want to insist course with given code exists
// or consider using Optional<Course>...
return null ;
}
}
}
// ...
}
And then your controller code would look like
final int courseCode = Integer.valueOf(courseId.getText());
Task<Course> courseTask = new Task<Course>() {
#Override
public Course call() throws Exception {
return myDAO.getCourseByCode(courseCode);
}
};
courseTask.setOnSucceeded(e -> {
Course course = courseTask.getCourse();
if (course != null) {
courseCodeLbl.setText(course.getName());
}
});
exec.execute(courseTask);
The API docs for Task have many more examples, including updating the progress property of the task (useful for progress bars..., etc.
Related
JavaFX - Background Thread for SQL Query
Sample for accessing a local database from JavaFX using concurrent tasks for database operations so that the UI remains responsive.
Exception in thread "Thread A" java.lang.IllegalStateException: Not on FX application thread; currentThread = Thread A
The exception is trying to tell you that you are trying to access JavaFX scene graph outside the JavaFX application thread. But where ??
courseCodeLbl.setText(rs.getString(1)); // <--- The culprit
If I can't do this how do I use a background thread?
The are different approaches which leads to similar solutions.
Wrap you Scene graph element with Platform.runLater
There easier and most simple way is to wrap the above line in Plaform.runLater, such that it gets executed on JavaFX Application thread.
Platform.runLater(() -> courseCodeLbl.setText(rs.getString(1)));
Use Task
The better approach to go with these scenarios is to use Task, which has specialized methods to send back updates. In the following example, I am using updateMessage to update the message. This property is bind to courseCodeLbl textProperty.
Task<Void> task = new Task<Void>() {
#Override
public Void call() {
String courseName = "";
Course c = new Course();
c.setCCode(Integer.valueOf(courseId.getText()));
mController = new ModelController(c);
try {
ResultSet rs = mController.<Course>get();
if(rs.next()) {
// update message property
updateMessage(rs.getString(1));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
public void getCourseNameOnClick(){
try {
Thread t = new Thread(task);
// To update the label
courseCodeLbl.textProperty.bind(task.messageProperty());
t.setDaemon(true); // Imp! missing in your code
t.start();
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
This has nothing to do with database. JavaFx, like pretty much all GUI libraries, requires that you only use the main UI thread to modify the GUI.
You need to pass the data from the database back to the main UI thread. Use Platform.runLater() to schedule a Runnable to be run in the main UI thread.
public void getCourseNameOnClick(){
new Thread(new Runnable(){
public void run(){
String courseName = requestCourseName();
Platform.runLater(new Runnable(){
courseCodeLbl.setText(courseName)
});
}
}, "Thread A").start();
}
Alternatively, you can use Task.

What is the purpose of await() in CountDownLatch?

I have the following program, where I am using java.util.concurrent.CountDownLatch and without using await() method it's working fine.
I am new to concurrency and want to know the purpose of await(). In CyclicBarrier I can understand why await() is needed, but why in CountDownLatch?
Class CountDownLatchSimple:
public static void main(String args[]) {
CountDownLatch latch = new CountDownLatch(3);
Thread one = new Thread(new Runner(latch),"one");
Thread two = new Thread(new Runner(latch), "two");
Thread three = new Thread(new Runner(latch), "three");
// Starting all the threads
one.start(); two.start(); three.start();
}
Class Runner implements Runnable:
CountDownLatch latch;
public Runner(CountDownLatch latch) {
this.latch = latch;
}
#Override
public void run() {
System.out.println(Thread.currentThread().getName()+" is Waiting.");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
latch.countDown();
System.out.println(Thread.currentThread().getName()+" is Completed.");
}
OUTPUT
two is Waiting.
three is Waiting.
one is Waiting.
one is Completed.
two is Completed.
three is Completed.
CountDownLatch is the synchronization primitive which is used to wait for all threads completing some action.
Each of the thread is supposed to mark the work done by calling countDown() method. The one who waits for the action to be completed should call await() method. This will wait indefinitely until all threads mark the work as processed, by calling the countDown(). The main thread can then continue by processing the worker's results for example.
So in your example it would make sense to call await() at the end of main() method:
latch.await();
Note: there are many other use cases of course, they don't need to be threads but whatever that runs usually asynchronously, the same latch can be decremented several times by the same task etc. The above describes just one common use case for CountDownLatch.

ThreadPoolExecutor is not executing concurrently?

This is for my academic purpose only. Are the tasks that we add to the executor service are really executing in parallel. Well this is my example that raised this question
Runnable Class
public Tasks implement Runnable{
int taskCount;
public Tasks(int count){
this.taskCount = count;
}
public void run(){
System.out.println("In Task :"+taskcount +" run method");
}
}
Main Class
Class MyTest {
public static void main(String args[]){
ExecutorService service = Executors.newFixedThreadPool(10);
for(inti=0;i<10;i++){
Tasks taskObj = new Tasks(i);
service.submit(taskObj);
}
service.shutdown();
}
}
As soon as i submit a taskObj to the executor, the taskObj run() is invoked.
What if i have to something like this,
Add all the taskObj to the executor , the run() must not get invoked
Execute all the task objects at one shot. All the taskobj run() must be executed in parallel/concurrently
Please let me know
Thanks...V
If I understood you right, one way to solve this would be to use thread barriers. This might sound strange, but is actually implemented quite easy. You just take a variable (lets name it traffic-light) and make every thread loop on it. If you started enough threads (starting a new thread might consume some time) you just change it to green and all your threads will start execution at the same time.
For academic purposes we used to take an atomic-integer as counter (initialized with 0) and started n threads. The task of each threads was to increase the counter and then loop on it until it reached n. Like this you'll have all threads as parallel as possible.
If you still want to go with a thread pool system, you might have to implement your own thread system, where threads can wait upon a signal prior to grabbing work.
good luck

Managing threads in Grails Services

So I have a service set up to import a large amount of data from a file the user uploads. I want to the user to be able to continue working on the site while the file is being processed. I accomplished this by creating a thread.
Thread.start {
//work done here
}
Now the problem arises that I do not want to have multiple threads running simultaneously. Here is what I tried:
class SomeService {
Thread thread = new Thread()
def serviceMethod() {
if (!thread?.isAlive()) {
thread.start {
//Do work here
}
}
}
}
However, this doesn't work. thread.isAlive() always return false. Any ideas on how I can accomplish this?
I would consider using an Executor instead.
import java.util.concurrent.*
import javax.annotation.*
class SomeService {
ExecutorService executor = Executors.newSingleThreadExecutor()
def serviceMethod() {
executor.execute {
//Do work here
}
}
#PreDestroy
void shutdown() {
executor.shutdownNow()
}
}
Using a newSingleThreadExecutor will ensure that tasks execute one after the other. If there's a background task already running then the next task will be queued up and will start when the running task has finished (serviceMethod itself will still return immediately).
You may wish to consider the executor plugin if your "do work here" involves GORM database access, as that plugin will set up the appropriate persistence context (e.g. Hibernate session) for your background tasks.
Another way to do this is to use Spring's #Async annotation.
Add the following to resources.groovy:
beans = {
xmlns task:"http://www.springframework.org/schema/task"
task.'annotation-driven'('proxy-target-class':true, 'mode':'proxy')
}
Any service method you now annotate with #Async will run asynchronously, e.g.
#Async
def reallyLongRunningProcess() {
//do some stuff that takes ages
}
If you only want one thread to run the import at a time, you could do something like this -
class MyService {
boolean longProcessRunning = false
#Async
def reallyLongRunningProcess() {
if (longProcessRunning) return
try {
longProcessRunning = true
//do some stuff that takes ages
} finally {
longProcessRunning = false
}
}
}

Resources