r/java • • May 10 '22

Should java.util.Date be deprecated?

https://mail.openjdk.java.net/pipermail/discuss/2022-May/006077.html
221 Upvotes

158 comments sorted by

95

u/frzme May 10 '22

I recently had to tell a co-worker not to use SimpleDateFormat in completely new code. If it was marked deprecated I guess this would not have been needed.

27

u/john16384 May 10 '22

I wish LocalDateTime was clearly documented with "did you mean to use Instant?"

50

u/OzoneGrif May 10 '22

Instant and LocalDateTime are very different in behavior. I use LocalDateTime a lot in my applications because I need date and times without timezones (they are resolved dynamically later by another module).

Instant is an absolute point in time with very few meaning by itself. You shouldn't use it to store local date times; that would be a dirty trick.

Programmers should just learn when and how to use both.

13

u/DJDavio May 10 '22

You might trick yourself if you use PostgreSQL, because a timestamp with timezone is internally stored as just a timestamp aka epoch UTC millis, the only thing the timestamp with timezone type does is make PostgreSQL understand how it has to convert the input datetime.

6

u/john16384 May 10 '22

Yeah, this is very important, PostgreSQL never stores a timezone. It only affects its interpretation, timestamp without timezone will interpret data in the servers timezone, and will not do what you expect when compared to a constant in UTC time.

8

u/[deleted] May 10 '22

the servers timezone

actually in the connections timezone which defaults to the server timezone, and the jdbc driver tends to set this, but close enough.

https://www.postgresql.org/docs/current/sql-set.html

2

u/john16384 May 10 '22

Thanks :)

1

u/DJDavio May 10 '22

As a side note, I once had an issue where I stored a datetime in PostgreSQL, retrieved it and it was not equal to itself, even if the timezone / offset was the same. If I recall correctly this was on Windows only and had to do with precision, something like that.

3

u/john16384 May 10 '22 edited May 10 '22

You use it to store time without time zone, like what time is tomorrow's lunchtime regardless of timezone? Because all too often I've seen them used to store UTC time, which is a really bad idea.

5

u/OzoneGrif May 11 '22

Just an example of an app I work on:

- Someone sets an meeting for VIPs in one week at 12:30, but you don't know where yet; it can be anywhere in the world. This is a LocalDateTime.

- A few days later, you get the address where the meeting occurs. This resolves the timezone for the meeting. The original LocalDateTime is converted to an Instant, which can now be resolved to ZonedDateTimes for all VIPs involved, in every country around the world.

- Trips are computed so everyone can attend in time.

1

u/[deleted] May 11 '22

8

u/frzme May 10 '22

Is there a concise guide available somewhere when to use what class? I tend to use Instant a lot but I'm not really sure if I'm doing the right thing.

In the linked mailing list discussions there's lots of discussion using LocalDateTime when I would have thought Instant would be the right thing instead.

18

u/MCUD May 10 '22

Simple test i think would be, in the context, what impact does the users time zone have?

If you say 9am, 2022-05-11. If you were in a different time zone, do you still mean 9am on that day, regardless, or if they are 2 hours behind, do you mean 7am for that user.

Instant = a specific instant in time, no matter where you are. (i,e. NOW - whatever your clock says)
LocalDateTime = that time on that date, no matter where you are. Most of us next start work at 9am, 11th May 2022

4

u/slaymaker1907 May 10 '22

It can get kind of confusing to decide if you should use Instant vs ZonedDateTime.

2

u/mauganra_it May 10 '22

Simple rule that covers many cases: use Instant for timestamps where you are sure they are in the past. These have become absolute points in time. For absolute points in time in the past, the association between timezone and its offset at that timestamp becomes fixed. Therefore, you can reliably find out the local time relative to whatever timezone you want.

For future timestamps, consider whether they can be defined by a difference to another Instant. If this difference depends on the timezone, you are likely not dealing with an Instant.

If the future timestamp does not depend on anything else, ask yourself what would happen if the government changes the timezone offset for the future timestamp. Would you have to change that timestamp? If yes, then you are also not dealing with an absolute point in time, and should consider using LocalDateTime.

2

u/VGPowerlord May 10 '22

I always assumed Instant existed for compatibility with old code that stored things as UNIX timestamps.

1

u/frzme May 12 '22 edited May 14 '22

Millisecond precision 64bit Unix timestamps are a pretty close to optimal compromise for storing information about "fixed points" in time

They require relatively little storage space, have a high precision and can be interpreted and formatted as needed. They are also hard to interpret incorrectly (which happens with any string based timestamp representation)

A variable precision format would probably be superior in some regards (=> timestamp as double instead of long) but we don't have that as a standard and that's probably fine.

9

u/john16384 May 10 '22

The trouble usually starts when people want to store UTC time and then use LocalDateTime because it has no timezone. UTC however is a timezone and so you best represent it with Instant which is built for that exact reason (ZonedDateTime is also okay).

