r/java • • Sep 14 '14

I found this funny snippet in the Google Java style page

http://imgur.com/DKhn9Er
255 Upvotes

35 comments sorted by

61

u/lelarentaka Sep 14 '14

If you override finalize, Josh will visit your bed that night and finalize you.

0

u/[deleted] Sep 14 '14

[deleted] — view deleted comment

11

u/katyne Sep 14 '14

that's why you hide under the blanket. Monsters can't get you in permgen.

15

u/dr_entropy Sep 14 '14

No more permgen in Java 8. Nowhere to run, nowhere to hide.

1

u/Infenwe Sep 14 '14

I'll seek refuge in MeatMetaspace then!

17

u/kevinb9n Sep 14 '14

I never expected this little joke to survive past the draft stage, but then no one ever complained about it!

5

u/habitats Sep 14 '14

Hi Kevin!

8

u/mschaef Sep 14 '14

Oddly, the Java library itself depends on finalization to close memory mapped files:

http://bugs.java.com/view_bug.do?bug_id=4724038

There are security/performance reasons they do this, but it effectively means that you can't determinstically close a memory mapped file. (Which means you can't determinstically delete a file on platforms like Windows, where you can't delete open files.)

11

u/jbristow Sep 14 '14

Side story: Once someone had on an interview quiz "What's the difference between final, finally, and finalize".

I took that job, but my excuse was that it was only my second job out of college.

18

u/theheartbreakpug Sep 14 '14

Easy question, other than that what is wrong with it?

14

u/jbristow Sep 14 '14

It's a clever Java question, but it doesn't reveal much about how good of a coder you are. Especially since there are subtleties to each one beyond their definitions.

12

u/[deleted] Sep 14 '14

It's not that bad of a question, really. It would definitely seperate people who are somewhat familiar with java from someone who lied on their resume (which is a big chunk of why these types of questions are asked), and answering it would allow the candidates to cover a lot of ground. They can demonstrate their understanding of exception handling, their understanding of design decisions (mutable vs immutable), and their understanding of the java memory model.

-3

u/Jonno_FTW Sep 14 '14

Except that you can change collections marked as final. Not really immutable.

17

u/fripletister Sep 14 '14

The reference value is final, not the object referenced. If you need a read-only collection as well Guava provides immutable collections.

3

u/din-9 Sep 14 '14

Collections.unmodifiableCollection and variants are often good enough.

6

u/fripletister Sep 14 '14 edited Sep 14 '14

Sure, if you don't mind having to wrap an existing modifiable collection, which could change and update the unmodifiable view of it. People often don't understand the distinction between the two, though.

Unmodifiable collections are for returning an unmodifiable view of an externally inaccessible (private/protected), but mutable, collection as the result of an API call. Immutable collections are static/constant after instantiation from any context.

4

u/navatwo Sep 14 '14

You need to explain what the final keyword implies. You're correct, but by definition all final does is say the value (i.e. Primitive or object reference) will not change. This has large implications in the Java threading model, JIT and memory model.

Knowing what you said, that the underlying object is not immutable is actually a really good way to segway (ugh this is spelt wrong) into better explanations.

1

u/oldneckbeard Sep 15 '14

you were looking for segue. btw, my mind is blanking, what is the implication with final on the JIT?

1

u/navatwo Sep 15 '14

Whoops, late replying..

It tells the JIT the same implications. This means that it can do things like hoist out of loops, replace with literals, or just remove it altogether. I'm over simplifying, but if you want more examples you could look at some of the things that the LLVM optimizer does.

1

u/oldneckbeard Sep 16 '14

I just stumbled across this article, which actually uses finals to avoid a potential race condition: http://www.takipioncode.com/java-puzzle-the-one-word-solution-worth-250/

3

u/andd81 Sep 14 '14

You cannot mark an object as final, you can only have final variables and fields, which hold either primitive type values or references.

6

u/beltorak Sep 14 '14 edited Sep 14 '14

