Been trying to find the best way to implement a method that makes a defensive copy of a Calendar object.
eg:
public void setDate(Calendar date) {
// What to do....
}
I am particularly concerned about interleaving of threads when checking for null input and making the copy or am I missing something very apparent?
(Aimed at a slightly different audience now, I guess...)
I would use clone()
if I absolutely had to use Calendar
at all (instead of Joda Time). You argue in comments that you're worried about a "naughty subclass" - how would you propose to work around that in any scheme? If you don't know anything about the subclasses involved, and don't trust them, then you've got no way of preserving type-specific data. If you don't trust the subclass not to mess things up, you've got bigger problems in general. How do you trust it to give you the right results when performing date/time calculations?
clone()
is the expected way of cloning objects: it's where I'd expect a sensible subclass to hook in any type-specific behaviour it needed. You don't need to know which bits of state are relevant - you just let the type deal with that itself.
Benefits over using Calendar.getInstance()
and setting properties yourself:
EDIT: In terms of the "thread interleaving" which the original question worries about: the value of the date
parameter will not change whatever other threads do. However, if another thread is mutating the contents of the object while you take a defensive copy, that could very easily cause problems. If that's a risk, then you've got bigger issues, basically.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With