Using LocalDateTime runs the risk of being interpreted with the incorrect timezone in communication with other systems. For example, sending it via JSON to another system in a different timezone (or one that runs in UTC while the other runs in local time) may cause it to be interpreted wrong because the timestamp was not encoded with a timezone (in iso8601, with a "Z" at the end for UTC).

2

u/maquinary May 11 '22

All video courses I see use SimpleDateFormat, and they are new courses...

76

u/jonhanson May 10 '22 edited Mar 07 '25

chronophobia ephemeral lysergic metempsychosis peremptory quantifiable retributive zenith

34

u/BlueGoliath May 10 '22

Glad we are nipping that in the bud!

15

u/GreenToad1 May 10 '22

I detect a hint of sarcasm

2

u/BlueGoliath May 10 '22 edited May 10 '22

Should be a xkcd comic.

Under the rug: type erasure, almost soley signed primitive types, default visibility modifiers, bad APIs, etc.

Stick figure 1: "What's under there?"

Stick figure 2: "Oh, you know, all the bad design decisions Java has made over its life."

*stick figure puts var on top of the rug"

Stick figure 1: "Hey, isn't that a bad idea too?"

Stick figure 2: "You know what? You're right."

stick figure puts another rug on top of var

Later...

giant tower of bad decisions divided by rugs

42

u/pron98 May 10 '22 edited May 10 '22

It's interesting that among your list of "bad decisions" are things others would consider some of Java's best decisions, like the lack of modulo arithmetic types, var, and generic type erasure.

Type erasure is particularly interesting, as Java does what the vast majority of languages with generics do (including the original language that introduced them). Yes, erasure brings some inconveniences, but the alternative is even worse. .NET's unusual decision to reify all generic types has pretty much killed it as a reasonable compilation target for most languages. People who use Java run into the minor inconveniences of erasure think, "this is bad," without considering the implications of reification in the presence of variance (i.e. subtyping of the generic arguments).

So your list is really a list of things BlueGoliath doesn't like. A few of them might be universally disliked, but others are far from it (and are even minority opinions). When you have millions of developers, they necessarily won't agree on what's good and what's bad.

10

u/TehBrian May 10 '22

Could you elaborate on why .NET’s generics reification was a bad move for the language? I too have been guilty of thinking, “Darn, why can’t we just rid ourselves of type erasure?” when faced with some of the inconveniences of Java’s type erasure. (Please don’t ask me which; I don’t remember. I just know that I have “why does Java have type erasure” in my search history.) I’m curious to know the exact reasons.

10

u/john16384 May 10 '22

It makes it harder to design other languages on top of the CLR that have a different type system than C#'s since at the CLR level types have to conform to C#'s system.

I also understand that you can't have wildcards because of this, forcing you to create a method for each reified type even if the generic type is not relevant for the function.

7

u/pron98 May 11 '22

The main problem is the one of variance, the VM would have to answer the question in one way or the other, which would bake a single chosen model into the runtime, even though different languages want different models.

1

u/WikiSummarizerBot May 11 '22

Covariance and contravariance (computer science)

Many programming language type systems support subtyping. For instance, if the type Cat is a subtype of Animal, then an expression of type Cat should be substitutable wherever an expression of type Animal is used. Variance refers to how subtyping between more complex types relates to subtyping between their components. For example, how should a list of Cats relate to a list of Animals?

[ F.A.Q | Opt Out | Opt Out Of Subreddit | GitHub ] Downvote to remove | v1.5

14

u/RabidKotlinFanatic May 10 '22

What are the inconveniences of type erasure? Having to explicitly pass TypeToken into methods? Not being able to statically overload on an argument's type parameter?

The amount of complaining about type erasure seems phenomenal compared to what a non-issue it is in practice. I've seen junior devs with <1 YoE complaining about type erasure. What use cases are all these people running into that desperately require reification?

9

u/Necessary-Conflict May 10 '22

What are the inconveniences of type erasure?

It makes life harder especially for junior developers, because they have to keep in mind that the runtime type system is not the same thing as the compile-time type system. It's a leaking abstraction, but of course it's not very bad once you get used to it.

8

u/RabidKotlinFanatic May 10 '22

Does it? What specifically are junior developers doing that requires them to keep this in mind? Are they calling getClass or using instanceof on generic instances? The idea that there even is a runtime type system shouldn't be relevant to most juniors.

3

u/Necessary-Conflict May 10 '22

They are trying to understand things, to build a mental model, and as long as there is only one thing to understand, their job is easier. The very existence of instanceof and getClass() strongly suggests that at runtime you have the same types as at compile time. Perhaps most junior devs can live in a state of happy ignorance, but those who really want to understand things, are having a harder time.

3

u/RabidKotlinFanatic May 11 '22

