I need to access an API using their SDK.
Access (well, anything I need to access) requires the use of a context object. The same one.
Context context;
It is running with the possiblity (well, certainty) that multiple threads will access this same context object to perform various operations (via the 'context' object)
So, is all that is needed for Thread-Safety is to refer to it only via a synchronized getter()?
Example:
getContext().someOperation()
getContext().anotherOperation()
Definition:
public synchronized Context getContext() { return context; }
No, synchronizing only on the getter is not an option. There are two possibilities:
the Context object is threadsafe, in which case you don't need to synchronize on anything at all.
the Context object isn't threadsafe, in which case both your getter and anything else that touches it all have to synchronize on the same lock.
You should read up on the API and see whether the object is in fact threadsafe, usually with APIs that require sharing something like this it's only good sense from the API provider's point of view to protect it from concurrent changes.
Assuming the documentation is inadequate, which is typical, reasoning about the spec from the implementer's point of view can be useful. In this case, if the API requires synchronization, what would be the lock that you would synchronize on? For synchronization to work you need a shared lock. Usually the container is a lot better positioned to handle this kind of concern than you are on the client-side.
The synchronized keyword is pointing to the scope of the method. So only that method is thread-safe.
I.e., only that method can be called by one thread at a time (per instance, of course since the method is an instance method).
To make the context thread-safe, any actions on it need to occur within a synchronized block or method (unless the actions of the Context object are already thread-safe, of course).
Related
I'm very new to J2EE, so apologies if this is obvious. I have to work around a bad database design, which has an update which cannot be done safely in parallel. The easiest way to fix this (for now) is to place a mutex protection around the method call to serialize it's access.
I understand that you can't safely just use the synchronised keyword on the method in J2EE as the container may interfere. Is there a "supported" way in J2EE to make a mutex/semaphore/lock in an EJB to ensure access to a method is serialised for the entire J2EE application?
Try using a static object as the mutex, for example:
private static final Object mutex = new Object ();
public void someMethod() {
synchronized(mutex) {
// do work that must be globally synchronous
}
}
The reason that using synchronized on the method itself won't work for you is that the Java EE container may create multiple instances of EJBs but the methods marked synchronized are only protected on a per-instance basis (where each instance can have only one thread executing a synchronized method at a time, but multiple instances can be accessed concurrently).
Just for prosperity, the java.util.concurrent are all approved for use within the container. Blocking using a Semaphore will work within a single container, but you will need a higher level of synchronisation to maintain synchronisation in a cluster.
Is it safe to cache and re use the instances of java.lang.invoke.MethodHandle?
I check the JavaDoc and couldn't find anything about thread safety.
Yes, it should be perfectly safe to share MethodHandle objects between threads.
Note the API documentation says the following about it:
Method handles are immutable and have no visible state. Of course, they can be bound to underlying methods or data which exhibit state. With respect to the Java Memory Model, any method handle will behave as if all of its (internal) fields are final variables. This means that any method handle made visible to the application will always be fully formed. This is true even if the method handle is published through a shared variable in a data race.
MethodHandle is an abstraction for code invocation, not the management of state behind the code. Thus the reasoning for thread safety is that it is reliant on the target method that is being actually executed, not the MethodHandle object itself.
I have a class "A" with method "calculate()". Class A is of type singleton(Scope=Singleton).
public class A{
public void calculate(){
//perform some calculation and update DB
}
}
Now, I have a program that creates 20 thread. All threads need to access the method "calculate()".
I have multicore system. So I want the parallel processing of the threads.
In the above scenario, can i get performance? Can all threads access the method calculate at same instance of time?
Or, Since the class A is singleton so, the threads needs to be blocked waiting.
I have found similar questions in the web/Stackoverflow. But I cannot get clear answer.
Would you please help me?
Statements like "singletons need synchronization" or "singletons don't need synchronization" are overly simplistic, I'm afraid. No conclusions can be drawn only from the fact that you're dealing with the singleton pattern.
What really matters for purposes of multithreading is what is shared. If there are data that are shared by all threads performing the calculation, then you will probably need to synchronize that access. If there are critical sections of code than cannot run simultaneously between threads, then you will need to synchronize that.
The good news is that often times it will not be necessary to synchronize everything in the entire calculation. You might gain significant performance improvements from your multi-core system despite needing to synchronize part of the operation.
The bad news is that these things are very complex. Sorry. One possible reference:
http://www.amazon.com/Java-Concurrency-Practice-Brian-Goetz/dp/0321349601/ref=sr_1_1?ie=UTF8&qid=1370838949&sr=8-1&keywords=java+concurrency+in+practice
That's the fundamental concept of Singleton. Only one instance of the class would be present in the system (JVM). Now, it depends on the implementation of calculate(). Is it a stateless utility method? If yes, you might not want to make it synchronized. In that case, multiple threads will be able to access it at the same instance of time. If calculate() is NOT stateless, i.e. it uses instance variables (and those instance variables will be used by multiple threads), then be careful; You have to make calculate() thread safe. You have to synchronize the method. At least you have to use a synchronize block inside the method. But, once you do so, only one thread will be able to access it (the synchronized block or the synchronized block inside the method) at any point of time.
public void calculate() {
//Some code goes here which does not need require thread safety.
synchronized(someObj) {
//Some code goes here which requires thread safety.
}
//Some code goes here which does not need require thread safety.
}
If you want to use parallel processing (if that's the primary goal), then singleton is not the design pattern that you should use.
I have found similar questions in the web/Stackoverflow. But I cannot get clear answer.
There is a good reason for that!!
It is not possible to say whether a method on a singleton does, or does not, need to be synchronized by virtue of being singleton.
Synchronization and the need for synchronization is all about state that may be shared by different threads.
If different threads share state (even serially), then synchronization is required.
If not then no synchronization is required.
The only clues that you have provided us that would help us give you a yes / no answer are this enigmatic comment:
// perform some calculation and update DB
... and the fact that the calculate() method takes no arguments.
If we infer that the calculate() method gets its input from the state of the singleton itself, then at least the part of the method (or the methods it calls) must synchronize while retrieving that state. However, that doesn't mean that the entire method call must be synchronized. The proportion of its time that the calculate method needs to hold a lock on the shared data will determine how much parallelism you can actually get ...
The updating of the database will also require some kind of synchronization. However, this should be taken care of by the JDBC connection object and the objects you get from it ... provided that you obey the rules and don't try to share a connection between multiple threads. (The database update will also present a concurrency bottleneck ... assuming that the updates apply to the same database table or tables.)
It depends on how you implement Singleton. If you use Synchronized keyword then they will wait else not.
Use Singleton with eager initialization.
Something like this:
public final class Universe {
public static Universe getInstance() {
return fINSTANCE;
}
// PRIVATE //
/**
* Single instance created upon class loading.
*/
private static final Universe fINSTANCE = new Universe();
/**
* Private constructor prevents construction outside this class.
*/
private Universe() {
//..elided
}
}
Above will perform very well in multithreaded environment. or else you can go for enum implementation of Singleton.
Check this link for various singleton implementation: http://javarevisited.blogspot.in/2012/07/why-enum-singleton-are-better-in-java.html
Multiple threads can invoke calculate() at the same time.
Those invocations won't be queued (executed serially) within that JVM unless you perform some type of concurrency control (making the method synchronized is one option).
The fact that your object is a singleton may or may not affect performance, depending on how that object's attributes (if any) are used within calculate().
Also bear in mind that since you are "updating DB", table or row level locks may also limit concurrency.
If you are worried about performance, the best bet is to test it.
I have a method that is invoked by a scheduler every minute to get a file from ftp, process and persists its records to a DB. I need to make this thread safe so that if the method has to perform multiple files at once, it acts a in a thread safe way..
public synchronized void processData(String data){
//do processing
}
is this really going to be a thread safe method that will handle high volumes of load gracefully?
It's thread-safe as long as it doesn't use any stateful fields from the enclosing object.
In other words, if there is a class-level field that is manipulated or accessed in processData(String data) with the intention of keeping track of what's going on, then it's not thread-safe.
An example might be a class-level field called private Boolean hasConnection; If you need to check whether or not a connection exists with this field, then you don't have a thread-safe method.
If you meet this requirement, then you don't even have to add the synchronized keyword to your method. It will be, by default, thread-safe, and an unlimited number of threads may access it simultaneously.
If you do not meet this requirement, then you will need to post the whole class in order to determine whether or not it is thread-safe.
Assuming that the mysterious "process the file" operation is self-contained, the biggest thing you should worry about is your DB connection: do not make it shared, obtain a new one each time from a connection string, and use a connection pool. Do not make your method synchronized, unless you need to access shared state inside your class; otherwise, your method would not be able to make progress concurrently on multiple threads.
Please describe us what resources your method uses, and which of those resources are shared.
If you do not use common object, there is no problem.
If you do use common resources, you need to make sure these resources can be accessed in a thread-safe manner, or are not accessed by multiple threads.
Your question is about performance. In general, processData seems to be a method which will take some time to complete: you are using databases. The time required to get a lock is minimal compared to a DB Query. So no, the synchronized keyword will not give you any noticeable performance impact.
Servlets are not thread safe. So if I use a static function of a class, What will happen when multiple requests come at the same time. How will they deal with the static function?
You'll have to synchronize it if accesses shared, mutable data. If the data is immutable or read-only or on the stack you should be fine.
It depends on what kind of static method do you have whether it is stateless or not. If it is stateless, and not referencing anything outside from your method's scope it will be thread safe.
if you are using static method in servlets you need to make them thread safe by
Using only local variables when state of the variable may change
or use static variable if they dont change or use synchronize access method
and you can amke function thread safe by implementing the SingleThreadModle interface or by 'synchronize' construct.