know your java? - agile developer

47
KNOW YOUR JAVA? speaker.identity { name 'Venkat Subramaniam' company 'Agile Developer, Inc.' credentials 'Programmer', 'Author', 'Trainer' blog 'http://agiledeveloper.com/blog' email '[email protected]' }

Upload: others

Post on 09-Feb-2022

7 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: KNOW YOUR JAVA? - Agile Developer

KNOW YOUR JAVA?

speaker.identity { name 'Venkat Subramaniam' company 'Agile Developer, Inc.' credentials 'Programmer', 'Author', 'Trainer' blog 'http://agiledeveloper.com/blog' email '[email protected]'}

Page 2: KNOW YOUR JAVA? - Agile Developer

Abstract

Java has been around for well over a decade now. It started out with the goal of being simple. Over the years, its picked up quite a bit of features and along comes complexity. In this presentation we will take a look at some tricky features of Java, those that can trip you over, and also look at some ways to improve your Java code. Java features. Set of tricks. Tips to improve your Java code.

2

Page 3: KNOW YOUR JAVA? - Agile Developer

Creating Strings

3

Page 4: KNOW YOUR JAVA? - Agile Developer

Creating Strings

Strings are immutable

"Hello" is already an instance of String

using new on String creates a new redundant instance

Using new to create String is not a good idea

4

Page 5: KNOW YOUR JAVA? - Agile Developer

Comparing Strings

5

Page 6: KNOW YOUR JAVA? - Agile Developer

Comparing Strings

== compares identity—don’t use it to compare Strings

.equals() compares value

6

Page 7: KNOW YOUR JAVA? - Agile Developer

Concatenating Strings

7

Page 8: KNOW YOUR JAVA? - Agile Developer

Concatenating Strings

They both do almost the same thing under the hood

If all you’re doing is concatenating two Strings occasionally like above, first one is sufficient and even better

If you’re concatenating large number of Strings, then consider alternatives

8

Page 9: KNOW YOUR JAVA? - Agile Developer

Concatenating Strings

9

Page 10: KNOW YOUR JAVA? - Agile Developer

Concatenating StringsNeither one

If thread synchronization is not needed, use StringBuilder instead

Go ahead and measure time taken for concatenation for each option

Remember to allocate enough size for StringBuilder

10

Page 11: KNOW YOUR JAVA? - Agile Developer

Object finalize

11

Page 12: KNOW YOUR JAVA? - Agile Developer

Object finalizeFile is not closed, content not written (flushed)

Resource may be held much longer than needed

don’t rely on finalizers

Option 1: provide your own clean up method

12

There’s still a problem here...

Page 13: KNOW YOUR JAVA? - Agile Developer

Object finalizeIn Option 1, you’re under the mercy of caller to call close()

Option 2: Try making it automatic

When Java gets closure, this will become easier, but until then...

13

Resource closed automatically...

There’s still a problem here...

Execute Around Method Pattern

Page 14: KNOW YOUR JAVA? - Agile Developer

Cleanup

14

Page 15: KNOW YOUR JAVA? - Agile Developer

CleanupIf exception is thrown, close() may not be called...

Wrap in try-finally

15

Page 16: KNOW YOUR JAVA? - Agile Developer

equals

16

Page 17: KNOW YOUR JAVA? - Agile Developer

equalsequals() must be symmetric, reflective, and transitive

17

Page 18: KNOW YOUR JAVA? - Agile Developer

equalsensure you’re checking objects of the right type

18

May be a problem if objects in differentcontainers/classloaders. May want to check

for their actual class name?

Page 19: KNOW YOUR JAVA? - Agile Developer

equals...

19

Page 20: KNOW YOUR JAVA? - Agile Developer

equals...

20

Equal objects are required to have equal hashCodes

Page 21: KNOW YOUR JAVA? - Agile Developer

equals...

21

If you override equals, provide hashCode() method

Page 22: KNOW YOUR JAVA? - Agile Developer

static in Generics

22

Page 23: KNOW YOUR JAVA? - Agile Developer

static in Generics

23

Type erasure converts T to Object

All instances of Generics will share the same static

Don’t use static in Generic classes

This becomes clearer if you convert getCount to static and call it as MyList<Integer>.getCount()

Compiler allows only MyList.getCount()

Page 24: KNOW YOUR JAVA? - Agile Developer