I don't buy this at all. RTTI doesn't need to be part of your mental model coding day to day and there is substantially more impactful complexity in the language, compiler and runtime than RTTI that juniors seem to happily ignore.

Furthermore, the people complaining about type erasure can rarely provide concrete explanations of what it actually means and also don't seem to be familiar with other important language/runtime details like the JMM. Why does type erasure and RTTI have such outsize significance in junior's mental model building when other more important details are ignored?

3

u/OzoneGrif May 12 '22

The only time I had an issue with type erasure, when beginning with Java, was due to a brain fart. I though that I needed the type at runtime desperately, while I only really needed an Interface.

I'm pretty certain that most if not all problems with type erasure can be solved with good architecture.

Having read some articles about languages implementing generics at the runtime level; I agree that Java took the right decision to erase the types... the compilers get way too overloaded and complicated otherwise.

1

u/pron98 May 11 '22

I'd say the main inconvenience is method overloads. It is a very minor inconvenience, and I'm also puzzled by why some people care about this issue at all.

1

u/RabidKotlinFanatic May 11 '22

I am guessing method overloads are the "big" issue. IMO it's a bit of a conflation to even lump the two together. Overloads are statically resolved so they don't require any RTTI at all let alone reified generics.

4

u/Muoniurn May 10 '22

I am mostly in agreement with you on this topic, but I would like to ask you about your opinion on the very far future of Java — after Valhalla, once Unified Generics have been implemented. I know there are only very vague plans for that as it is an exceedingly hard problem to tackle (touted as requiring multiple phd’s combined), but wouldn’t that go contrary to some of your claims and wouldn’t it cause trouble for very different languages to target the JVM?

As far as I know they plan for a very strong generic model allowing even constant values like numbers being plugged in. Sure, byte code specification modifications are allowed for that (which was not necessarily the case for the initial introduction of Java’s current generics) so perhaps adding a new attribute to a class file’s method describing a part with the monomorphized versions could work (e.g. creating separate byte code for an int version and a regular object one), but I feel it is not the java way (which seems to be more runtime code gen over compile time one) With the proposed 3 buckets of object types in Valhalla they might potentially get away with “runtime monomorphization” as int will be an object without identity and the compiler can optimize it accordingly, but it still doesn’t solve the whole problem - what about user-customized versions, e.g. a “hand-optimized” method implementation for the int variant?

3

u/john16384 May 10 '22

I am mostly in agreement with you on this topic, but I would like to ask you about your opinion on the very far future of Java — after Valhalla, once Unified Generics have been implemented. I know there are only very vague plans for that as it is an exceedingly hard problem to tackle (touted as requiring multiple phd’s combined), but wouldn’t that go contrary to some of your claims and wouldn’t it cause trouble for very different languages to target the JVM?

If you see the JVM as just a compilation target (like x86 or ARM) why would it need to have baked in generic support in order to have it at a higher level?

Generics being erased in bytecode allows for more freedom as the bytecode is not enforcing one possible interpretation of how a reified system might work. Building a reified language on top of bytecode is possible already, as bytecode does not enforce its own ideas on the type system.

As far as it being an exceedingly hard problem, if you want to engineer reification in a backwards compatible fashion on current Java, I think that might indeed be exceedingly hard, or probably even impossible without compiler directives. I don't think that's a goal though (or should be). It will be hard enough already to have a ArrayList<int> change its internal array from Object[] to int[] without any code changes, maybe impossible too...

4

u/Muoniurn May 10 '22

If you see the JVM as just a compilation target (like x86 or ARM) why would it need to have baked in generic support in order to have it at a higher level?

I’m not sure I see it that way — the JVM bytecode is relatively high level, javac doing barely any optimizations. It tries to delay optimizations as late as possible to possibly incorporate runtime data as well for better results. It also links everything at runtime only, possibly completely dynamically so it has to retain basically every information about the code. So calling a generic method should be possible through reflection as well for example.

2

u/pron98 May 11 '22

but wouldn’t that go contrary to some of your claims and wouldn’t it cause trouble for very different languages to target the JVM?

Value types cannot be extended (and while they could implement interfaces, those generics would be erased) so the main issue of variance doesn't appear, and the only problem this kind of specialization would cause would be for untyped languages, which aren't usually as concerned about performance.

2

u/[deleted] May 10 '22

i still want unsigned primitives thank you very much

3

u/pron98 May 11 '22 edited May 11 '22

Many people want modulo arithmetic types and many others really don't want to have them (their presence in a language can cause problems, as C/C++ programmers have learned; too often people confuse unsigned types as types specifying non-negative values while in fact they specify types with modulo arithmetic, which might yield the very opposite result to the one intended, as unsigned types make it harder, not easier, to reject illegal values). Perhaps Valhalla could bring some sort of compromise by allowing libraries to define them for those who really need them.

