Does method.invoke create a new thread in java? - java

I am calling a method using reflection in Java using the method.invoke function. Does that method.invoke create a new thread or it will run with the current thread?

No, it does not create a new thread.
The JavaDocs don't mention anything about multithreading or being asynchronous, and this is typically a very strong indication that it will be executed in the current thread.
Constructs that may use other threads are typically quite explicit about not making any guarantees as to which thread will execute the code - see the documentation for Executors or Stream

Related

Advantage of directExecutor

As far as I understand Guava's MoreExecutors.directExecutor() creates an Executor which will executes the runnable before the execute method call could return.
What are the usecases that need direct executor ? Can't the caller directly call runnable.run() directly instead of the extra level of indirection by creating an executor and submitting the runnable to this executor ? May be I am missing the real purpose of it's existence. I wanted to understand in what case is this useful.
There are few places which require both Runnable and Executor.
One of then is for example ListenableFuture and its addListener method. The only way how to execute listener immediately within the same thread is to provide direct executor.
MoreExecutors.directExecutor() is useful when you call an API that requires you to specify an executor to execute the task (e.g. Futures.transform(), listenableFuture.addListener(), etc).
Note that when you use directExecutor() with these APIs, the runnable may be run on one of these two threads:
The thread that completes the previous future
The thread that calls transform()/addListener()
This uncertainty could cause unexpected issues. So be careful when you use directExecutor().

What does the JVM do in background before calling Thread.run()? OR Why Thread.run() isn't exposed to the user?

A thread's run method is invoked by JVM when Thread.start() is called by the programmer.
What does the JVM do in background before calling Thread.run()?
Why is Thread.run() not exposed to the user?
What does the JVM do in background before calling Thread.run()?
It does the JVM work to manage the thread object (allocate stack space, thread-locals, ...) and the per-architecture native work of forking and scheduling a new thread/process/clone or whatever the architecture uses to implement threads.
Why is Thread.run() not exposed to the user?
I assume you are talking about "exposed" in terms of the stack frame. Just like the the static main method, there obviously are call frames above the user code that aren't exposed to the user because they aren't useful and would be confusing. I'd say the same thing about the Thread.run() method. It will show up in the call stack if you extend Thread and override run() but won't if you are passing in a target Runnable.
I have a lot of details about this in this answer:
How does Java run() method work?
What does the JVM do in background before calling Thread.run()?
When you call start() it starts a thread associated with the Thread object which calls the run() method of the thread.
Note: All the work of creating, starting and scheduling threads is done by the OS. Java just makes the right system calls. It is not JVM code which does the real work.
OR Why Thread.run() isn't exposed to the user?
It is exposed. It is public and you can call it like any other method.
When you do the start by thread.run(), you are running this as a normal process and not really using it as a thread. It will be joined with the main thread. With thread.start(), the JVM allocates the separate thread which will not be joined with the main thread.
When you call start(), the Thread class actually creates the new JVM thread (which is separate from the calling thread), and calls run() from that new thread.
Creating new JVM threads, so that application code can have multiple threads of running code, is a low-level JVM operation.
If run() were exposed to the user, and it were called instead of start(), then the code in run() will be executed serially in the single, calling thread.
someThread.start() calls a native method which tells the JVM to create a new thread. The gory details for hotspot, for example, can be found in the source code.
In substance, start() asks the os to create a new thread then calls the Thread#run() method in that newly created thread.
You're starting to delve into the implementation of the JVM itself, as launching of a new thread requires interacting with the operating system. Here's a pretty good mid-level explanation of threads in the JVM.

Need for thread safety when using a SinglethreadExecutor [duplicate]

This question already has answers here:
Is ExecutorService (specifically ThreadPoolExecutor) thread safe?
(6 answers)
Closed 4 years ago.
I was working on a Java EE app that took in user requests from a UI and then keyed off a lon workflow asynchronously for each of these requests using ExecutorService (SinglethreadExecutor). Now since i was using a SinglethreadExecutor and because there was genuine need for the requests to be served one at a time, i did not feel the need for thread safety.
Is my understanding correct ?
Recently i had asked a question Issue when executing asynchronous tasks using ExecutorService and the solution to this question was that i make my code thread safe.
I'm looking if any shared resources that I'm using in my code is causing the need for this thread safety but would just like to be sure that my understanding of
the scenario is correct.
FYI, I have implemented my ExecutorService in a servlet as mentioned in Running a background Java program in Tomcat
Your requests will be passed to a different thread to be executed. Even if this thread doesn't access shared data structures, the passing of the request to the thread and the returning of the result need to be properly synchronized.
If you use one of the submit or invoke methods which use a Future object for returning the results, you can assume that the appropriate synchronization is performed. The javadoc for ExecutorService says this:
Memory consistency effects: Actions in a thread prior to the submission of a Runnable or Callable task to an ExecutorService happen-before any actions taken by that task, which in turn happen-before the result is retrieved via Future.get().
In short, if the requests / tasks don't use shared data structures and you use the interface methods provided, then you should be OK.
There are two things that you need to consider when you need to make something "thread safe": When does a thread make data visible to anyone else? When does a thread try to read shared data?
Imagine this situation: Thread A gets the request. It works a bit on it. Then it calls a method foo() that gets the request as a parameter. foo() starts a new thread. The thread puts the reference to the request as a private, non-final field.
In hardware, thread A has copied the request into the L1 cache of the CPU core on which it runs. Since there is no synchronization between the two threads, A has no idea that some other thread might want to read the modified request, so it never flushes the cache (or it does it too late).
This means that thread B will get a stale request object. It won't see any changes made by thread A. As you can imagine, this usually works: If A doesn't change the request, B works. It breaks as soon as you change the code of A and you have a "but it worked yesterday!" situation.
To fix this, you must tell A to flush its caches even if the current version of your code works without it. There are several ways to do it; Stephen C described one. Two other ways:
You can synchronize foo() - A thread must flush when it enters a synchronized block.
Make the request a final field of B - Object graphs referenced via final fields must be completely flushed at the time the type construction has completed (where type == the class which contains the final field).

