'new' in JVM -- What happen when 'new' is called? 1st

11
'new' in JVM (1/2) What happen when 'new' is called? Kengo TODA 2012/May/3 1252日水曜日

Transcript of 'new' in JVM -- What happen when 'new' is called? 1st

Page 1: 'new' in JVM -- What happen when 'new' is called? 1st

'new' in JVM (1/2)What happen when 'new' is called?

Kengo TODA 2012/May/3

12年5月2日水曜日

Page 2: 'new' in JVM -- What happen when 'new' is called? 1st

On condition that:

You already know

what is reference

what is memory

what is ‘class file’

12年5月2日水曜日

Page 3: 'new' in JVM -- What happen when 'new' is called? 1st

This code becomes...

public class Test {! public static void main(String[] args) {! ! Test test = new Test();! }}

12年5月2日水曜日

Page 4: 'new' in JVM -- What happen when 'new' is called? 1st

this byte code.

public static void main(java.lang.String[]); Code: 0:! new!#1; //class Test 3:! dup 4:! invokespecial!#16; //Method "<init>":()V 7:! astore_1 8:! return

12年5月2日水曜日

Page 5: 'new' in JVM -- What happen when 'new' is called? 1st

new => 3 opcodes

new dup

new

invokespecial

javac

12年5月2日水曜日

Page 6: 'new' in JVM -- What happen when 'new' is called? 1st

opcode ‘new’

new‘new’ allocates memory(Java heap) to store instance data.

Allocated memory isn’t initialized.

You get a reference to allocated instance.

12年5月2日水曜日

Page 7: 'new' in JVM -- What happen when 'new' is called? 1st

opcode ‘dup’

‘dup’ copies a referencecreated by ‘new’.

dup

12年5月2日水曜日

Page 8: 'new' in JVM -- What happen when 'new' is called? 1st

opcode ‘invokespecial’

‘invokespecial’ invokes <init> method of specified class. <init> is name of constructor.

This opcode consumes a reference, so JVM has to call ‘dup’ at first.

Finally instance is fullyinitialized!

invokespecial

12年5月2日水曜日

Page 9: 'new' in JVM -- What happen when 'new' is called? 1st

Summary

Java heap

instance

1.‘new’

reference3.‘invokespecial’

4.retu

rn

reference2.‘dup’

12年5月2日水曜日

Page 10: 'new' in JVM -- What happen when 'new' is called? 1st

key point

Opcode ‘new’ doesn’t call constructor.

We can get an reference to uninitialized instance.

Data size is fixed at first (by opcode ‘new’).

JVM can decide size from class definition.

We have to create new instance to expand data size. @see ArrayList#grow(int).

12年5月2日水曜日