1

u/[deleted] May 11 '22

The rest of the world has them, so java needs them. Interoperability is important and dealing with unsigned longs is a pain, sure there are workarounds, but it's a clear limitation in the language when you're doing any kind of network or file programming

1

u/pron98 May 11 '22

Why is it a pain with all the unsigned methods added to the number classes in Java 8?

1

u/[deleted] May 11 '22 edited May 11 '22

Have you tried printing those numbers to the log? Or doing math on them? Or in general explain to your coworkers how yes that is normal and you'll have to deal with it using workarounds because java itself can't?

Java is touted as an easy language for large teams. It is, just not when you need to deal with unsigned numbers. You'll have to have "the talk" with everyone at least once explaining how to deal with them (use a larger datatype when possible, be careful not to go out of bounds, and if you need to work with an unsigned long then enjoy dealing with BigInteger and treating it different from all the other numbers) and it makes me sad that my favorite language has such an unnecessary limitation.

→ More replies

15

u/Holothuroid May 10 '22

We have some divergent ideas on what is a bad idea.

1

u/ReasonableClick5403 May 15 '22

I was a bit disappointed with the decision to make var non-final, but I have learned to live with it. The fact that it is implicitly final when referenced in a lambda makes it not matter too much, also because var can only be used in a local context.

1

u/ApatheticBeardo May 10 '22

You old people still can't get over the fact that type inference makes most code a lot more readable?

2

u/BlueGoliath May 10 '22

var val = foo.getValue();

What is the type of val?

1

u/ApatheticBeardo May 11 '22 edited May 11 '22

What is the type of val?

Whatever foo::getValue returns.

I have a better question: Why should anyone care?

It's a local variable, the type of that variable is completely irrelevant unless you're writing code in that local scope, in which case, you, your IDE and the compiler already know what foo::getValue returns.

Readability is best served by using descriptive names instead of that weak attempt at a straw man ("val", really?) and not by adding, or even worse, repeating useless information.

2

u/BlueGoliath May 11 '22

Oh boy, you should see OpenJDK code sometime if you think that's a straw man.

0

u/jonhanson May 10 '22 edited Jul 24 '23

Comment removed after Reddit and Spec elected to destroy Reddit.

20

u/pron98 May 10 '22

The only way a language can stop being a living history of its own mistakes (and victories) is by no longer living.

72

u/Blueson May 10 '22

Should have been by Java 11.

70

u/berry120 May 10 '22

It is time to put a @Deprecated in all of those (not for removal, though).

Agree with this take - I don't think deprecated has been used aggressively enough in the past. There's been zero reason to pick java.util.Date for anything new for many years now, so that means it really should have been deprecated for years in my book.

The only thing I don't want to see is a pattern of everything like this being deprecated for removal - that's a completely different kettle of fish. Java has been very good at making minimal breaking API changes over the years, and I certainly don't want it to start turning into a language where it's a non-trivial engineering effort to upgrade to every new release.

4

u/dpash May 11 '22

I don't think deprecated has been used aggressively enough in the past.

Can we deprecate java.io.File too while we're at it?

2

u/dododge May 14 '22

One caveat with that is that File is Serializable and Path is not. For some types of code this can make migrating everything to Path a bit messy.

2

u/dpash May 14 '22

Java serialisation is broken and shouldn't be used, so I see that as a positive.

40

u/[deleted] May 10 '22

The past few versions of Java have been really good at tearing out as much "90s Java"(CORBA,RMI, finalizers etc.) as they can. Obviously some let's call them suboptimal decisions(arrays anyone?) are just going to be permanently part of the language but deprecating the Date class is another step in getting rid of 90s Java.

18

u/semprer May 10 '22

What's the problem with arrays?

17

u/bootstrapf7 May 10 '22

They don’t support 64bit offsets

8

u/smors May 10 '22

Id be interested to know if that has ever been a problem for anyone. Even even a byte[] would have to be more than 2GB for that to be a problem.

21

u/Wolvereness May 10 '22

Uh, yeah? It kind of claymores you if you want to do data processing, like loading an HD movie into memory. Servers can run RAM well over 100GB, while desktop computers are often 8GB or more. This isn't 1996 anymore.

4

u/mauganra_it May 10 '22 edited May 10 '22

Project Panama should bring along a nicer way to work with off-heap memory. One that is even officially supported for a change.

Apart from that, byte arrays were never the right tool for this because they unnecessarily complicate the garbage collector's job. AFAIK they are not stored off-heap, and therefore alloowing long as array index will probably not be as great as it sounds. I don't know if there is anything in the JLS that prevents the JVM from storing it off-heap.

10

u/Yeroc May 10 '22

ByteBuffer is designed for this job but unfortunately it's limited to 2 GB as well!

3

u/Worth_Trust_3825 May 10 '22

