Is java.lang.reflect.Method thread safe? - java

Is java.lang.reflect.Method thread safe?
Profiling result of my program showed that Class.getMethod() took considerable computing time when called many times, a little more than I expected.
I can call this once and store the resulting method somewhere easily accessible.
But then, multiple web worker threads will use the stored Method object concurrently.
Is this safe?

The Method is safe to use accross multiple threads provided you don't change the Method's state after making it available to multiple threads.e.g. You can call setAccessible(true) and setAccessible(false) in two threads and the result would be not thread safe. However this has no really good use.
In short, Method.setAccessible() is not techincally thread safe, but you should be able to use it in a thread safe way.

Java classes are guaranteed to be defined only once per ClassLoader instance, so you can safely assume that the definition, including methods and their signatures will not change through time, so you can safely "cache" them for use by multiple threads.
However, keep in mind that classes with the same fully qualified name (package + class name) can be defined differently by separate ClassLoader instances.

The class definition isn't going to change, so unless you are loading different classes in different threads (from separate libraries, say), the Method object should be thread safe. (Of course, whether the method itself being called by reflection is thread-safe is a different question.)

Related

Are all Java apps single-threaded unless the programmer explicitly creates Threads or implementations of Runnable?

I'm trying to understand how Java (and the JVM) create threads under the hood.
I read Java Concurrency in Practice, and I couldn't find a good explanation of whether or not all Java apps are, by default, single- or multi-threaded.
On the one hand, from the POV of a developer: I write a pile of sequential code without creating Thread instances or implementing Runnable anywhere. Do I need to synchronize anything? Should I be making double-sure my classes are thread-safe? If so, should I stop using POJOs that have mutable fields? I read that the JVM will create multiple threads under the hood for its own business. Is the JVM also creating threads to run my application without me explicitly creating those threads?
On the other hand: I write a pile of code in which I explicitly create Threads and Runnable implementations. Does the JVM spin off its own threads to "help" my multi-threaded code run faster?
It's entirely possible I'm not even thinking about the JVM's thread handling in the right way. But, I'm an entry-level Java developer, and I hate that I find this confusing.
On the one hand, from the POV of a developer: I write a pile of sequential code without creating Thread instances or implementing
Runnable anywhere. Do I need to synchronize anything? Should I be
making double-sure my classes are thread-safe? If so, should I stop
using POJOs that have mutable fields?
The straightforward answer is that no, you do not need to proactively make your objects thread-safe to protect them from concurrent access by threads you did not create.
Generally speaking, threads that interact concurrently with the code and classes you write1 won't be be created unless you do something yourself that is known to create threads, and then you organize to share an object instance between threads. Creating a Thread object is one example of creating a thread, but there are others. Here is a non-exhaustive list:
Using Executor or ExecutorService implementations which use threads (most of them).
Use a concurrent Stream method e.g., by creating a stream with the parallelStream method.
Use a library method which creates threads behind the scenes.
So generally threads don't just pop out of nowhere but rather as a result of something you do. Even if a library creates threads that you don't know about, it doesn't matter for your concern because unless documented otherwise they will not be accessing your objects, or will use locking to ensure they access them in a serialized fashion (or the library is seriously broken).
So you generally don't need to worry about cross-thread synchronization except in places where you know threads are being used. So by default you don't need to make your objects thread-safe.
1 I'm making this distinction about "interact with code you write" because a typical JVM will use several threads behind the scenes, even if you never create any yourself, for housekeeping tasks like garbage collection, calling finalizers, listening for JMX connections, whatever.
Is the app code you wrote single- or multi-threaded? Unless you explicitly took steps to create new threads – for example, by doing something like Thread t = new Thread(); – your app code will be single-threaded.
Are there multiple threads running in a single JVM? Yes, always – there will be various things running in the background that have nothing to do with the code you wrote (like the garbage collector).
Should you guard against concurrency concerns? With a single-threaded app, there is no need. However, if your code itself creates one (or more) threads, or if your code is packaged up in some manner to be used by other app creators (maybe you've created a data structure for others to use in their code), then you might need to take steps for concurrency correctness. In the case of creating code for others to use, it's perfectly fine to declare in Javadoc that your code is not threadsafe. For example, ArrayList (https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html) says "Note that this implementation is not synchronized" along with suggested workarounds.

Does my elasticsearch callee method needs to be threadsafe?

I am using RestHighLevelClient provided in elastic search java library. As per documentation, this class is threadsafe. I am using create index function inside a method. Do I need to specifically made that thread safe?
Or in general, if the objects used by a java method are threadsafe, then does it make sense to make method thread safe?
Do I need to specifically made that thread safe?
Since you seem to mean making the method synchronized, the answer is no. "Thread-safe" means that the methods of the class can be safely invoked from multiple threads without external synchronization like the one you propose.

Why wait, notify and notifyAll are methods in Object class not like Cloneable

Recently, I was asked in interview why wait, notify, and notifyAll are used. I explained them.
After that they asked me to assume an application is always single threaded. Is it really required? My answer was no.
Then, they asked why is design like wait, notify, and notifyAll are methods on the Object class. Why doesn't Java have an interface and these methods are in that interface and which ever class wants to implement it can use it. So, I was kind of stuck and unable to think over this design. Can anyone please sow light over this?
JVM uses OS-level threads. That means that each concrete JVM for each concrete OS handles threads differently. And these methods are not only implemented in Object class, they are marked as native, which kind of means that the are implemented in system layer of JVM.
And if those methods were in some interface, that would mean that anybody can redefine them.
Wait and notify and notifyAll is not just normal methods or synchronization utility, more than that they are communication mechanism between two threads in Java. And Object class is correct place to make them available for every object if this mechanism is not available via any java keyword like synchronized. Remember synchronized and wait notify are two different area and don’t confuse that they are same or related. Synchronized is to provide mutual exclusion and ensuring thread safety of Java class like race condition while wait and notify are communication mechanism between two thread.
Then, they asked why is design like wait, notify, and notifyAll are methods on the Object class. Why doesn't Java have an interface and these methods are in that interface and which ever class wants to implement it can use it.
All of these methods are implemented in native code and they integrate closely with the synchronized block that wraps them. They are part of the Java language definition and have specific behaviors that programmers rely on. It would not be appropriate for them just to be interface methods that any object would implement.
When one object calls obj.wait(); on another object, it doesn't have to worry about the implementation of wait. It needs to make sure that it has a mutex lock on that object so it can make critical updates to it or other storage and if the wait method was implemented by the object itself, then that object could violate the language requirements and, for example, allow multiple threads into the protected block at the same time. A thread can synchronize and call wait/notify/notifyAll on another object or not without having to worry about whether or not that object has implemented those methods appropriately. By making them final methods on Object the behavior will work the same regardless of the object type or local implementation.
Also, as I mentioned, wait/notify/notifyAll are integrated closely with the surrounding synchronized block. When a thread is blocked in wait() the surrounding synchronized lock is released so that other threads can get access to the protected block. This coordination would not be possible if the wait() was just a simple method call without other strange language features.
This reminds me of my other answer here: Concept behind putting wait(),notify() methods in Object class
It was a design goal from the start that Java programs would be multithreaded. Remember the plan was for Java to make embedded programming less intimidating, the whole serverside web application thing (leading to the commoditization of Sun's core business) was an accident.
Since the goal was to enable creating embedded applications that would talk to other devices, it had to be multithreaded in order to be network-friendly and event-driven. But writing efficient multithreaded servers wasn't high on the list for java.
Java didn't have ReentrantLock or nonblocking i/o for a long time. Initially the main data structures available were Vector, Hashtable, and StringBuffer (all of which had synchronized on all public methods). From that choice it seems like the goal was good-enough, as opposed to being as efficient as possible. Later on it was clear Java needed to be more efficient for the use case of server applications and 1.2 introduced equivalents of Vector and Hashtable that were unsynchronized. This seemed like an afterthought, a course adjustment made once it was apparent Java had a new role it wasn't previously designed for.
If Java had stayed in the niche it was created for then possibly intrinsic locks might have been adequate. It seems the initial plan was for intrinsic locks only, so that the lock might as well be wired into the Object.

Thread safe method and stack

StringBuffer class having methods which are thread safe? OK but i have question that when the particular method will be called then it will be loaded on to stack and stack is thread safe so why we need the thread safe method?
It's quite possible to share a given StringBuffer instance across different threads in which case multiple threads will end up "modifying" or mutating the StringBuffer's internal state. This is why it's required to explicitly synchronize append methods on a StringBuffer.
But you are right. If you don't plan on sharing stuff across thread boundaries (or like they call "publish" the instance), it is more logical to just create a StringBuilder instance (which is the non-synchronized brother of StringBuffer) in a given method call and throw it away (or more like let the GC take care of it) after the method call ends.
There is another aspect which comes into play when you absolutely have to share instances across threads and at the same time feel that the cost of synchronizing each operation is way too much -- thread locals. Basically, the idea in this case is to make each thread have its own copy of a "mutable" entity. There is no locking required because the moment some other thread tries to access a thread local variable, you hand across a fresh/pre-configured instance. This is commonly used for stuff like sharing StringBuilder and DateFormat instances to boost performance.
If you want to compare between raw/unsafe sharing of a mutable object between threads versus using a thread local, take a look at the snippet I have hosted on Bitbucket.

multi thread safe class

Question:
A) Write a thread safe class with methods doA(), doB(), doC(). Each of these methods must report the method name, time of invocation, and calling thread name.
B) Write a multi threaded driver that spawns 4 threads, and each thread must call every method – doA(), doB(), doC() – 10 times
I am assuming that it means doA(), doB(), doC() must be safe. But none of them mutate the shared state within the object, they just read object state such as method name, thread name and running time. So, do I need synchronize each method? For the counter within each thread, it is not shared.
I am a little confused here, which of state of the object needs protection?
Edit:
Do we need a mechanism to assure the running sequence of doA(), doB(), doC()? I dont think so.
From the sounds of it, your object will have no mutable state at all. Objects without mutable state are usually (not always, but usually) thread-safe without any additional locking. Of course, if there's additional requirements that do imply mutable state, the answer would be different.
How are you reporting the information? If it's to a console or any other resource that's independent of thread, there's your shared "state". Sort of. Some mechanisms for writing to a console will buffer lines, so you may not have problems, but over multiple lines you'll have to make sure that two don't write to it at the same time. For example, if I were to print:
Thread: A
Method: doA
Running Time: 4.6s
Then I'd want to make sure another thread doesn't start half-way through. Otherwise you may end up with something like this:
Thread: A
Thread: B
Method: doB
Running Time: 4.6s
Method: doA
Running Time: 3.2s
Not so helpful.

Categories

Resources