Reputation: 23
Say I have a class with synchronized methods. It's actually a class that uses Apache POI to write excel files.
public static synchronized List<CellData> createRow(final CellData... columns) {
List<CellData> row = new ArrayList<CellData>();
if (columns != null && columns.length > 0) {
for (CellData column : columns) {
row.add(column);
}
}
return row;
}
public synchronized void writeFile() throws IOException {
.................
}
This helper class resides in a jar (common library) and many programs use it at the same time.
Do I really need to make this class synchronized since every other class that uses it creates an instance of that helper class?
Upvotes: 2
Views: 703
Reputation: 351
Few things to note here
Upvotes: 0
Reputation: 24791
If the method does not use any member fields of the class(i.e. it uses only local variables), then you don't need any synchronization
Upvotes: 1
Reputation: 3225
You only need to synchronize the access of shared data if there's a possibility that you'll have more than thread accessing the same instance of your class at the same time.
So the questions are:
Do your methods actually share the access to any instance variables?
Are you ever going to have more than one thread accessing one instance of your class at the same time?
In the situation you described does not seem to be something that anyone that uses that library would want to do. You could simply just document that this implementation is not synchronized.
Upvotes: 1
Reputation: 920
You should synchronize your method in case of altering data which can be accessed from several threads.
Your method (at post) manipulates with data which was passed as a parameter, so you have not to use synchronization.
But if your static method will manipulate (alter) with public static data, it will require using of synchronization of method.
Upvotes: 0
Reputation: 308733
I don't see any variables that are preceded by this.
, so I can't detect any member variables that are shared in your code. It looks like your createRow()
uses only parameters that are passed in and local member variables. If that's true, I'd conclude that you don't need to synchronize.
Upvotes: 1
Reputation: 26597
the synchronized keyword do synchronization only between threads that call the method on the same instance of the object.
In the case you're describing, since each other class create their own instance, the synchronized serves absolutely no purpose, so you can safely remove it.
Upvotes: 4