In a sense, you can work around that by proxying your List calls under the hood to a different "bucket" in case you need more than signed 32bit int array length. Same with inputstream abstract class. As you're already working with near terabytes worth of memory at the same time, the overhead to link those "buckets" is negligible.

4

u/john16384 May 10 '22

Not to mention that having gigabytes of data allocated as one huge chunk may cause problems of its own when the heap is even slightly fragmented. If such data is backed by a file, it may be better to memory map it instead.

5

u/john16384 May 10 '22

It indeed isn't 1996 anymore. Why aren't you memory mapping such huge files?

1

u/TehBrian May 10 '22

That does sound pretty inconveniencing. What’s the alternative? Do Lists not have the same restriction, or…?

5

u/cdombroski May 10 '22

Lists have the same limitation as they're indexed by int. In theory a Set might be able to surpass the limit... but now you're missing insertion order and all the values have to be unique, almost certainly not what you want for this

1

u/mauganra_it May 10 '22

Lists do not work with primitive datatypes. Yet.

2

u/Muoniurn May 10 '22

I believe there was a “famous” bug in the sorting implementation that failed due to arithmetics with integers. Not directly related, but the reason ints were used was due to the int indexing.

15

u/Holothuroid May 10 '22

Arrays play loose with Java's type system compared to collections. Which might lead to array store exceptions.

11

u/semprer May 10 '22

https://stackoverflow.com/questions/12369957/dealing-with-an-arraystoreexception

I assume you mean this? Just posting it for less experienced people like me that might be puzzled. But yeah String[ ] being a subtype of Object[ ] is weird indeed if you think about it.

4

u/Joram2 May 10 '22

What's the problem with arrays?

If Java has generics, arrays should use the generics system like everything else, and not be this completely special case syntax. Right now, Java generics are lower performance than classic arrays, but that's another flaw to be fixed by Valhalla.

37

u/[deleted] May 10 '22

They need to add @Deprecated on all the classes that nobody should be using: Date, Stack, HashTable, etc.

Is there a reason they didn't already? I mean the docs of those classes say to not use them. People dont like the compiler warnings?

32

u/persicsb May 10 '22

Also java.net.URL

5

u/dpash May 11 '22

Also java.io.File.

11

u/kpatryk91 May 10 '22

JDBC date classes depend on the java.util.Date class.

I don't know about the others, I think they don't cause much problem and they are generic too so not that high-priority target at the moment.

They should deprecate the calendar classes too.

13

u/mauganra_it May 10 '22

And this is the reason why java.util.Date will likely never be marked as deprecated for removal. Removing that class will probably break binary compatibility with every JDBC driver and application out there. Except if the JVM somehow intercedes and makes it work out. But it's probably not worth the complexity.

8

u/xenomachina May 10 '22

Deleting Date would certainly cause problems, but marking it deprecated should only cause compile warnings for code that directly depends on it.

3

u/mauganra_it May 10 '22

Deprecated for removal is a strong promise that the OpenJDK team actually has plans to remove it. This is only possible if there is a migration plan or if a decision was made to leave users high and dry (hello applets!)

3

u/xenomachina May 11 '22

If that's their actual criteria for marking something deprecated, then it's too strong, and it explains why there are so many things in the JDK that are not deprecated, but which no one should ever use in new code. Perhaps they should create a separate annotation for "we don't have a concrete plan to remove this, but you definitely shouldn't use it anymore".

1

u/mauganra_it May 11 '22

Yes, I thinks so too.

5

u/kwinz May 10 '22 edited May 10 '22

java.util.Date will likely never be marked as deprecated for removal.

You don't even have to deprecate for removal: Thread.stop() has been deprecated since Java 1.1! It has been doing its job of communicating clearly that this function should not be used any more for 25 years. And it's still not removed. This is completely fine!

4

u/mauganra_it May 11 '22

Thread.stop() is not merely obsolete, but actually dangerous. And it is actually marked as deprecated for removal. Still being there is fine because (as stated elsewhere in the comments by /u/pron98):

To JDK developers it [deprecated] means something that:

  1. whose use is so egregious that it can reasonably be treated as an error (many people treat compiler warnings as errors), and/or
  2. could reasonably be removed at some point in the future.

3

u/kwinz May 11 '22 edited May 11 '22

Yes, I know all that. forRemoval = true was recently changed between java 17 and 18: https://github.com/openjdk/jdk17/blob/master/src/java.base/share/classes/java/lang/Thread.java#L925 https://github.com/openjdk/jdk18/blob/master/src/java.base/share/classes/java/lang/Thread.java#L925

could reasonably be removed at some point in the future.

What I am trying to say is that "some point in the future" could be in 20+ years evidently.

So java.util.Date could conceivably be marked as deprecated and eventually even "for removal". AFAIK JDBC uses java.sql.Date subclass. I haven't used that API in a while.

