Subj : Re: How do I use the Java API in a Thread-Safe Manner? To : comp.programming.threads From : Al Koch Date : Wed Jun 22 2005 11:02 am Hi David, Thanks very much for your reply. I have a couple of follow on questions. > APIs in Java are not functions, they are class interfaces. What the > references you found mean by saying that the API is not in general > thread-safe, is that if you use the *same* API object from multiple threads, > there may not be any synchronization (unless the documentation says there is). > > If you create objects that are only accessible to code that you write, > OTOH, then you can ensure the necessary synchronization when using those > objects. This argument may not apply to static methods of some API classes. I didn't state it in my question but I agree that "most of the time" the API would be called on an instance of a "Java API class" and I suspected that I ought to be able to synch control of my object instances (I didn't want to say that in the question so that I could get a "wide open" response.) However, there are (at least!) two things that confuse me: 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. For instance, the following wouldn't accomplish anything (assuming it is even necesarry to protect the new): public static final String appendTrailingBackslash(String sStr) { Object lockObject = new Integer(666); StringBuffer sbStr = null; synchronized(lockObject) { sbStr = new StringBuffer(sStr); } sbStr.append('\\'); return(sbStr.toString()); } 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"); 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 and 2) if we have a static member function that we do need to worry about, how would that be protected?) Thanks again for your help. Al. AlKoch@MyRealBoxREMOVEALLTHESECHARS.com .