difference between thread.start() and executor.submit(thread)

i am facing a problem regarding the thread. I am having a class which implements runnable, and i can use thread.start() method on that class.
My question is i have one more class java.util.concurrent.ExecutorService in which i can call executor.submit(thread)..
can anyone please tell me what is the difference between thread.start() and executor.submit(thread)...
The executor.submit method takes a Runnable, not a Thread. The point of executorServices is that they take control over creating and pooling threads so the code calling them doesn't have to.
You should not submit a thread to an executor. First it is simply a waste because the only method that will be called on it is run(), and you just need a Runnable and don't need a Thread for that.
Secondary, while this issue is solved in the latest JDK, it used to be the case that a memory leak problem occurs if you create a lot of Thread objects and don't call .start() on them. Basically creating a Thread objects allocates some memory that can only be reclaimed after .start() was called. Therefore, doing executor.submit(thread) is potentially hazardous in earlier JDKs (I think it was only solved in JDK6 or so).
Coming back to your question, executor.submit(thread) is not valid.. It is simply wrong, because an executor uses its own thread to execute the runnable. That's after all the whole point of using a executor. You want to separate task (invocation) and execution. Only if you want to supply the executor (thread), you should be using Thread, but it is rare that you need to do so. Generally it is advisable to implement a Runnable and use executors to execute it, rather than dealing with Thread yourself.

Calling a method on thread termination

I am writing a java program which tracks as threads are created in a program and is then supposed to perform some work as each Thread terminates.
I dont see any 'thread termination hooks' out there in the javadoc.
Currently the only way I can think of to achieve my requirement is to hold on to the thread objects and query its 'state' at repeated intervals.
Is there any better way to do this?
Edit:
I cannot wrap the runnable or modify the runnable in any way.
My code uses runtime instrumentation and just detects that a thread is created and gets a reference to the Thread object.
The runnable is already running at this point.
You can use the join() method.
EDIT
If your main thread must not be blocked until threads are not terminated, you can create a sub main thread which will call the threads, then wait for them with join() method.
I see four possible methods.
Use your own Thread subclass with an
overridden run() method. Add a
finally block for thread
termination.
Use a Runnable with
similar decoration, perhaps as a
wrapper around the supplied
Runnable. A variant of this is to
subclass Thread in order to apply
this wrapper at construction time.
Create a 2nd thread to join() on the
real thread and thus detect its
termination.
Use instrumentation to rewrite the Thread.run() method as above.
Just poking around in the (sun 1.5) source code for java.lang.Thread and sun.misc.VM, there is a field in thread called threadStatus. It is a private int and its values map to the enum java.lang.Thread.State. I have not verified this, nor determined how quickly it occurs if it does, but when a thread eventually terminates, this value will be set to java.lang.Thread.State.TERMINATED.
With this relatively simple condition to detect, I think it would be fairly straightforward to inject a field interceptor on threadStatus to fire an event when the field is set to a specific target value.
You could write a decorator for Runnable which calls a termination hook and wrap your thread code in it when you create the threads.
If you added a try/finally block to each run method, the code inside would be executed when each thread completed. Let the thread be responsible for its own clean-up.
AspectJ could help you do this if you needed to inject code into third-party compiled code, but apparently it doesn't work on standard Java class libraries.
Looks like there's a whitepaper on doing this here, but there's no telling if it's practical. I think you have to pay for it.
http://portal.acm.org/citation.cfm?doid=1411732.1411754
You could download OpenJDK, put the hook in yourself, compile a custom JRE and ship that with your application :)
As you say, there are no thread termination hooks. You have to code them yourself; call some method on a controller at the end of the run() method of your Runnables (AFAIK subclassing Thread is considered bad practice, you should implement Runnable and create a Thread with that Runnable as its target).
You can also implement an UncaughtExceptionHandler to know if a thread terminated abnormally due to an exception, in which case your controller's method won't be called.
If you run on java 1.5 you can probably do it using java.lang.instrument and the -javaagent option to the jvm.
Redefine the run method on the thread object which should call your code. You already seem to use instrumentation so it should be available. as it modifies runtime bytecode you should be fine
That said, it is hard to provide a more specific and detailed answer your question lacks at least the jvm version and the main frameworks in use (think spring-aop, jboss-aop, jvm version etc)

Categories

Resources