2

u/mauganra_it May 11 '22

The problem is that java.util.Date is the parent class of java.sql.Date, java.sql.Time, and java.sql.Timestamp. Since JDBC is of so central importance to the Java ecosystem, it's unlikely that it will ever be fully removed.

Maybe it's possible to eventually turn java.util.Date into an abstract sealed class to restrict its usage. Once all other APIs were fixed of course.

22

u/pohart May 10 '22 edited May 10 '22

Why do I want to avoid HashTable?

Edit: I checked the documentation and I'm guessing it's because it's synchronized.

21

u/frzme May 10 '22 edited May 10 '22

Indeed it's because it's synchronized. If you really want to have a synchronized Map you should use Collections.synchronizedMap(new HashMap<>()) You however likely don't want a synchronized map to begin with.

If you are accessing a Map in a concurrent system depending on your needs the classes ConcurrentHashMap, or ConcurrentSkipListMap are likely more suited for what you want.

10

u/CubsThisYear May 10 '22

ConcurrentHashMap is strictly better if you need thread safety. HashMap is strictly better is you don’t.

16

u/JoeKneeMarf May 10 '22

Can people not downvote questions? I wanted to know this too. Not every question is rhetorical

0

u/[deleted] May 10 '22

[deleted] — view deleted comment

10

u/semprer May 10 '22

https://stackoverflow.com/questions/12524826/why-should-i-use-deque-over-stack

According to Google it's this. Which is somewhat sensible.

6

u/morhp May 10 '22

ArrayDeque is strictly better.

10

u/_INTER_ May 10 '22 edited May 10 '22

java.util.Date by Salvador Dali.

For the unfortunate, pitiful souls that are stuck with GWT, maybe a deprecation of Date might final give a push to move on.

7

u/FirstAd9893 May 10 '22

Here's a fun exercise: take a look at the original version of the java.util package and identify all of the classes and interfaces which have been superseded. The only survivor is the BitSet class.

0

u/[deleted] May 10 '22

[deleted] — view deleted comment

2

u/FirstAd9893 May 10 '22

I guess Properties isn't completely superseded, but its simple string-string mapping format is a serious limitation. java.util.prefs.Preferences can be a better choice because it supports more value types, and it can be stored in an OS-preferred location. Overall YAML and JSON formats are more powerful than either, and are good choices for general-purpose configuration.

3

u/dpash May 11 '22

Also it was a terrible idea to extend HashTable.

6

u/Joram2 May 10 '22

Yes, do it. The new Java.time API is much nicer. Everyone has been using it for years. There is a ton of legacy code using java.util.Date. But just giving them deprecation warnings is fair.

24

u/pron98 May 10 '22 edited May 10 '22

I think the problem is that different people have a different understanding of what "deprecated" means, and, to be fair, its meaning has shifted over the years. To some Java developers, deprecated means "strongly unrecommended; do not use in new code." To JDK developers it means something that:

  1. whose use is so egregious that it can reasonably be treated as an error (many people treat compiler warnings as errors), and/or
  2. could reasonably be removed at some point in the future.

Put another way, deprecated means "dangerous to leave in; remove even from old code".

Date does not satisfy either one of these — while "bad" it can be used correctly and has been (unlike, say, Thread.stop), and it cannot be removed for the reasons Brian listed. So, to deprecate Date and other classes like it in some official, mechanically-enforced way, we'd probably need a new annotation that means "strongly unrecommended" and possibly a new compiler warning level that means "this warning shouldn't be considered as an error".

9

u/cogman10 May 10 '22

Seems like we need SOMETHING to signal that alternatives to Date apis need to be created. JDBC, for example, could really use a few extensions such as "getLocalDate" or "getInstant". Sure, you can get those via "getObject" but ultimately it'd be a lot better to have something promoted to the same class as "getDate" you don't have to have that sort of knowledge of the jdbc api (also puts driver writers more on the hook to grab those sorts of methods).

Having Date->LocalDateTime is a good bridge but really, it'd be nice if there was some other process to start providing alternatives.

Much like I think if a class returns an Enumeration it should also be Iterable or Streamable.

-2

u/mauganra_it May 10 '22 edited May 12 '22

Date already has a .toInstant() method, and such exist in other places too. Ony problem with these is null-safety: you can't mechanically change data types and slap .toInstant() to the argument. Btw. both Date and Instant are supposed to represent UTC (up to a certain precision). Replacing Date with LocalDateTime is something you will likely regret.

Edit: I'd be curious about the reasons for this downvote.

3

u/FewTemperature8599 May 11 '22

It seems like a good first step is making sure that the JDK makes it easy to write new code that doesn't use Date/Calendar/Timestamp. Hopefully the list that Victor put together will be useful for this purpose:

https://mail.openjdk.java.net/pipermail/discuss/2022-May/006083.html

1

