File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Developer Certification (SCJD/OCMJD) and the fly likes API methods and synchronization Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Developer Certification (SCJD/OCMJD)
Bookmark "API methods and synchronization" Watch "API methods and synchronization" New topic

API methods and synchronization

Mike Hays

Joined: May 15, 2009
Posts: 14
I call Random.nextLong() and HashMap.toString() from code that is accessed by multiple threads. Should calls to these methods be synchronized? I believe Random is threadsafe. I know that HashMap is not, but I'm not sure about toString().

This question may be better suited to the Threads forum, but since the issue came up while working on the SCJD exam I'll post it here.
K. Tsang

Joined: Sep 13, 2007
Posts: 3130

Howdy Mike. I don't know why you need to use the Random class when the record numbers are calculated from the Sun data file. The toString() method in HashMap isn't synchronized.

K. Tsang JavaRanch SCJP5 SCJD OCPJP7 OCPWCD5 OCPBCD5 OCPWSD5 OCMJEA5 part 1 part 2/3
Mike Hays

Joined: May 15, 2009
Posts: 14

I use the Random class' nextLong() method to generate lock cookies.

Since toString() is not synchronized does that mean I need something like

where masterLock is used to protect lockedRecords?
I agree. Here's the link:
subject: API methods and synchronization
It's not a secret anymore!