Subj : Re: How do I use the Java API in a Thread-Safe Manner? To : comp.programming.threads From : David Hopwood Date : Wed Jun 22 2005 09:53 pm Al Koch wrote: > 1) How "safe" is the new operator? Here is a (simplifed) piece of code: > > public static final String appendTrailingBackslash(String sStr) > { > sbStr = new StringBuffer(sStr); > sbStr.append('\\'); > return(sbStr.toString()); > } > > Do I ever need to worry about synch'ing the new and if so, how would I do > that in the above example. No. 'new' is threadsafe. > 2) We agree that I should be able to synch my object instances but what > about a static member function in the API. For example, > > MessageDigest mdSHA1 = MessageDigest.getInstance("SHA-1"); MessageDigest.getInstance simply asks each installed security provider whether it has an implementation of "SHA-1" (possibly caching the result for future calls). The only APIs that could change data structures that it reads are java.lang.Security.{addProvider,insertProviderAt,removeProvider}, and possibly setProperty. So unless you are also using those APIs, it can't fail to be threadsafe. > In this example, getInstance() is a static member. How in the world do you > protect this call? (I realize that one might argue that getInstance() > "appears" to only "lookup" something and as such needs no synchronization > but 1) how are we supposed to determine what a static member function does > internally You could look at the implementation you're using. Of course, this doesn't guarantee anything about other Java API implementations. > and 2) if we have a static member function that we do need to > worry about, how would that be protected?) Determine what other APIs might change any state that the function depends on, and make sure that your program and any of the libraries it uses don't make use of those APIs without synchronization (unless the documentation says it is safe). Yes, in principle there could be cases where this may be impractically difficult. OTOH, I've never found this to be a real problem in practice, possibly because: - typical Java programs don't use very many static API functions, - the ones that they do need to use are often implemented to be threadsafe, whether or not the docs say so. -- David Hopwood .