static and Inheritance

24

Page 25: KNOW YOUR JAVA? - Agile Developer

static and Inheritance

25

Output from above code is

static methods are not polymorphic

Don’t call static methods on instances

Avoid confusion, only call them on classes

Page 26: KNOW YOUR JAVA? - Agile Developer

static and Threading

26

Page 27: KNOW YOUR JAVA? - Agile Developer

static and Threading

27

count++ is not atomic

If multiple threads invoke constructor at same time, count will be in jeopardy

Does this fix?

Page 28: KNOW YOUR JAVA? - Agile Developer

static and Threading

28

Nope, not effective synchronization

How about?

Page 29: KNOW YOUR JAVA? - Agile Developer

static and Threading

29

Too sweeping

Generally, synchronizing on Class is not a smart idea

If another part of code synchronizes on the same, it limits concurrency

Make synchronization very specific and narrow

Page 30: KNOW YOUR JAVA? - Agile Developer

static and Threading

30

For simple increment operation, use AtomicLong

Page 31: KNOW YOUR JAVA? - Agile Developer

Overriding

31

Page 32: KNOW YOUR JAVA? - Agile Developer

Overriding

32

foo in Derived is hiding foo in Base

Don’t override and change signature

Page 33: KNOW YOUR JAVA? - Agile Developer

Overriding

33

Not all languages (on the JVM) are the same

Try running the above Java code through Groovy!

Groovy’s multimethods produces a different result

//Test.groovy

Page 34: KNOW YOUR JAVA? - Agile Developer

Polymorphism

34

Page 35: KNOW YOUR JAVA? - Agile Developer

Polymorphism

35

Don’t call polymorphic (non-final) methods from within constructors

Page 36: KNOW YOUR JAVA? - Agile Developer

Generics and Interfaces

36

Page 37: KNOW YOUR JAVA? - Agile Developer

Generics and Interfaces

37

ArrayList’s remove looks for index

Collection’s remove looks for object

So, it converts 0 to Integer (which does not exist in list)

Try running the above example through Groovy!

Again Groovy’s multimethod will produce different result

Page 38: KNOW YOUR JAVA? - Agile Developer

It is odd?

38

Page 39: KNOW YOUR JAVA? - Agile Developer

It is odd?

39

% 2 for -ve numbers does not work as you’d expect

instead ask if it is even and negate

Page 40: KNOW YOUR JAVA? - Agile Developer

Computation

40

Page 41: KNOW YOUR JAVA? - Agile Developer

Computation

41

Which language?!

Java reports 0.8999999999999999

Groovy reports 0.9

float and double don’t give you as much accuracy as BigDecimal

Groovy uses that by default

In Java, use BigDecimal for accuracy

Note use of "" instead of new BigDecimal(2.0)

Never use BigDecimal(double) constructor–exact double representation, so in accurate

Page 42: KNOW YOUR JAVA? - Agile Developer

Simple Math?

42

Page 43: KNOW YOUR JAVA? - Agile Developer

Simple Math?

43

Initial value fits in size of int

Final result fits

But intermediate values don’t

Make type large enough to hold intermediate results

Page 44: KNOW YOUR JAVA? - Agile Developer

Simple Addition

44

Page 45: KNOW YOUR JAVA? - Agile Developer

Simple Addition

45

Magnitude of number is too large

As magnitude increases, next representable nearest number if farther away

You can find next nearest number using ulp (unit in the last place)

Page 46: KNOW YOUR JAVA? - Agile Developer

References"Effective Java: Programming Languages Guide," Joshua Block, Addison Wesley, 2001.

"Java Puzzlers: Traps, Pitfalls, and Corner Cases," Joshua Block and Neal Gafter, Addison Wesley, 2005.

"Java Concurrency in Practice," Brian Goetz, Tim Peierls, Joshua Bloch, Joseph Bowbeer, David Holmes, Doug Lea, Addison Wesley, 2006.

"Programming Groovy: Dynamic Productivity for the Java Developer," Venkat Subramaniam, Pragmatic Bookshelf, 2008.

46

You can download examples and slides fromhttp://www.agiledeveloper.com - download

Page 47: KNOW YOUR JAVA? - Agile Developer

Thank You!Please fill in your session evaluations

47

You can download examples and slides fromhttp://www.agiledeveloper.com - download