Reputation: 4886
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?
Upvotes: 0
Views: 1607
Reputation: 1539
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.
Upvotes: 1
Reputation: 726479
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.
Upvotes: 2
Reputation: 28019
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.
Upvotes: 4