Java wait for all threads before terminating - java

I am trying to test an application with Jmeter. The application uses a proprietary library that creates multiple threads. In JMeter I have created a AbstractJavaSamplerClient, which does not seem to wait for all the other threads that might be generated in the application. Instead it just runs its own default method and closes leaving the other threads running in the background - since I am connecting to a server in the application, I can see through the server logs that it is still connected. Since I don't have the references to the other threads as they are instantiated through the proprietary library, I can't use the common solutions of wait() or join().How can I get the main thread to wait for all the threads (none of which I have references too)?

Put all work with the library in a separate thread in a specially created thread group. The library will create new threads in that thread group and its descendants. List all threads of that group recursively with group.enumerate(new Thread[group.activeCount()*2],true). Then you can join() them all.

You can start with
Thread.getAllStackTraces().keySet();
which will give you a set of all running threads. This will include those you are interested in and all the other threads, including those internal to the JVM.
Hopefully you'll be able to filter out the ones you are interested in by name, and then you can join() them.

Related

Execute sequential from two instance of the same Java application

I have a Java application named 'X'. In Windows environment, at a given point of time there might be more than one instance of the application.
I want a common piece of code to be executed sequentially in the Application 'X' no matter how many instances of the application are running. Is that something possible and can be achieved ? Any suggestions will help.
Example :- I have a class named Executor where a method execute() will be invoked. Assuming there might be two or more instances of the application at any given point of time, how can i have the method execute() run sequential from different instances ?
Is there something like a lock which can be accessed from two instances and see if the lock is currently active or not ? Any help ?
I think what you are looking for is a distributed lock (i.e. a lock which is visible and controllable from many processes). There are quite a few 3rd party libraries that have been developed with this in mind and some of them are discussed on this page.
Distributed Lock Service
There are also some other suggestions in this post which use a file on the underlying system as a synchornization mechanism.
Cross process synchronization in Java
To my knowledge, you cannot do this that easily. You could implement TCP calls between processes... but well I wouldn't advice it.
You should better create an external process in charge of executing the task and a request all the the tasks to execute by sending a message to a JMS queue that your executor process would consume.
...Or maybe you don't really need to have several processes running in the same time but what you might require is just an application that would have several threads performing things in the same time and having one thread dedicated to the Executor. That way, synchronizing the execute()method (or the whole Executor) would be enough and spare you some time.
You cannot achieve this with Executors or anything like that because Java virtual machines will be separate.
If you really need to synchronize between multiple independent instances, one of the approaches would be to dedicate internal port and implement a simple internal server within the application. Look into ServerSocket or RMI is full blown solution if you need extensive communications. First instance binds to the dedicated application port and becomes the master node. All later instances find the application port taken but then can use it to make HTTP (or just TCP/IP) call to the master node reporting about activities they need to do.
As you only need to execute some action sequentially, any slave node may ask master to do this rather than executing itself.
A potential problem with this approach is that if the user shuts down the master node, it may be complex to implement approach how another running node could take its place. If only one node is active at any time (receiving input from the user), it may take a role of the master node after discovering that the master is not responding and then the port is not occupied.
A distributed queue, could be used for this type of load-balancing. You put one or more 'request messages' into a queue, and the next available consumer application picks it up and processes it. Each such request message could describe your task to process.
This type of queue could be implemented as JMS queue (e.g. using ActiveMQ http://activemq.apache.org/), or on Windows there is also MSMQ: https://msdn.microsoft.com/en-us/library/ms711472(v=vs.85).aspx.
If performance is an issue and you can have C/C++ develepors, also the 'shared memory queue' could be interesting: shmemq API

Suspending and serializing a running thread

Does anybody know a mechanism that can capture the state of a running thread and serialize that for further resume?
Is there anything available for the JVM?
How about pthreads?
My main goal is to be able to migrate a running thread to a remote machine.
With the cooperation of that thread, you can do it by any mechanism that thread supports. Without the cooperation of that thread, it is impossible. What happens if that thread holds a lock that your serialize code needs?
What happens if you migrate a running thread that is currently using some kernel resource such as a pipe. Will you migrate that resource?
The right solution to your problem may be to have the thread support a migration mechanism. How you do that depends on precisely what that thread is doing. You'll get answers that are more likely to help you solve your actual problem if you explain precisely what is.
The answer to this is really going to depend on what constitutes the state of the running thread.
If the state is local thread data which allows for the thread state to be copied and saved and then inserted back into a new thread, then the mechanism is basically to just save the state with some kind of a serializable object which is then used to create a new thread with the saved state and to then begin it running.
However if the thread state depends on external objects or entities, the problem is much tougher. For instance if you have a thread which is acting as a server using TCP and you want to save its state then restart it later, the socket is going to change and the client which was accessing the server thread will know that the server thread stopped communicating for a while.
This means that for any external entities that are depending on the thread, will need to know that the thread is being saved and frozen, they will need to have something that allows them to either fall over to an alternative or to save and freeze themselves, and there will need to be some kind of protocol so that the restarted thread can let the other entities know that it is back in business and its current state.
Also if the thread is depending on some external entities then those entities must be able to deal with the thread being frozen. There may need to be some kind of a mechanism in place so that the thread can release various resources, whose states are saved, and then when restarted, be able to reclaim those resources or comparable resources and then reset those resources to the saved state.
If you want to move a running JVM from one machine to another, you will most likely not do it by yourself but instead use the live migration functionality of a VM manager.
The VM managers will move entire virtual machines from one physical machine to another without stopping the virtual machine or processes, but it's quite a bit higher level than serializing/deserializing a thread. Since a thread may use resources that are local to the operating system such as file systems or sockets, the whole operating system needs to follow the thread to the other physical machine.
I'm not aware of any way that you can send a thread, per se. However, you could use a pattern such as the memento pattern to save the state of your thread.
See these references before continuing so you know the terminology:
Memento pattern, oodesign.com
Memento pattern, Wikipedia
Basically, you'll have this:
Design a job (thread) that can run with any starting state, including a state from mid-execution.
When it needs migrated, get the state of that thread.
In Java, you could use ThreadLocal variables to store the thread state.
Serialize that state to the other machine.
Use the state to start a new thread with the state you deserialized.
This is a better approach then actually migrating a thread, its state, stack, etc. since you can pick and choose what absolutely needs to be moved instead of moving everything no matter what.

What are those java threads starting with "pool"?

I have a problem with a Tomcat server that is unable to shutdown gracefully. I have taken a thread dump after I issued the shutdown command, and it looks like this:
http://pastebin.com/7SW4wZN9
The thread which I believe is the "suspect" that does not allow the VM to shut down is the one named "pool-4-thread-1". The rest of them are either daemon threads or internal VM threads. While trying to find out what this thread is for, I noticed that there are other java programs out there that create threads with similar names (For example, JVisualVM creates such threads).
So I'm wondering if someone else knows what this thread is and how it can be created.
These threads are probably created by an ExecutorService that you created in your code somewhere (directly or indirectly through a library) and that needs to be shutdown (for example in a ServletContextListener).

Java RMI specification on thread usage: "..may or may not execute in a separate thread"

I might have a problem with my application. There is a client running multiple threads which might execute rather time consuming calls to the server over Java RMI. Of course a time consuming call from one client should not block everyone else.
I tested it, and it works on my machine. So I created two Threads on the client and a dummy call on the server. On startup the clients both call the dummy method which just does a huge number of sysout. It can be seen that these calls are handled in parallel, without blocking.
I was very satisfied until a collegue indicated that the RMI spec does not necessarily guarantee that behavior.
And really a text on the hp of the university of Lancaster states that
“A method dispatched by the RMI runtime to a remote object
implementation (a server) may or may not execute in a separate thread.
Calls originating from different clients Virtual Machines will execute
in different threads. From the same client machine it is not
guaranteed that each method will run in a separate thread” [1]
What can I do about that? Is it possible that it just won't work in practice?
in theory, yes, you may have to worry about this. in reality, all mainstream rmi impls multi-thread all incoming calls, so unless you are running against some obscure jvm, you don't have anything to worry about.
What that wording means is that you can't assume it will all execute in the same thread. So you are responsible for any required synchronization.
Based on my testing on a Mac laptop, every single client request received in parallel seems to be executed on a separate thread (I tried upto a thousand threads without any issues. I don't know if there is an upper bound though. My guess is that the max no. of threads will be limited only by memory).
These threads then hang around for some time (a minute or two), in case they can service more clients. If they are unused for some time, they get GC'ed.
Note that I used Thread.sleep() on the server to hold up every request, hence none of the threads could finish the task and move on to another request.
The point is that, if required, the JVM can even allocate a separate thread for each client request. If work is done and threads are free, it could reuse existing threads without creating new ones.
I don't see a situation where any client request would be stuck waiting due to RMI constraints. No matter how many threads on the server are "busy" processing existing requests, new client requests will be received.

What is the best practice for starting threads or loading shared resources in a Java application server outside of Servlet invocation?

Abstract Question
What is the best way to load resources into memory that will be shared across servlets in a Java application server?
What I am actually doing
I want to create a daemon thread that monitors a queue. This queue could have objects added to it from servlet threads. The thread would wait until a set period of time and check the queue to see if it had items in it, if so then it would process them and remove them. This thread would need to be started somewhere at sometime. I was thinking that a servlet with only the init method implemented would work for this task or is there a better place to put startup code like this in an application server? Am I approaching the problem all wonky?
Updates
I found this question and the accepted answer was to use the LifeCycle Listener. Is this a portable way of doing things or is my code going to be tied to a single application server. A bit more investigation led me to a find a few posts on message boards saying that I could do this in a ServletContextListener implementation.
I usually start these kinds of worker threads indirectly from a Servlet using the method you describe (usually they exist inside some other object that does the queue extraction and controls the processing).
For pulling objects off the thread, you don't need to do it based on time, you could have your thread wait() on the queue object and when an object is put onto the queue by some other thread, that thread would call notify() on the queue to release the watching 'worker' thread.
Google 'java worker thread wait notify' for many examples.

Categories