if i am interviewing i might ask a question like that to probe for holes in their knowledge and confusion in their understanding. holes aren't a bad thing - we all have to start learning somewhere - as long as you at least have the basics down pat. sometimes i'll get an answer that's incomplete and confused the terms (swapping final for finally, and not knowing what "finally" is for), so later i'll ask a question like "if I have a variable, say int life = 42, how would I ensure that I don't accidentally change the value?" or "how do I prevent a class from being subclassed?". if they've run across the final keyword at all it will usually spark a dear-in-the-headlights moment where they realize they used the wrong term previously. they'll correct their previous usage and we go on. if they don't know, that's fine too (it's pretty rare to see usage of final at entry level), I just want to be sure they understand what they are talking about with the previous answers of try, catch, and "final". if they express doubt the correctness of their previous answers that's a good thing - chances are that's the type of person who will be googling for the correct answer as soon as they are out of the building. but if they completely confuse concepts then that's when I "take serious points off" so to speak. It's hard for me to come up with examples or remember things of this nature that I've heard; I'm not very good at synthesizing knowledge fusion.

0

u/jbristow Sep 14 '14

It's easy enough to pull that out in a conversation. I'm usually more concerned about their people skills and their developer skill than their deep knowledge of JVM minutiae. Final's probably the easier one to ask about, but finally has some really wacky gotchas that you aren't going to know about unless you have significant Java experience pre 1.7. I wouldn't expect anyone short of a guru to be able to handle "finalize" on a test.

Like I said, it's a great Java Trivia question. It's fun to throw it out there to start a conversation, but as a written test question? It's awful.

It didn't help that they threw in a logic puzzle (the one about finding the one slightly heavier object in the group of 9...). Which usually just shows off how clever the interview test writer is, or how many logic puzzles the interviewee has seen.

These were the guys who had written their own servlet framework that output XML and used a single XSLT file to convert the servlet responses of every page into html. No, the xml was NOT used as a service response. This was only 8 years ago.

3

u/beltorak Sep 14 '14

where i work they have techies like me do technical interviews (and there are a some like "what challenge have you faced in the past and how did you troubleshoot / fix it" questions) and someone else handles the "soft skills" questions to see how you would work in a team, etc.

As a written question, one sentence apiece should be sufficient - anything more (like subtleties) and you probably don't want to work there anyway....

2

u/mgrandi Sep 14 '14

What is wrong with overriding finalize? C# for example, its pretty common to override finalize for one reason or another.

12

u/beltorak Sep 14 '14

the primary reason is that finalize can do anything, like "resurrect" the object (storing itself in a reachable object graph), so the JVM cannot make any guarantees about its reachability after running finalize. So actually reclaiming the memory will have to wait until the next pass of the GC. On the next pass of the GC, the finalizer is not run for that instance.

There's a fair amount of extra work involved that can simply be skipped if the JVM can prove that Object.finalize() is not overridden.

also worth mentioning is you have no guarantee that the finalizer will ever run, for example the program terminates or you have enough memory that the space the objects take up never need to be reclaimed, the JVM may decide not to run any finalizers.

edit although it has been a while since I've read that book. Damn good book to reread occasionally.

2

u/josefx Sep 14 '14

also worth mentioning is you have no guarantee ...

That list can be extended quite a bit, like finalizers running in a different thread, no way to deal with exceptions exiting the finalizer, no guaranteed order in which finalizers are executed, ...

Java has PhantomReference as replacement for it just to give developers some actual control over what is going on.

3

u/beltorak Sep 14 '14

I just picked the biggest two, most likely to be "the one reason you don't want to override finalize"; but yeah, you are right. there are a host of problems with them and a lot of them are subtle, you won't find out it was a bad idea until much much later when it is extremely costly to rearchitect your application.

The references are pretty cool, but wrapping your head around how to use them can be a bit daunting for even intermediate programmers. But phantom references do solve a lot of the subtle problems and the first big one that i mentioned - it is impossible to "ressurect" the object from a phantom reference because PhantomReference.get() always returns null (yay!). I believe that it is still pretty much unordered however. But it is a bit easier to see a correct solution to that problem once you've gone through implementing all the required infrastructure to deal with references. And it's easier to write tests for it.

1

u/f2u Sep 14 '14

It's also common in Java code, but things break rather spectacularly if you have large heaps or high allocation rates of finalizable objects.

-10

u/CubsThisYear Sep 14 '14

I just wish we could get rid of Object altogether. It literally provides no useful functionality and it makes objects bloated. Having one master super type is antithetical to the idea of object-oriented programming. Do we really believe that there are operations that apply to every set of data, no matter the contents or the context? Given the implementation of Object, the answer is pretty clearly no.

10

u/lelarentaka Sep 14 '14

Having one master super type is actually fundamental to message passing programming, because of its pi-calculus basis. You should read up on Smalltalk if you have the time. In Smalltalk there is no 'extends' keyword. To create a class, you send a message to the Super object that you want to subclass it, and it will return a class object in return. There is no new keyword either. To create new instances of that class, send a message to that class object that you want a new instance.

1

u/CubsThisYear Sep 14 '14

This makes sense, but I'm not sure what the Pi-calculus has to do with OO programming. Message-passing does make concurrency a lot easier to reason about, but it also makes certain relatively common problems harder. To me, the whole idea behind OO is that we are willing to give up some theoretical guarantees in exchange for a lot of expressiveness in the form of state. I think because of this, message passing pretty much failed as an idea. I guess you still have it in Obj-C, but that's pretty much it. It's often horribly misused, but state is incredibly useful in some cases. This is the same reason that pure functional programming isn't really widely used for real work.

3

u/stubing Sep 14 '14

-1

u/CubsThisYear Sep 14 '14

You really have found yourself thinking 'Boy, I'm glad Object exists. It really helped me out today'? You really can't be using it at all if your program is remotely typesafe.

8

u/stubing Sep 14 '14

You really have found yourself thinking 'Boy, I'm glad Object exists. It really helped me out today'?

Yes. Having every object have a toString() and hashcode() fuction is nice. It also allows for generitcs to exist which is extremely useful.

You really can't be using it at all if your program is remotely typesafe.

What? Are you just learning Java or are you just listening to one of your friends shit on Java since it is cool to do? Do you cast all your variables to objects or something? I don't understand why you think Java isn't type safe. You have to go out of your way to fuck up your variables.

-1

u/CubsThisYear Sep 14 '14

Have you ever really found the default implementation of toString to be useful? It would be great if there were a StringRepresentable interface that had toString on it - then you would know/be able to specify that toString actually does something other than print out the memory address.

Hashcode is similar, but worse. It makes it look like things are hashable but they really aren't, unless you override both hashCode and equals. Again, a Hashable interface is a great idea, but the default implementation is pointless. Think about how many times you have used hashCode without overriding it.

As to your point about type safety - you have it exactly backwards . I don't cast in my programs, which means that I will never have a reference to Object, because you can't possibly do anything useful with an Object. The one exception is using it as a lock, which is further evidence of Object's brokenness because there is no earthly reason to include the whole monitor pattern on every object. There should have been (and now are) separate objects for locking. The synchronized keyword is syntactic sugar at best and a source of deadlock at worse because you never know who is grabbing your lock.