Other method in thread executing before run method in java - java

In my program I am calling the thread to do some job but the other method of thread class executes before the run method.
public class Verify extends JFrame implements Runnable
{
long Local_cid;
String local_path;
static boolean isIntialised=false;
JProgressBar bar;
final static ArrayList<Long> ContactList=new ArrayList<>();
final static ArrayList<Long> Scanned=new ArrayList<>();
static boolean flag=true;
static boolean Duplicate_flag=true;
boolean[] flags=new boolean[6];
public Verify(long ID,String path)
{
Local_cid=ID;
local_path=path;
}
public boolean[] Return_Flag()
{
System.err.println("Verify Id");
return flags;
}
public void dispose_Frame()
{
System.err.println("Executing First");
dispose();
}
#Override
public void run()
{
System.err.println("This should Executed First");
}
}
When I call this thread via start call the output is as follows:
Verify Id
Executing First
This should Executed First

You should follow the Java coding standard style guides, it will make it much easier for people to read.
There is nothing in the code you have posted that calls Return_Flag() so you must be calling it somewhere else - probably from the code that creates the thread in the first place.
Run is only called once the thread is started, and other threads are still running at the same time and can call whatever methods they like in whatever order they like...

I'm 100% sure that you are calling those methods somewhere in your code before actually starting the thread. Just look more careful and you will find it.

Related

Force method to finish before continuing

