java - Why is 'create' asynchronous? -
i told, creating new instance async message; don't understand why.
e.g.:
foo myfoo = new foo();
here have wait until constructor finishes , returns new object. doesn't asynchronous mean, go on independently (no waiting) - starting thread?
i told, creating new instance async message;
sorry, have either heard wrong or told wrong. first off, should terminology straight. term "async" or "asynchronous" means invocation returns immediately caller. can demonstrate not true constructor, simple experiment [1]. in other words, constructor must return caller make progress.
starting thread indeed asynchronous. call thread.start()
returns , @ later point in time thread starts running , executing run()
method.
1 experiment
consider class (for illustration only) below:
foo.java
class foo { foo() throws interruptedexception { while (true) { system.out.println("not returning yet ..."); thread.sleep(2000); } } public static void main(string[] args) throws interruptedexception { foo foo = new foo(); } }
if compiled , run class (i used java 8 on mac, not requirement). expected, class runs forever producing output every 2 seconds:
not returning yet ... not returning yet ... not returning yet ... not returning yet ...
note sleep
call added make bearable. try experiment without it, program overwhelm 1 of cpu's stressing 100%.
if, while running, took thread dump (for example, using command jstack
), see below (curtailed brevity):
"main" #1 prio=5 os_prio=31 tid=0x00007f9522803000 nid=0xf07 waiting on condition [0x000000010408f000] java.lang.thread.state: timed_waiting (sleeping) @ java.lang.thread.sleep(native method) @ foo.<init>(foo.java:5) @ foo.main(foo.java:9)
regardless of state of thread (runnable, blocked, waiting, timed_waiting
), see (take various thread dumps see means) see these 2 lines:
@ foo.<init>(foo.java:5) @ foo.main(foo.java:9)
which means caller (in case, main thread
) never make progress. , since constructor never returns, no progress happens.
Comments
Post a Comment