In a multi-threaded application, I encountered problems with dates being
"reset" to 1970, or being negative when converted into ms since 1970.
I use Calendar to do operations on dates, and as I see no obvious bug in the
code, and as the problem occurs randomly and after a certain time, I was
wondering if that was a multi-threading issue.
So the question is: Is Calendar.getInstance() thread safe?
I did not find a satisfying answer searching the web.
Is there asbolutely no possibility that two (or more) threads calling
Calendar.getInstance() at the same time get the same Calendar object?
In my code I do the following:
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MINUTE, amount);
[...]
Thanks for your answers.
Christophe B.
> So the question is: Is Calendar.getInstance() thread safe?
I think you have to assume all methods are thread safe unless there is
documentation to the contrary. How could you call any method reliably
unless it was deemed to be safe to do so?
> In my code I do the following:
>
> Calendar calendar = Calendar.getInstance();
> calendar.add(Calendar.MINUTE, amount);
"getInstance()" doesn't say it returns a new instance, but I don't see
how it could not. I think it is more likely that:
1. "amount" above is set to an incorrect value. Do you range check it?
2. The "calendar" object is getting set incorrectly after this line
(i.e., it's in the code you aren't showing us). OBJECTS are never
thread safe unless you make them so, and that discounts the possibility
of simple logic errors (i.e., you set the value of "calendar" to a
negative value somewhere else in your code).
I think we need to see some code that actually reproduces the problem.
If you can make an SSCCE that shows us the error, we'll take a look at it.
By synchronizing when you need to call them simultaneously from multiple
threads.
I doubt the Calendar class is thread-safe, except possibly static
methods like getInstance(). Typically, classes are NOT thread-safe
unless documented otherwise.
That said, I agree with the rest of your comments. The Calendar class
is mutable, so it wouldn't make sense if the "getInstance()" overloads
didn't create new instances each time they are called. So while not
explicitly stated, simply by virtue of how they work, those methods
should be thread-safe without any explicit implementation to make them so.
And indeed, if you look at the source code for the java.util.Calendar
class, the getInstance() methods call a private static method
createCalendar(), the essence of which is simply to use "new" to create
a new instance. And "new" is definitely thread-safe.
So if there's a thread-safety bug, it's probably in the OP's code, which
of course without a concise-but-complete code example (SSCCE) we would
not be able to point out.
Pete
Maybe for a static method like this. It is not very obvious to
synchronize on the Calendar class.
But in general (for instance methods) I would make the opposite
assumption: unless the doc states that it is thread safe, then
I will assume that it is not.
Arne
Synchronizing on what? Synchronization requires a shared object to be
effective. If you synchronize on ObjectA, and the body of some method
you call synchronizes on ObjectB, then nothing has been done and no
synchronization occurs.
If the method does not document what object you need to synchronize on,
then you can't do anything with it.
I think you know this, and maybe we are talking at cross purposes. What
I mean by "thread safe" here is that a method can be called safely by a
single thread. If you can't do that, then you can't make the call. The
OP doesn't seem to be implying anything different. He says he has
multiple threads, but doesn't provide any interaction between them other
than making one method call. Well, yes, that has to be safe, or no
thread at all could call the method. If it were not safe, like Java's
Swing methods, then it should be documented.
> I doubt the Calendar class is thread-safe, except possibly static
> methods like getInstance(). Typically, classes are NOT thread-safe
> unless documented otherwise.
By a single thread, sure, they must be. Objects aren't thread safe by
default. I see what you are saying, but sometimes I think people get
confused as to what thread safety really means, or does.
There's an implicit guarantee in all methods that they are safe to call
from a single thread. You have to have that or the method is just
broken. And that's all the OP has shown us, is a single method call by
a single thread. That much is always "thread safe."
What is thread safe by single thread?
I agree with:
http://en.wikipedia.org/wiki/Thread_safe
"A piece of code is thread-safe if it functions correctly during
simultaneous execution by multiple threads."
Thread safety as a concept relates to multiple threads.
Arne
It would be odd as hell for a static factory method not to be thread-safe.
But since this isn't documented anywhere, let's have a look at the source
code (for 1.5.0_16-b02):
public static Calendar getInstance()
{
Calendar cal = createCalendar(TimeZone.getDefaultRef(),
Locale.getDefault());
cal.sharedZone = true;
return cal;
}
private static Calendar createCalendar(TimeZone zone,
Locale aLocale)
{
// If the specified locale is a Thai locale, returns a
BuddhistCalendar
// instance.
if ("th".equals(aLocale.getLanguage())
&& ("TH".equals(aLocale.getCountry()))) {
return new sun.util.BuddhistCalendar(zone, aLocale);
}
// else create the default calendar
return new GregorianCalendar(zone, aLocale);
}
Not much doubt that it always returns a newly constructed one. If the
version you're using might return the same Calendar twice, it has a pretty
significant bug in it.
I'll give you a counter example: Most Swing methods are NOT thread safe
for a single thread to call, since they interact with the EDT and will
not synchronize properly between the caller and the EDT.
Let me try to explain my idea a bit more:
Given some method a(), if the results of a() are visible to the calling
thread (all object properly constructed, any threads started by the
method synchronize properly with objects they interact with, etc.) then
a() is safe for a single thread to call.
If the results are not visible (objects are NOT properly created) then
that method isn't safe. Again, using Swing:
public void createAndShowGui() {
JFrame frame = new JFrame( "Not safe." );
frame.add( new Label( "This isn't safe" ) );
frame.pack();
frame.setVisible( true );
}
This method is not safe to call, since it doesn't synchronize with the
EDT, and the objects aren't created in a thread safe manner. It's not
safe for even one thread to call without special consideration (being
called on the EDT).
Another example might be a method which uses a persistence layer to
makes database calls, perhaps on a separate thread. That method is
responsible for making sure all objects created or interacted with are
visible to the calling thread, or else document what the calling thread
has to do to make those objects visible.
Brian Goetz talks about this in Java Concurrency in Practice, that
single-thread safety is the default. Anything different must be documented.
my thread + EDT = single thread
????
> Let me try to explain my idea a bit more:
>
> Given some method a(), if the results of a() are visible to the calling
> thread (all object properly constructed, any threads started by the
> method synchronize properly with objects they interact with, etc.) then
> a() is safe for a single thread to call.
If the code in a() is thread safe then a() is thread safe. That
is hardly surprising.
> Brian Goetz talks about this in Java Concurrency in Practice, that
> single-thread safety is the default. Anything different must be documented.
It is reasonable to expect that the library does not start any threads
working on the objects unless the documentation state so.
But I still don't see much point in considering a single thread
scenario for thread safe.
Arne
Surely by that he specifically means that the default is for a class to
NOT be thread-safe. As Arne says, the idea of "thread safe" pertains
only to multi-thread scenarios. ALL code is trivially thread safe for
single-thread scenarios, and calling code "thread safe" but qualified to
only the single-thread scenario makes no sense.
Pete
I guess I have to conclude that the odd behaviour I get is related to my own
code rather than Java's Calendar class.
I would have prefered the mistake to be in Java standard API's, but... ;-)
So, I'll try to have a SSCCE, and that's what I should have done at the
beginning.
Thanks again for your answers and the interesting discussion on thread
safety.
Christophe B.
No he meant what I wrote. His exact discussion concerned the database
driver object, which is well known to be multi-threaded, but doesn't
document its thread safety. In fact, there were a few buggy
implementations which weren't safe for a single thread to execute.
Which was his whole point: in the absence of documentation, you have to
assume that method invocation is safe for a single thread. That's for
the caller and the implementer both.
I'll look up the chapter if you're interested in a reference, but it's
pretty easy to find too if you have a copy.
Second point: I said "method" (and so did the OP), you said class.
There's a difference. I'm only talking about the invocation of a single
method call by a single thread here.
>
> As Arne says, the idea of "thread safe" pertains
> only to multi-thread scenarios.
Which is possible to have multiple threads even if you have only one
thread yourself.
> ALL code is trivially thread safe for
> single-thread scenarios, and calling code "thread safe" but qualified to
> only the single-thread scenario makes no sense.
'cept for that Swing method I showed, and that buggy driver
implementation I mentioned, and ....
How can you use a multi-threaded example to claim that it makes sense to
talk about thread safety in the context of a single thread?
> In fact, there were a few buggy
> implementations which weren't safe for a single thread to execute. Which
> was his whole point: in the absence of documentation, you have to assume
> that method invocation is safe for a single thread. That's for the
> caller and the implementer both.
>
> I'll look up the chapter if you're interested in a reference, but it's
> pretty easy to find too if you have a copy.
I don't have a copy handy. Feel free to post the text that you believe
justifies the use of the term "thread safe" when talking about a
scenario in which only one thread is involved.
> Second point: I said "method" (and so did the OP), you said class.
> There's a difference. I'm only talking about the invocation of a single
> method call by a single thread here.
A practically pointless distinction when it comes to instance methods.
A class can support thread safety for a single instance method without
implementing it for any other instance method, but it's extremely
unusual to do so and of dubious usefulness in any case.
Still, whatever�if you'd prefer to constrain the discussion to single
methods, fine with me. It doesn't change the question of whether it
makes sense to use the term "thread safe" when there's only a single
thread involved.
>> As Arne says, the idea of "thread safe" pertains only to multi-thread
>> scenarios.
>
> Which is possible to have multiple threads even if you have only one
> thread yourself.
If there are multiple threads accessing the same object, that is a
multi-threaded scenario for that object.
>> ALL code is trivially thread safe for single-thread scenarios, and
>> calling code "thread safe" but qualified to only the single-thread
>> scenario makes no sense.
>
> 'cept for that Swing method I showed,
The method you showed is perfectly fine if it's called in the EDT
thread. If it's not called in the EDT thread, then by definition it's
not a single-threaded scenario for the method.
> and that buggy driver
> implementation I mentioned, and ....
The "bugger driver implementation" you mentioned is also specifically
not a single-threaded scenario.
Finally, I note that you have switched from the phrase "thread safe" to
the phrase "single-thread safe". The former makes sense only in a
multi-threaded context, the latter is not a useful phrase at all
(everything is trivially "single-thread safe").
If you have decided to concede the "thread safe" question and move only
to the "single-thread safe" question, I suppose I have to agree that
every method is "single-thread safe", simply because that's trivially
true. But that's not where this discussion started.
Pete
>
>In a multi-threaded application, I encountered problems with dates being
>"reset" to 1970, or being negative when converted into ms since 1970.
I have got in trouble with SimpleDateFormat not being thread safe.
Don't make them static unless you have but a single thread.
--
Roedy Green Canadian Mind Products
http://mindprod.com
The first 90% of the code accounts for the first 90% of the development time. The remaining 10% of the code accounts for the other 90% of the development time.
~ Tom Cargill
> I have got in trouble with SimpleDateFormat not being thread safe.
How possibly _could_ a SimpleDateFormat be thread safe?
Regards, Lothar
--
Lothar Kimmeringer E-Mail: spam...@kimmeringer.de
PGP-encrypted mails preferred (Key-ID: 0x8BC3CD81)
Always remember: The answer is forty-two, there can only be wrong
questions!
?
What do you mean ? It looks to me if SimpleDateFormat had been designed
immutable, it would make sense to have it thread-safe, as other
languages or libraries have it.
Actually, even though its mutable, I would have expected it to be
thread-safe as long as you don't mutate it anymore. Thankfully the
JavaDoc is clear that it's not. Oh well.
--
Mayeul
> Lothar Kimmeringer wrote:
>> Roedy Green wrote:
>>
>>> I have got in trouble with SimpleDateFormat not being thread safe.
>>
>> How possibly _could_ a SimpleDateFormat be thread safe?
>
> ?
>
> What do you mean ? It looks to me if SimpleDateFormat had been designed
> immutable, it would make sense to have it thread-safe, as other
> languages or libraries have it.
I mean, how can you expect it to be thread safe if the Javadoc
clearly states
| Synchronization
|
| Date formats are not synchronized. It is recommended to create
| separate format instances for each thread. If multiple threads
| access a format concurrently, it must be synchronized externally.
> Actually, even though its mutable, I would have expected it to be
> thread-safe as long as you don't mutate it anymore. Thankfully the
> JavaDoc is clear that it's not. Oh well.
Ah, you read it (now) ;-)
>I mean, how can you expect it to be thread safe if the Javadoc
>clearly states
It was quite some time ago I got in trouble. I suppose I thought of a
SimpleDateFormat as sort of static final constant, like the string
that describes a Regex.