I have two questions:
I need to stop child processes through my main process and then start them again after something happened in my main process.have can I do that?
thanks alot.
I'm not entirely sure what you mean in the above post - I suspect they are different questions and the second is related to Glassfish, which I probably can't answer.
However, for the first I can if you mean threads rather than processes - Java has a wait/notify method pair that used in combination allow you to launch n child threads and wait for them all to complete before continuing in the main process. I think this is what you need, rather than stopping the child process from the main process - in concurrent programming this should never be done as you can't guarantee where you're up to in the child process. Have a look at: http://www.javamex.com/tutorials/synchronization_wait_notify_4.shtml
For your first part there are some classes in java.util.concurrent.locks that may help you. Have a look at LockSupport.
The answer to the first part of your question depends on whether the "processes" you are talking about are Process or Thread. But in both cases, there is no good way to cause an uncooperative process to "stop".
In the Process case, the OS may well provide support for suspending processes, but the Java Process APIs don't offer this functionality. So you'd need to resort to non-portable means (e.g. JNI/JNA) to implement this.
In the Thread case, there are methods called suspend and resume, but they should not be used because they are fundamentally unsafe. And the Javadoc says so very clearly!
So if you implement a suspend/resume mechanism, you need your processes to participate / cooperate. In the Thread case, you could implement your suspend / resume mechanism using the low-level synchronization primitives, or using something like the CyclicBarrier class.
Well it was a long time ago and I was really confused probably that forgot to look for the answers. Thanks but there actually a way to take care of the first part and the answer was Java Remote Method Invocation or simpli RMI:
http://en.wikipedia.org/wiki/Java_remote_method_invocation
I am going to remove the second part of my question as I simply don't remember what I was on!
Related
In our Netty application. We are moving all blocking calls in our code to run in a special backgroundThreadGroup.
I'd like to be able to log in production the threadName and the lineNumber of the java code that is about to execute a blocking operation. (i.e. sync File and Network IO)
That way I can grep for the logs looking at places were we might have missed to move our blocking code to the backgroundThreadGroup.
Is there a way to instrument the JVM so that it can tell me that?
Depends on what you mean by a "blocking operation".
In a broad sense, any operation that causes a voluntary context switch is blocking. Trying to do something special about them is absolutely impractical.
For example, in Java, any method containing synchronized is potentially blocking. This includes
ConcurrentHashMap.put
SecureRandom.nextInt
System.getProperty
and many more. I don't think you really want to avoid calling all these methods that look normal at a first glance.
Even simple methods without any synchronization primitives can be blocking. E.g., ByteBuffer.get may result in a page fault and a blocking read on the OS level. Furthermore, as mentioned in comments, there are JVM level blocking operations that are not under your control.
In short, it's impractical if not impossible to find all places in the code where a blocking operation happens.
If, however, you are interested in finding particular method calls that you believe are bad (like Thread.sleep and Socket.read), you can definitely do so. There is a BlockHound project specifically for this purpose. It already has a predefined list of "bad" methods, but can be customized with your own list.
There is a library called BlockHound, that will throw an exception unless you have configured BlockHound to ignore that specific blocking call
This is how you configure BlockHound for Netty: https://github.com/violetagg/netty/blob/625f9d5781ed85bfaca6fa4e826d0d46d70fdbd8/common/src/main/java/io/netty/util/internal/Hidden.java
(You can improve the above code by replacing the last line with builder.nonBlockingThreadPredicate(
p -> p.or(thread -> thread instanceof FastThreadLocalThread)); )
see https://github.com/reactor/BlockHound
see https://blog.frankel.ch/blockhound-how-it-works/
I personally used it to find all blocking call within our Netty based service.
Good Luck
What is the sequence of events that occur between calling Thread.start and Thread.run being called? I ask because mostly out of curiosity, and because I can't seem to trace the native calls to find their implementation, but also to answer some questions I had about what I can expect after starting a Thread.
This question gives a good high level answer, but I'm looking for a more in-depth answer + links to source code is possible.
I'm not sure how every native method of a Java Thread is hooked up, but Java Threads use pthreads in the native layer. https://en.wikipedia.org/wiki/POSIX_Threads
The Thread#start method in Java creates (and starts) a VMThread, which is backed by a pthread. The VMThread is backed by JNI and most of its calls wind up at vm/Thread.c (e.g. https://android.googlesource.com/platform/dalvik/+/eclair-release/vm/Thread.c).
E.g. the VMThread#create calls JNI method Dalvik_java_lang_VMThread_create and that calls the dvmCreateInterpThread function in vm/Thread.c
I hope this is a good start for you to start Googling around what exactly happens between Thread creation and its start.
Streets of Boston pointed me in the right direction, where I found https://android.googlesource.com/platform/art/+/marshmallow-release/runtime/ . I will update this answer as soon as I get a chance to read through the code and grok it.
Due to the deprecated nature of the Thread stop() and suspend() methods, I have become accustomed to implementing a standard cooperative suspension method using the well tested wait/notify methodology. Unfortunately my current project includes an initialisation thread that duplicates a recursive directory structure via a single call to an external method that doesn't return until it has finished and does not implement any kind of wait/notify cooperation.
I'm curious to know what other programmers are tempted to do in this situation, save perhaps reimplementing the external method, as I'm quite tempted to use the Thread.suspend() method and hope the file operations contained within the external method don't hold on to anything critical whilst suspended.
Hmmm...this is a tricky one.
Well do not even try stop() or suspend(). They were deprecated and there are reasons for rightly so. Ideally you shouldn't even be trying wait or notify when you have so many excellent libraries available in java.util.concurrent package.
In your case, you should check the documentation of the external method you are calling to know about the shutdown policy of that library. If none is mentioned then you can probably try interrupting. interrupt will surely work if the external method call makes some blocking calls. Other than it, I see no other way.
Using suspend will only lead to instability rather than aiding anything. Not using it will take more computational power but will be stable atleast.
I was use C++ signals
sigaction
struct sigaction sigact;
and set all attributes to use signals
now I want to use it in Java what's the equivalent in java
to the include "signal.h"
I have two threads:
one run from the beginning of the program
and the other run at the signal Alarm
I was implement the functionality in C++ using Signals as shown and now I want to implement it using java
Edited to put my Goal:
actually my Goal to run the second Thread When the signal arrives from the first thread
Thus sounds like a typical "XY-Problem".
In plain Java you have no access to OS-signal. They are platform specific and Java strifes to be platform agnostic. Also: calling Java from a signal handler with JNI might be "fun" (as explained in Dwarf Fortress).
So you have to go back to the drawing board and think about what is the problem you want to solve and stop thinking about how to solve it with signals.
That said: if you insist on signals and are not afraid to use internal stuff which might change on a whim: Take a look at sun.misc.Signal.
EDIT Now the question made it clear, that the signalling takes place within one JVM. For this signals are definitely the wrong thing in Java.
So the simplest solution is to create and start the second thread directly from within the first thread. No signalling required.
The next best solution is to code a "rendezvous point" using Object.wait() in the second thread (using any object instance but the Thread itself) and Object.notify() or notifyAll() from the first thread. Searching for these terms in a Java tutorial will bring up enough examples.
How to determine part of what Java code needs to be synchronized? Are there any unit testing technics?
Samples of code are welcome.
Code needs to be synchronized when there might be multiple threads that work on the same data at the same time.
Whether code needs to be synchronized is not something that you can discover by unit testing. You must think and design your program carefully when your program is multi-threaded to avoid issues.
A good book on concurrent programming in Java is Java Concurrency in Practice.
If I understand your question correctly, you want to know what you have to synchronise. Unfortunately there isn't a boiler plate code to provide that shows you what to synchronise - you should take a look at methods and instance variables that can be accessed by multiple threads at the same time. If there aren't such, you usually don't need to worry about synchronisation too much.
This is a good source for some general information:
http://weblogs.java.net/blog/caroljmcdonald/archive/2009/09/17/some-java-concurrency-tips
When you are in a multithreaded environment in Java and you want to do many things in parallel, I would suggest using an approach which uses the concurrent Queue (like BlockingQueue or ConcurrentLinkedQueue) implementations and a simple Runnable that has a reference to the queue and pulls 'messages' of the queue. Use an ExecutorService to manage the tasks. Sort of a (very simplified) Actor type of model.
So choose not to share state as much as possible, because if you do, you need to synchronize, or use a data structure that supports concurrent access like the ConcurrentHashMap.
There's no substitute for thinking about the issues surrounding your code (as the other answers here illustrate). Once you've done that, though, it's worth running FindBugs over your code. It will identify where you've applied synchronisation inconsistently, and is a great help in tracking otherwise hard-to-find bugs.
Lot of nice answers here:
Java synchronization and performance in an aspect
A nice analysis of your problem is available here:
http://portal.acm.org/citation.cfm?id=1370093&dl=GUIDE&coll=GUIDE&CFID=57662261&CFTOKEN=95754288 (require access to ACM portal)
Yes, all these folks are right - no alternative for thinking. But here is the thumb rule..
1. If its a read - perhaps you do not need synchronization
2. If its a 'write' - you should consider it...