Java: naming conventions for thread safety?
Imagine I have this class:
class Notifier {
public Listener listener;
public void notify() {
if (listener != null) {
listener.stuffHappens();
}
}
}
This code is incorrect in the case listener
can be changed from another thread. Let's fix it:
class Notifier {
public volatile Listener listener;
public void notify() {
Listener l = listener;
if (l != null) {
l.stuffHappens();
}
}
}
The code is correct now, but the notify()
method l开发者_运维知识库ooks weird in isolation. Imagine a larger class with a mix of volatile and regular fields used in the same method and you'll get the picture.
My first impulse is to name the variable volatileListener
---assuming it's private and there's a setListener()
of course, but I imagine a "hungarian notation is evil" knee-jerk reaction from many people.
So, are there established practices/conventions? Or maybe there are some patterns allowing to systematically avoid such situations. What do you do when writing heavily multi-threaded code?
What do you do when writing heavily multi-threaded code?
Separate the code that cares about threading from the code that doesn't.
Having a class responsible for notifications is a good start, but your comment about "change[ing] listener from another thread" is disturbing -- and making your listener
variable public is even more disturbing. Make it private, and add methods to Notifier
to control changes.
And don't add code to Notifier
that does anything other than notify listeners.
This is not a naming convention, but in Java Concurrency in Practice the authors suggest using annotations to describe thread safety policies.
I would highly recommend this book to anyone writing multi-threaded code in Java.
Brian Goetz suggested in his book "Java Concurrency in Practice" the usage of Annotations to mark fields an classes as thread-safe or not.
http://www.javaconcurrencyinpractice.com/annotations/doc/net/jcip/annotations/package-summary.html
(Nerveless Anon is right, separate thread safe and not thread safe code.)
精彩评论