the main class:
package com.xxx.yyy;
public class Hello{
public static void main(String[] args){
A a = new A();
while(true){
try {
a.execute(1000);
Thread.sleep(1000);
}catch (Exception e){
e.printStackTrace();
}
}
}
}
class A:
package com.xxx.yyy;
public class A{
public void execute(int sleepTime) throws Exception {
System.out.println("sleep time is "+sleepTime);
}
}
btrace script:
import static com.sun.btrace.BTraceUtils.println;
import static com.sun.btrace.BTraceUtils.str;
import static com.sun.btrace.BTraceUtils.strcat;
import static com.sun.btrace.BTraceUtils.timeMillis;
import com.sun.btrace.annotations.BTrace;
import com.sun.btrace.annotations.Kind;
import com.sun.btrace.annotations.Location;
import com.sun.btrace.annotations.OnMethod;
import com.sun.btrace.annotations.ProbeClassName;
import com.sun.btrace.annotations.ProbeMethodName;
import com.sun.btrace.annotations.TLS;
#BTrace
public class BtraceTest{
#OnMethod(clazz="com.xxx.yyy.A",method="execute",location=#Location(Kind.RETURN))
public static void traceExecute(#ProbeClassName String name,#ProbeMethodName String method,int sleepTime){
println(strcat("the class name=>", name));
println(strcat("the class method=>", method));
println(strcat("the class method params=>", str(sleepTime)));
}
}
everything is right.
BUT: when I move the line Thread.sleep(1000) to class A's execute function, like this:
package com.xxx.yyy;
public class A{
public void execute(int sleepTime) throws Exception {
System.out.println("sleep time is "+sleepTime);
Thread.sleep(1000);
}
}
the NoSuchMethodError is thrown by Hello.
Exception in thread "main" java.lang.NoSuchMethodError: com.xxx.yyy.A.$btrace$BtraceTest$traceExecute(Ljava/lang/String;Ljava/lang/String;I)V
at com.xxx.yyy.A.execute(Unknown Source)
at com.xxx.yyy.Hello.main(Hello.java:8)
my environment is
java version "1.8.0_121"
BTrace v.1.3.9 (20170111)
anyone can explain why?thanks!
I think your class should implements Runnable or extends Thread. Then only you can use start, sleepand such similar methods in your program. Have a look at here to know how to implement thread methods.
Related
I am using AssertThrows to test for an exception thrown in a thread. I know an exception is thrown since the exception message shows before the AssertionFail message.
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class Main {
public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(1);
SingleThread thread = new SingleThread();
pool.execute(thread);//Thread 1 (in real application there are several)
}
}
class SingleThread implements Runnable{
#Override
public void run() {
throw new NullPointerException();
}
}
class Testing{
#Test
public void SingleThreadTest() {
SingleThread testClass = new SingleThread();
ExecutorService executor = Executors.newCachedThreadPool();
executor.execute(testClass);
Assertions.assertThrows(NullPointerException.class, () -> executor.execute(testClass));
}
}
It appears that JUnit does not see the exception since it is not thrown on the main thread. Is it possible for JUnit detect the exception in this situation?
UPDATE
I was wrong the whole time. I was blocking the output with a method I was using and didn't add here. Now it works well and I'm able to write from other process.
I would like to know if there is any way of printing a line to a console view from outside. I have a class (class1) that has an onMessage method.
public class Class1 implements MessageListener {
...
public void onMessage(Message msg) {
System.out.println(msg.getText());
}
...
}
And then I have a class with a main that creates an instance of this class and while doing things the onMessage of Class1 fires.
public class Class2{
public static void main(String args[]) {
Class1 obj = new Class1();
...
while(!":q".equals((action = scanner.next()))){
obj.anotherAction(action);
}
...
}
}
When I try that the object seems to be blocked. I think that I'm approaching wrong to the solution. Maybe calling println from outside blocks as it doesn't have anywhere to print to.
I would like to understand what's happening and how could I solve this. My problem is using the output that creates the Class2 main from Class1.
I hope I explained well, I'm not a native speaker.
EDIT
Now I added more coding. I'm now realizing that waiting for the standard input maybe is interfering with the Print of the other class. Should I run an external proccess for the output? How could I do it on the same console view?
try this
Class1.java
import java.util.Scanner;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.TextMessage;
public class Class1 {
public static void main(String args[]) throws JMSException {
Class2 obj = new Class2();
Scanner s=new Scanner(System.in);
Message m;
TextMessage textMessage = null;
System.out.println("Enter a message");
textMessage.setText(s.next());
m=(Message)textMessage;
obj.onMessage(m);
}
}
Class2.java
import javax.jms.*;
public class Class2 implements MessageListener{
public void onMessage(Message msg) {
System.out.println(msg.toString());
TextMessage textMessage = (TextMessage) msg;
try {
System.out.println(textMessage.getText());
} catch (JMSException e) {
e.printStackTrace();
}
}
}
There are many similar questions to my questions,but there is no clear answer for it!
My tests are failing because they are running once inside suite and once alone. And I need them to run only once inside suite.
This is my suite:
#RunWith(Suite.class)
#Suite.SuiteClasses({Test1.class, Test2.class})
{
.....
}
I am running the test from the command line with command test.
Has anyone found a solution for this?
I use the following setup to run tests with JUnit, parallel, and they run only once:
#RunWith(ParallelSuite.class)
#SuiteClasses({ Test1.class, Test2.class })
public class AllTests {
}
And I have a ParallelSuite.class:
package tests;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.junit.internal.runners.*;
import org.junit.runners.Suite;
import org.junit.runners.model.InitializationError;
import org.junit.runners.model.RunnerBuilder;
import org.junit.runners.model.RunnerScheduler;
public class ParallelSuite extends Suite {
public ParallelSuite(Class<?> klass, RunnerBuilder builder) throws InitializationError {
super(klass, builder);
setScheduler(new RunnerScheduler() {
private final ExecutorService service = Executors.newFixedThreadPool(4);
public void schedule(Runnable childStatement) {
service.submit(childStatement);
}
public void finished() {
try {
service.shutdown();
service.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
} catch (InterruptedException e) {
e.printStackTrace(System.err);
}
}
});
}
}
I have a problem with Idea 14 and JUnit. I can't run #BeforeClass and #AfterClass methods in proper order (before all test and after all test). Every time order is different. I tried to reinstall IDEA, delete all settings but nothing works. Please help. This is example of my test code:
package com.rent.test;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import static org.junit.Assert.*;
import org.junit.Test;
public class testnewTest {
static int num;
static int num1;
#BeforeClass
public static void OnceExecutedBeforeAll() {
System.out.println("#BeforeClass: onceExecutedBeforeAll");
num = 15;
num1 = 16;
}
#AfterClass
public static void after() throws Exception {
System.out.println("End");
}
#Test
public void testLogin() throws Exception {
System.out.println("test");
assertEquals(15, num);
}
#Test
public void testGetOrdersDate() throws Exception {
System.out.println("test2");
assertEquals(16, num1);
}
}
This is output:
test2
#BeforeClass: onceExecutedBeforeAll
test
End
What you're likely observing is the fact that the output is not always going to be synchronous in the terminal. The test themselves are running in the correct sequence.
If they weren't, then you would have failures in test2 given that it would have appeared that your #BeforeClass method fired afterwards.
I've created a java code (swing GUI JFrame form) that call another class function (which is in another project) when the button is pressed, but it needs me to click the button twice in order to successfully return the value from the called function. Is there any solution?
here is my code,
The GUI
package aarib;
import java.awt.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import AlKhalil.ui.Aarib;
public class GUI extends javax.swing.JFrame {
public String Input;
public String Lexems;
public Aarib A;
public GUI() {
initComponents();
A = new Aarib();
jTextField1.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
jLabel2.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
if(jTextField1.getText().isEmpty())
{
jLabel2.setText("No input");
}
else{
Input = jTextField1.getText().toString();
A.inputText= Input;
try {
Lexems = A.LexicalAnalysis();
jLabel2.setText(Lexems);
} catch (Exception ex) {
jLabel2.setText("Error");
Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
and the remote function
package AlKhalil.ui;
import java.util.*;
import java.util.List;
import AlKhalil.token.*;
import AlKhalil.analyse.*;
import AlKhalil.*;
import AlKhalil.result.*;
public class Aarib {
public Analyzer analyzer;
public String myResult="";
public String inputText="";
public Aarib() {
Settings settings = new Settings();
analyzer = new Analyzer();
}
public String LexicalAnalysis() throws Exception {
Thread t = new Thread()
{
public void run()
{
//some code
...
...
...
}
};
t.start();
return myResult;
}
}
Thanks in advance :)
The solution is to wait for the result produced in the Thread t. With your current code you start a concurrent thread and instantly return the attribute myResult. With the second click on your button the myResult is (most times) filled by the thread and returned after starting another concurrent thread doing the calculation.
I suggest considering some kind of Observer-Pattern for your program. Your GUI then should obsever the calculating thread and get notified about a result, which then will be handled.
But as we all cannot see the code executed in the thread and as you wait for the thread to finish, why not simply not use a thread.