Java Reference
In-Depth Information
Q How much slower is a synchronized method than an unsynchronized one?
A It's difficult to say, but unscientific tests seem to indicate that a synchronized method
is anywhere from 1.5 to 150 times slower than an unsynchronized method, depending
on contention. Noncontended synchronization may have negligible impact on time.
Q Can you synchronize data?
A No, you can only synchronize access to data.
Q Aren't vectors synchronized data?
A No, vectors provide synchronized methods that access their data. It's an important
difference.
Q What's the difference between synchronizing on a static member variable and a local
one?
A There's no difference, really. You're still obtaining a lock on an object. But by synchro-
nizing on a static member variable, the lock can be shared across multiple objects who
share that static object as a class member variable.
Q What does it mean when people say that an object, such as a Vector , is synchronized?
A It means that all public methods of that object are synchronized when they access
shared data. Generally, it means that calling a method on that object is an atomic
action. Any other thread calling a method on that object will block until your thread
completes its operation on that object.
Q What happens when one method synchronizes on a member variable, and another
synchronizes on the this keyword, and the two have to interact?
A Then you are acquiring two locks on two distinct objects—namely this and the mem-
ber variable—and it is very important to be careful. Otherwise, you are opening the
door to deadlock. You should consider carefully whether you really need to do this, or
whether you can synchronize on the one object.
Q How can I restart a thread after it has died?
A You can't. You will have to create a new thread.
Q Most of the examples provided show the main application implicitly waiting until all
the created threads had finished before exiting. Is there a way of exiting the program
without waiting for a thread to complete?
A Yes—you can explicitly call System.exit , or you can call Thread.setDaemon(true) on
the thread you don't want to wait for before you start it running. See the creation of the
IceCreamMan thread for an example of how to set a daemon thread.
Search WWH ::




Custom Search