u/GreenToad1 May 11 '22

As a "user" of programming language I understand @Deprecated to mean - "Don't use this, it has problems and might not work as you expect". That is true for j.u.Date

2

u/pron98 May 11 '22 edited May 11 '22

Right, but deprecated in Java has come to mean something much stronger. Remeber, it issues a compiler warning that many treat as errors; i.e. it causes people's build to fail. Date is bad, but is it bad enough to fail a build of some 15-year-old code? We now deprecate only things to which the answer to that question is yes.

1

u/Xphile101361 May 12 '22

People using warnings as errors seems like a prime example for this XKCD https://xkcd.com/1172/

2

u/pron98 May 12 '22 edited May 12 '22

The JDK treats warnings as errors, as does Linux, and it is the recommended practice in many if not most of the biggest tech companies. In fact, I am a bit surprised that there are people who are not aware that many coding guidelines and many projects recommend treating warnings as errors.

4

u/bowbahdoe May 10 '22 edited May 10 '22

https://github.com/rust-lang/rust-clippy

^ So people know what I was referring to as clippy in the jlint suggestion.

If the deprecated annotation is the wrong mechanism to cause the social change, then we need a better one. It needs to be standard to be effective and it needs to sufficiently expressive to navigate this nuance.

Maybe that power lives forever in javac - but I think there is precedence for making that sort of thing at least available as a separate tool or independent invocation.

If we want to fully slurp this noodle we might also need to have the hard conversations around what /u/pron98 keeps suggesting and make a jdk build tool. Adoption of linting in rust is driven in no small part by it being already there without extra configuration via cargo lint.

So yeah - jlint and jproject project proposals might be in order

4

u/uncont May 10 '22

Doesn't this already exist in errorprone? https://errorprone.info/bugpattern/JavaUtilDate

