manage thread with junit4 - multithreading

With Junit4, I tried to write a test (.class) that contains 3 #test and need to open the app in each test.
So in the function init that start the app and close it:
#BeforeClass
public static void setupOnce() {
final Thread thread = new Thread() {
public void run() {
//start the appli in the main
thread.start();
}
}
}
#AfterClass
public static void CloseAppli() {
closeAppli();
}
In my testClass: TestButtons.java I want to start the appli in each #test which is not possible...
Any idea?

It seems what you're looking for is the #After method. That's called after every individual test. #AfterClass is only called once at the ending of ALL the tests.
http://junit.sourceforge.net/javadoc/org/junit/After.html

Related

simple problems in multi thread in java

I need help to get the answer for this :
The question asked what is the output of the following codes?
package tryScope;
public class MyThread extends Thread{
public void run() {
System.out.println("MyThread: run()");
}
public void start() {
System.out.println("MyThread: start()");
}
}
class MyRunnable implements Runnable{
public void run() {
System.out.println("MyRunnable: run()");
}
public void start() {
System.out.println("MyRunnable: start()");
}
}
public class myTest {
public static void main(String[] args) {
MyThread myThread = new MyThread();
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
myThread.start();
}
}
So, I am suppose to choose 1 correct answer but I can't even make it run. I would like to verify if there is something wrong with the code the question is set?
Here are the 4 choices:
Prints: MyThread: run() followed by MyRunnable: start()
Prints: MyThread: start() followed by MyRunnable:start()
Prints: MyThread: run() followed by MyRunnable:run()
Prints: MyThread: start() followed by MyRunnable:run()
Please let me know which is the correct answer and if there is something wrong with the code.
Tks.
I think this code is just stupid. The output should be "MyThread: start()" and nothing else.
Thats because in the class MyThread the start method is overwritten. So there's no Thread starting at all. You can try modify the method like this:
public class MyThread extends Thread{
public void run() {
System.out.println("MyThread: run()");
}
public void start() {
System.out.println("MyThread: start()");
super.start();
}
}
Then the ouput should be something like "MyThread: start()" followed by "MyThread: run()"
To achieve this:
MyThread: start() followed by MyRunnable:run()
add in the main-method the line:
myRunnable.run()
Note: You shouldn't override the start method in Thread at all, as mentioned above from Hejday. This method handles the intern creation and starting of the Thread. The Thread will then execute it's run method see Thread.

JSF Concurrency - Launch threads from managed beans to call Service

I have a ManagedBean that can call a Service that accesses the database. That service has the #Service and #Transactional annotations, and since it is a service that has functions to mess around in the database, it obviously is called in a number of places.
In my frontend, in my managed bean I want to call for a function that is like a job, a batch, and it can take quite a while. The job can take like 1 minute and I don't want the client to be waiting on the frontend that long, since there may be jobs that can take like an hour.
I'll post an example of the code I have currently (just consider I have in my xhtml file some button that calls the launchBatch() function):
#ManagedBean
#RequestScoped
public class JobLauncherController {
#ManagedProperty("#{serviceController}")
private ServiceController serviceController;
public void launchBatch(String code) {
switch (code) {
case Constants.Batch.BATCH_1:
Thread t1 = new Thread(new Runnable() {
public void run() {
serviceController.getBatchService().batch1();
}
});
t1.start();
break;
case Constants.Batch.BATCH_2:
Thread t2 = new Thread(new Runnable() {
public void run() {
Date date = new Date();
String parameters = String
.valueOf(date.getHours() + ":" + date.getMinutes() +
":" + date.getSeconds());
serviceController.getBatchService().batch2(parameters);
}
});
t2.start();
break;
case Constants.Batch.BATCH_3:
Thread t3 = new Thread(new Runnable() {
public void run() {
serviceController.getBatchService().batch3();
}
});
t3.start();
break;
case Constants.Batch.BATCH_4:
Thread t4 = new Thread(new Runnable() {
public void run() {
serviceController.getBatchService().batch4();
}
});
t4.start();
break;
default:
break;
}
showGrowl();
}
public void showGrowl() {
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "",
"Job launched sucessfully!");
FacesContext.getCurrentInstance().addMessage("growlPanel", message);
}
public ServiceController getServiceController() {
return serviceController;
}
public void setServiceController(ServiceController serviceController) {
this.serviceController = serviceController;
}
}
My service (interface):
public interface AppBatchService {
public void batch1();
public void batch2(Object parameters);
public void batch3();
public void batch4();
}
And the implementation
#Service
#Transactional
public class AppBatchServiceImpl implements AppBatchService {
//code to implementation goes here
}
So this is launching a thread successfully, because when I debug this, I have put the functions batchN to sleep for like a minute, and the code keeps flowing to my showGrowl() and my showGrowl(), ends the code flow successfully, the problem is at frontend, because it doesn't complete the action of the button while the thread I launched is running.
Is there a specific way to start threads when dealing with JSF/Primefaces to end the action, without changing the service I have? I've seen solutions with #Stateless and with #Asynchronous on the functions, but I cannot change this structure.