I'm working on some sensitive LWJGL code and need to make sure that I create my display, and therefore GL context before executing any other code.
To give a clear example of my current predicament, take the following:
public static void main(String[] args) {
GLDisplay display = new GLDisplay();
display.start();
GLShader shader = new StaticShader();
}
The beginning of my GL creation happens in display.start(), where a separate thread is created, and within the separate thread, my Display is created.
Except this is where the problem lies, I have it in a separate thread. So then my program goes on and starts prematurely executing the new StaticShader() which calls even more GL code, breaking the program. (Can't execute before display is created).
What I'm trying to do, is achieve two threads simultaneously which I already have, but make sure that start() method is called completely before anything else is.
Here is how the start method works:
public synchronized void start() {
Threader.createThread(this, "GLDisplay");
}
#Override // public class GLDisplay extends Runnable
public void run() {
// GL code goes here.
}
And here is Threader:
public static void createThread(Runnable behaviour, String name) {
new Thread(behaviour, name + behaviour.hashCode()).start();
}
Now you may notice the synchronized keyword in the start method, well thats just one attempt I've had to no avail. I've also tried the following (which I actually grabbed from another StackOverflow answer):
#Override
public void run() {
synchronized(this) {
// GL code
}
}
I've checked other StackOverflow answers but either don't understand them or don't help me in my case. With the first code block I give in the main method, that is how I want my code to look to the person using it. I'm trying to put the thread-creation inside GlDisplay to hide it.
Any ideas?
Edit:
I can't simply wait for GLDisplay to close either (with Thread.join()) because there lies a while-loop that updates the display for the entirety of the program.
This is the entire reason I multi-threaded it. To allow this forever-ending loop to run while I do other things in the program. By closing the thread, I close the loop, cleanup the display and free the GL context from memory, once again making the shader code fail for lack of an existing context.
You can use java.util.concurrent.CountDownLatch to achieve it which aids in making a thread(s) wait till the operations on other threads is complete. Please see the reference on on what and how to use it.
Example:
public static void main(String[] args) {
CountDownLatch cdl = new CountDownLatch(1);
// pass the CountDownLatch into display
GLDisplay display = new GLDisplay(cdl);
display.start();
// wait for the latch to have been counted down in the disp thread
try
{
cdl.await();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
GLShader shader = new StaticShader();
}
In your GLDisplay thread, call the countDown method of CountDownLatch
I might be misunderstanding something, but try the following:
public static void createThread(Runnable behaviour, String name) {
Thread t = new Thread(behaviour, name + behaviour.hashCode()).start();
t.join();
}
By calling join() the program should wait for the thread to complete.
Well I remember now that I can't have GL code against two separate threads anyway, but thats besides the point.
I don't actually need to use any thread-lock classes or anything, but rather can just do something as simple as this:
private Boolean threadLock = true;
public void start() {
Threader.createThread(this, "GLDisplay");
while (true) {
synchronized(threadLock) {
if (!threadLock) break;
}
}
}
#Runnable
public void run() {
// Do GL code.
synchronized(threadLock) { threadLock = false; }
// Do the rest of whatever I'm doing.
}
When the threadlock is reached in the second thread and is released, the first thread continues doing it's activity. It's that simple!

Function as a function parameter in Java

I have a class, with Thread as superclass, I pass a function as a parameter and this class just execute that function. This class uses it to create threads, so I can execute any function in a thread without having to create a different class.
public class ThreadEjecucionLambda extends Thread {
Runnable funcion;
public ThreadEjecucionLambda(Runnable funcion)
{
this.funcion=funcion;
}
public void run()
{
funcion.run();
}
}
Now, to create several threads of a same method I use a 'for' block, for example:
for(Computer computer: Persistencia.getListComputers())
{
ThreadEjecucionLambda hilolambda=new ThreadEjecucionLambda(()->logica.EnciendeMonitor(computer.getNombrePC()));
hilolambda.run();
}
What I want to achieve is to generalice the previous 'for' so that I can execute a method,to which I will pass ,as parameters, (following the example) a list of 'Computers' and a function. This method will execute the 'for' block and will create a thread for each 'Computer, so I will pass as a parameter the previous function to the thread and that function will have, as a parameter, the 'Computer'.
What I want to get is something like this (WARNING: IT'S WRONG):
public void EjecutaHilosLambdaSegundo(ArrayList<Computer> listapcs,Runnable funcion)
{
for(Computer computer: listapcs)
{
ThreadEjecucionLambda hilolambda=new ThreadEjecucionLambda(funcion(computer));
hilolambda.run();
}
}
I hope I have explained myself well because it's a very confusing problem.
Thread already has a constructor taking a Runnable as argument, and executing it when you start it, so your subclass is useless and confusing. Not only that, but you never actually start any thread. So you could just run the Runnable directly, without creating any Thread or ThreadEjecucionLambda.
If I understand correctly, you want to execute the same function, taking a Computer as argument, on a list of Computers.
You don't need a Thread to do that. All you need is a Consumer<Computer>:
public consumeAllComputers(List<Computer> computers, Consumer<? super Computer> function) {
computers.forEach(function);
}
But, as you see, this method is useless, since you could just call forEach on the List directly.
So, suppose you want to print the name of each computer in a list, you would use
computers.forEach(computer -> System.out.println(computer.getName());
Don't reinvent the wheel!
For the synchronous solution, look at #JB Nizet answer.
Asynchronous solution
First, your ThreadEjecucionLambda class is not creating thread, because to start a new thread, you need to call the start() method of Thread.
public class ThreadEjecucionLambda extends Thread {
Runnable funcion;
public ThreadEjecucionLambda(Runnable funcion)
{
super(funcion);
this.funcion = funcion;
}
public void run()
{
super.start();
}
}
Second, this class is meaningless! Thread is already working that way.
Third, Runnable as is does not accept argument. What you actually need to do is create your own Runnable that takes a Computer as an argument.
public class MyRunnable implements Runnable {
Computer computer;
public MyRunnable(Computer computer)
{
this.computer = computer;
}
#Override
public void run()
{
// Do what you want cause a pirate is-
// Erm do what you want with your computer object
}
}
And then use it for your above method.
public void EjecutaHilosLambdaSegundo(ArrayList<Computer> listapcs, MyRunnable myRunnable)
{
for(Computer computer: listapcs)
{
Thread myThread = new Thread(myRunnable);
myThread.start();
}
}

Calling a method of a class which extends Thread, from another class

I know this is a bit naive question but I want to understand the basic working principle behind multi-threading in java. Consider the following code and say A is executed in Main thread and it starts execution of another worker thread ,defined in class B. I want to know that can B.func1 called from A and run method of B, be executed in parallel or not?
public class A {
public static void main(String[] args) {
B obj = new B();
obj.start();
obj.func1();
}
}
public class B extends Thread {
public B() {
//constructor
}
public void run() {
while(true) {
//do somethings
}
}
public void func1() {
//do someotherthings
}
}
There is no magic behind a method call. If you call method from a thread, it is called in exactly the same thread. So since obj.func1() is called from main, it will be run in the main thread. It doesn't matter which class it belongs to or whether or not it extends Thread.
The new thread starts by executing run. Everything called from run and so on will be executed in parallel to main.
It's important to understand the difference between a thread and a Thread.
A thread is an independent execution of your code. Often when we talk about how some method or another works we say things like, "It tests the variable x, and if x is less than zero it calls the foobar method..."
Ok, but what is the "it" in that sentence? It is not the method. Methods don't do anything. A method is just a list of instructions, like the list of chores that somebody left for their housemate to perform. The list doesn't do the chores, it's the housemate that does the work (or so we might hope).
The "it" is a thread. Threads are entities in the operating system that execute methods (i.e., they do the chores).
A Thread, on the other hand, is a Java object that your program can use to create and manage new threads. Your program creates a new Thread object by doing:
thread t = new Thread(...);
[Oops! See what I just did? It's not your program, that does the work, it's your program's main thread, or maybe some other thread in your program. It's an easy thing to forget!]
Anyway, it subsequently creates the new thread by calling t.start();
Once you understand all that, then Sergey Tachenov's answer becomes obvious: Calling the methods of a Thread object really is no different from calling methods of any other kind of object.
There are multiple issues with your code. I have corrected them and added one more statement to print Thread Name in func1().
Working code:
public class A {
public static void main(String args[]){
B obj = new B();
obj.start();
obj.func1();
}
}
class B extends Thread{
public B (){
//constructor
}
public void run(){
while(true){
//do somethings
}
}
public void func1 (){
//do someotherthings
System.out.println("Thread name="+Thread.currentThread().getName());
}
}
output:
Thread name=main
Since you are directly calling func1() from main method (A.java) , you will get Thread name = main in output.
If you add same print statement run() method, you will get output as : Thread name=Thread-0

how to unit test this threaded code

I have a class that normally runs in a thread that processes data forever until another thread invokes stop() on it. The problem I have is that the unit test gets stuck in the main loop since the test is single threaded and I want to keep it that way. How can I unit test this without polluting the code? this class is part of a critical system and needs to be as simple and efficient as possible so I want to avoid unit testing hacks in the code
public class MyClass implements Runnable {
boolean running;
public void run() {
//foo is injected from the outside
foo.start();
work();
foo.end();
}
public void work() {
running = true;
while(running) { //main loop
bar.process(); //bar is injected from the outside
}
}
public void stop() {
running = false;
}
}
Basically what I'm doing in the test is mocking out foo and bar and I call run() from the unit test, where later I verify in the bar mock whether process was actually called. I also verify that in the foo mock start() and end() got called. The problem is that because I really want to keep the test single threaded, the test thread gets stuck forever in the while(running) loop.
Some things I have tried and don't like
add some VM property to trigger a break at the end of the iteration of the main loop. The problem with this is that as mentioned, this code is very critical and I want to keep the code clear of unit-testing clutter. I don't want production code evaluating in every iteration some VM property that I only use at development time
use the bar mock to invoke stop() on its call of process(). Mockito doesn't like the fact that I call another class' method and throws an exception
externalize the control of the mainloop. so instead of checking a boolean in the while, I call a method that returns whether to continue or not. And this loop-control object can be injected from the outside, that way in the unit test i can make the control method return true and then false to get a single iteration out of the loop. This complexifies the code quite a bit and makes it unnatural and harder to read plus it only would make any sense in a unit test context
Are there any other suggestions or common patterns to test Runnables, or maybe a better way to write my code so that testing it is easier?
I suggest making a change which would both make your code more by-the-book and allow breaking out in a single thread:
while (!Thread.currentThread().isInterrupted() && running) {
bar.process();
}
You can call Thread.currentThread().interrupt() before you run this code; the thread's interrupted flag will be set and the method isInterrupted() will return true.
This is more by-the-book because it makes your main loop participate in Java's interruption mechanism.
Create an interface for the class of bar that only contains the method process. Your MyClass seems generic enough so that this would be OK. Then, instead of mocking bar, create your own implementation dummy (or mock, whatever you like to call it). This will then call the stop method and your process method is only called once. You can check whether BarMock.process was called with an assertion using its isCalled method. Also, I would suggest an isRunning method for your MyClass so that you can check whether it was stopped.
public interface Processable {
public void process();
}
public class BarMock implements Processable {
private MyClass clazz;
private boolean called;
public BarMock(MyClass clazz) {
this.clazz = clazz;
called = false;
}
#Override
public void process() {
// you can assertTrue(clazz.isRunning()) here, if required
called = true;
clazz.stop();
}
public boolean isCalled() {
return called;
}
}
public class MyClass implements Runnable {
boolean running;
public void run() {
// foo is injected from the outside
foo.start();
work();
foo.end();
}
public void work() {
running = true;
while (running) { // main loop
bar.process(); // bar is injected from the outside
}
}
public void stop() {
running = false;
}
public boolean isRunning() {
return running;
}
}
I think this method has three advantages over the one suggested by William F. Jameson, but also disadvantages:
Advantages:
You can test whether your process method was actually called
You don't have to add code that you never use during the actual program run
You can test whether the stop method really stops
Disadvantages:
You have to introduce an interface
Need to test BarMock class, too
That said, I'd still prefer introducting the interface, since it doesn't pollute your code too much and therefore is a small price to pay.

Java: Modify & access variable initialized in constructor

I have a class.
I initialize a variable in the constructor of that class.
I call a method that contains a while loop and increments the variable each time through.
I wrote a test to check the value of the variable after the method has been called (and goes through the while loop one time).
public class ThreadGenerator implements Runnable {
private int requests;
private int limit;
public ThreadGenerator() {
requests = 0;
}
public void setRequestLimit(int anyLimit) {
this.limit = anyLimit;
}
public void generateThread() {
new Thread(this).start();
}
public void run() {
while(requests < limit) {
try {
// do some stuff
requests++;
// close some stuff
} catch (IOException e) {
e.printStackTrace();
}
}
}
public int getRequests() {
return requests; // calling this method from my tests always returns 0
}
In my test, when I create a new instance of this class, then call this method on that class, it runs correctly and it increments the request counter correctly. I've tried several print statements to make sure of that. But if I call getRequests on my ThreadGenerator object in my test, it will return 0, the amount it was initialized with.
My test code:
ThreadGenerator threadGenerator = new ThreadGenerator();
threadGenerator.setRequestLimit(1);
threadGenerator.generateThread();
assertEquals(threadGenerator.getRequests(), 1);
How can I modify this variable I initialized in the constructor and gain access to it in my test suite?
Bear in mind that just because you ask Java to create a new thread with a Runnable, doesn't mean that the run() method will be called immediately. It's likely the case that the assertEquals is happening before the run happens the first time.
You may want to return the thread and call join in the test on the generated thread, which will ensure that the Thread runs until it dies, possibly with a short timeout.
/* in the system under test */
#VisibleForTesting Thread generateAndReturnThread() {
Thread thread = new Thread(this);
thread.start();
return thread;
}
public void generateThread() {
generateAndReturnThread();
}
/* in the test */
#Test public void yourTest() {
ThreadGenerator threadGenerator = new ThreadGenerator();
threadGenerator.setRequestLimit(1);
// wait up to a second for thread to complete
threadGenerator.generateThreadAndReturn().join(1000);
assertEquals(threadGenerator.getRequests(), 1);
}
Side note: Consider AtomicInteger for your requests class, if multiple threads might modify requests. This will help prevent two different threads from both modifying requests and overwriting one another.
In addition to above answer, consider declaring the variable as volatile, so that you can actually get the latest value after another thread incremented the variable.

Categories