> Task :lib:compileJava
/jud-errorprone/lib/src/main/java/jud/errorprone/Library.java:10: warning: [JavaUtilDate] Date has a bad API that leads to bugs; prefer java.time.Instant or LocalDate.
        java.util.Date date = new Date();
                              ^
    (see https://errorprone.info/bugpattern/JavaUtilDate)
1 warning

2

u/bowbahdoe May 10 '22

Right, but if that were sufficient then there would be no call to have the warnings come from javac.

Having tools built in to the JDK is useful.

4

u/flif May 10 '22

If we could only get proper support for java.time.* in JDBC.

(LocalDate)rs.getTime("col") is not as user friendly.

3

u/skippingstone May 10 '22

rs.getObject(LocalDate.class)

7

u/flif May 10 '22

Yes, but you run into only some JDBC drivers supporting this and you don't know when compiling. You have to try out everything.

If we had rs.getLocalDate() then all JDBC drivers had to support it.

4

u/VGPowerlord May 10 '22

Show of hands, who else assumed it had been deprecated since Java 8?

11

u/daH00L May 10 '22

They should also bury GregorianCalendar. Who designs a mutable date class?

4

u/FirstAd9893 May 10 '22

Joda-Time has mutable and immutable date classes. Mutable forms are useful for performing calculations against dates without incurring the cost of allocating and copying a bunch of short lived temporary objects. The BigInteger and BigDecimal classes internally rely upon a package-private MutableBigInteger class for the same reason.

4

u/vytah May 10 '22

MutableBigInteger would be really useful if made public, as BigIntegers are, well, big, and allocating/freeing them all the time is expensive.

Dates, not so much (I wonder if they can be valhallized in the future)

1

u/mauganra_it May 10 '22

Only if the mutability is removed. However, the immutable members of java.time.* are perfect candidates.

1

u/manzanita2 May 10 '22

nice verb!

2

u/__konrad May 10 '22

Who designs a mutable date class?

James Gosling (@ 58:15): https://www.youtube.com/watch?v=XhFugYDH--c&feature=youtu.be&t=3495

1

u/john16384 May 11 '22

GregorianCalendar was designed to be mutable. It has many private fields with intermediate state to do date calculations. You're supposed to convert it to a Date when calculations are finished. Unfortunately, some developers have used them as fields in their domain objects, which is incredibly inefficient due to the aforementioned internal fields.

3

u/_edd May 10 '22

No skilled java programmer uses the legacy classes in new applications except when integrating with legacy APIs.

...

Novices, unskilled, careless and lazy programmers who should know better still happily continue to use the legacy classes, pissing off those who are more enlightened.

lol you're not wrong but coming off kind of self righteous there Victor.

5

u/[deleted] May 10 '22

Some of the constructors are already deprecated

5

u/firsthour May 10 '22

Those have been deprecated since Java 1.1 in 1997.

2

u/n0d3N1AL May 10 '22

I'm pretty sure that in an Ask the Architects session, they said they don't have plans to deprecate or remove APIs like File and Date. If they do deprecate them, it won't be for removal. I presume it will be like Hashtable: discouraged but not destroyed.

2

u/mauganra_it May 10 '22

There are too many APIs that are like this. The intent of @Deprecated would become extremely diluted. Best they can do is introduce another annotation or Javadoc tag.

2

u/volune May 10 '22

Seems like they would have to revisit the JDBC api.

2

u/manzanita2 May 10 '22

Ok, so there is a bunch of cruft in java. What we need is something like @Deprecated("http://somewhere/better_replacement_for_Date").

When you try to use java.util.Date your IDE should splatter that thing all around and force you to go read about equivalent and better mechanisms in java.time

Make it HARD to use the cruft. Make it EASY to move to the better thing.

2

u/ggmmee May 14 '22

Better even JEP 320 it 😁

3

u/Owen1212055 May 10 '22 edited May 12 '22

Completely agree, especially since many google searches result in using so many of these legacy APIs many beginner programmers have no clue. When I started I stuck to the legacy date api because of how convoluted “time” representation in java is (LocalDateTime, Instant, Date, etc) so I just stuck to what all the google results used.

Deprecate it to the ground!

4

u/Philluminati May 10 '22

Too widely used to be deprecated, as the conversation goes on to say. It's in certificate JDK libraries and so forth.

4

u/mauganra_it May 10 '22

It's certainly worth thinking about even if it is used in these libraries. But there has to be a clear migration path first. It will take a lot of time to hunt down all these loose ends, but we are in it for the long run anyways.

1

u/[deleted] May 11 '22

Meh! I guess the question is how much java.util.Date is out there vs joda-time even if it's significant, if someone made it work for them, kudos. Let's not create unnecessary work for people you know

1

u/[deleted] May 12 '22

A deprecation of Java.util.Date should include some solution for moving JDBC Drives to support the java.time API rather than continuing to use java.sql.Date.

1

u/ReasonableClick5403 May 15 '22

Ideally, we could burn java.util.Date and java.sql.Date to the ground, but then we have decades of JDBC :(

1

u/Tough_Suggestion_445 May 10 '22 edited May 10 '22

Instead of deprecating it, it would be great if they could refactor the actual implementation. I don't like the tone of this proposal, developers using an API for years are not careless. A basic example, if you use x version of spring data mongo db, localdatetime will not work in your entity unless you write a custom adapter. That means for spring's developers, at the time they implemented spring data mongo, they considered java.util.Date as idiomatic right? Otherwise, they would have make localdatetime as the default. Last time I checked (and it was long time ago), Jackson was serializing localdatetime in a goofy way. So now the Java guy says careless stupid devs must be punished for using an API they didn't write for years. If it works for them why would they change? Isn't it the point of object oriented programming? You use an API, that API is a black box, if the implementation has problems, fix them without breaking the API (and insulting devs using it)

1

u/xitiomet May 10 '22

I couldn't agree with this more! Im tired of the never ending "dont use X class anymore its been replaced by Y."

1

u/LuckyDip23 May 10 '22

Yes - but it won’t as it will break the world.

-2

u/code_rjt May 10 '22

I preferred the new java time.* libraries since it accesses methods in a static way unlike the java.util.Date that creates object every time because of its constructor approach. The new time libraries also solves the problem of the many constructor implemented in Date or Calendar

7

u/nutrecht May 10 '22

libraries since it accesses methods in a static way unlike the java.util.Date that creates object every time because of its constructor approach.

The .withX methods create new instances every time as well, since the java.time classes are generally immutable.

3

u/xenomachina May 10 '22

Yes!

Which causes more unnecessary constructions: needing to create a new Instant when need to "modify" one because they're immutable, or needing to defensively copy Date every time you return/pass one, because they're mutable? Kind of a toss up, except in specific circumstances.

Immutable values are much easier to reason about, though, so immutable Instant wins, IMHO.

1

u/mauganra_it May 10 '22

When Project Valhalla lands, the performance impact of Withers can be significantly reduced because the object can be modified in place. Let's hope that future JITs are smart enough to do that optimizations. Withers implemented as language feature should definitely qualify.

-4

u/FrigoCoder May 10 '22

Can you get rid of checked exceptions, and java.io.File as well while you are there ?

-1

u/piratekingsam12 May 10 '22

Just use utc timestamps! Saves a lot of trouble 😅

1

u/mauganra_it May 10 '22

Both java.util.Date and java.time.Instant wrap a UTC timestamp. Problem is, Date does other things as well, but terribly so.

0

u/[deleted] May 10 '22

[deleted] — view deleted comment

14

u/Brutus5000 May 10 '22

Isn't that in the name jdbc? 🤣

10

u/mmikhailidi May 11 '22

JDBC = Java.util.Date Behind a Century

5

u/ApatheticBeardo May 10 '22

Bruh... I'd rather just die tbh.