How to run multiple Runnable in Java threadpool?

How can I execute bunch of different method or Runnable using "ExecutorService" parrally?
I think you understood what I am trying to say..
Thanks
An application that creates an instance of Thread must provide the code that will run in that thread. There are two ways to do this:
Provide a Runnable object. The Runnable interface defines a single method, run, meant to contain the code executed in the thread. The Runnable object is passed to the Thread constructor, as in the HelloRunnable example:
public class HelloRunnable implements Runnable {
public void run() {
System.out.println("Hello from a thread!");
}
public static void main(String args[]) {
(new Thread(new HelloRunnable())).start();
}
}
Subclass Thread. The Thread class itself implements Runnable, though its run method does nothing. An application can subclass Thread, providing its own implementation of run, as in the HelloThread example:
public class HelloThread extends Thread {
public void run() {
System.out.println("Hello from a thread!");
}
public static void main(String args[]) {
(new HelloThread()).start();
}
}
See java documentation here https://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html

Context switching not happening between a created thread and main thread

I am trying to run a thread in background with while(true) condition, and not using any join after the thread so that it continue running the main thread. But what I am observing is only while loop is running and it is not switching to main thread. please help me find the issue. This is Groovy code.
public static void main(args) {
Thread.start {
while (true) {
long sleepMillis = 2000
System.out.println("inside async block")
Thread.sleep(sleepMillis)
}
}
//main func code goes here
}
Please give me pointers to the issue.
Here You go:
public class Lol {
public static void main(String[] args) {
def t = new Thread(new Runnable() {
public void run() {
while(true) {
println 'lol'
Thread.sleep(500)
}
}
}).start()
println 'other'
}
}

How to stop an infinite thread in an application server

i have a JSF web application deployed under glassfish in which i have two buttons.The first start a infinite thread and the second stop it.My problem is that i can not stop a running thread.I have searched for a solution on the net but in vain.it works in case i have a J2SE application but not with a J2EE application here is my code
package com.example.beans;
import org.apache.commons.lang.RandomStringUtils;
public class MyBusinessClass {
public static void myBusinessMethod() {
/* this method takes a lot of time */
int i = 1;
while (i == 1) {
String random = RandomStringUtils.random(3);
System.out.println(random);
}
}
}
package com.example.beans;
import java.util.Random;
import java.util.TimerTask;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.log4j.Logger;
import com.example.core.RandomUtils;
public class MySimpleRunnableTask implements Runnable {
private Logger logger = Logger.getLogger(MySimpleRunnableTask.class);
#Override
public void run() {
MyBusinessClass.myBusinessMethod();
}
}
#ManagedBean(name = "MainView")
#SessionScoped
public class MainView {
private static Thread myThread;
#SuppressWarnings({ "unchecked", "rawtypes", "deprecation" })
public String startSimpleThread() throws SecurityException,
NoSuchMethodException,
InterruptedException {
MySimpleRunnableTask mySimpleRunnableTask = new MySimpleRunnableTask();
myThread = new Thread(mySimpleRunnableTask);
myThread.start();
return null;
}
#SuppressWarnings({ "unchecked", "rawtypes", "deprecation" })
public String stopSimpleThread() throws SecurityException,
NoSuchMethodException,
InterruptedException {
myThread.interrupt();
return null;
}
}
I have changed my code so you can understand really what's my problem
interrupt only sets the interrupt status in the thread to true. The thread needs to regularly pool the interrupt status flag to stop running:
public void run() {
/* you will have to touch the code here */
int i = 1;
while (i == 1) {
String random = RandomStringUtils.random(3);
logger.info(random);
if (Thread.currentThread().isInterrupted()) {
// the thread has been interrupted. Stop running.
return;
}
}
}
This is the only way to properly stop a thread : ask him to stop. Without cooperation from the running thread, there is no clean way.

Resources