Reputation: 98
I have a class whose public methods are synchronized (everything else is private and it has no subclasses). Does that make it thread safe? What about performance - how badly will it suffer if I have database access in the synchronized methods ?
Upvotes: 2
Views: 646
Reputation: 20069
The Answer is as usual: Depends on a lot of Details.
If your class has internal state that carries over between method invocations, it won't be thread safe. -EDIT- If a class/object is thread safe depends on, broadly speaking, if any sequence of calls made by multiple threads would create an inconsistent state in the instance. For example, if your class opens a JDBC connection, you could carry over that connection between calls without problem, but if you were giving out a ResultSet of said connection as a result from a method, that would be not safe, since the ResultSet could become invalid when another thread requests another ResultSet from the same connection -/EDIT-
If you take a performance penalty depends first and foremost on the number of accesses and how much time is actually spent in the synchronized sections, that is how long your DB accesses take.
Upvotes: 1
Reputation: 533870
Does that make it thread safe?
synchronized
methods help, but they only provide thread safety for one method at a time. e.g. StringBuffer
is thread safe, but only if you only use one method making it rather useless.
Also Iterator
are often not thread safe even if the collection is thread safe, as again, you need to call more than one method which mean releasing the lock between calls.
What about performance - how badly will it suffer if I have database access in the synchronized methods ?
Some where between none at all and a lot. However, correctness should come first, it doesn't matter how fast it is if it is wrong.
Upvotes: 1