Java 엿새째
TmaxSoft R&D Center
1
113년	 10월	 22일	 화
자바 교육 계획
1일 : Language, String,
ClassLoader, Proxy
2일 : GC, Collections
3일 : Thread, Java Memory
Model
4일 : AQS, ForkJoin,
Concurrent Utils
5일 : IO, Generics, Annotation,
RMI
6일 : Unsafe, Lambda (Java 8)
2
내겐 바스켓만 보여 (Flow 상태)
213년	 10월	 22일	 화
오늘 내용
sun.misc.Unsafe
Lambda (Java 8)
3
313년	 10월	 22일	 화
sun.misc.Unsafe
4
413년	 10월	 22일	 화
sun.misc.Unsafe
5
A collection of methods for performing low-level, unsafe operations
park, unpark
direct memory manipulation
provide wrappers for malloc, realloc, free, memset, memcpy
(not Java Heap)
direct object memory manipulation
CAS operations : compareAndSwap
defineClass, defineAnonymousClass
513년	 10월	 22일	 화
Java is not safe with Unsafe
6
can easily corrupt memory
fast serialization
super array (non-Java heap)
allocateMemory(long size)
can cause JVM crash
613년	 10월	 22일	 화
Lambda
7
The	
  issue	
  being	
  debated	
  is	
  not	
  whether	
  closures	
  are	
  a	
  
good	
  idea	
  -­‐	
  because	
  they	
  clearly	
  are	
  -­‐	
  but	
  whether	
  
the	
  benefits	
  of	
  retrofi7ng	
  the	
  Java	
  language	
  with	
  
closures	
  are	
  worth	
  the	
  costs.
-­‐	
  Brian	
  Goetz
713년	 10월	 22일	 화
Functional Programming
8
lambda
anonymous function with a single argument
closure
a block of code that may contain free (unbound)
variables
currying
handling multiple argument function with lambda
function
813년	 10월	 22일	 화
Java 8 Lambda Expression
SAM (single abstract method) of an interface
Java lambda expression
a list of formal parameters and a body—an expression
or block—expressed in terms of those parameters
e.g,
s -> s.toUpperCase()
(int a, int b) -> a + b
9
913년	 10월	 22일	 화
Method Reference expression
method reference : refer to a method without invoking it
System::getProperty
"abc"::length
constructor reference : refer to a constructor without creating
a new instance of the named class or array type
ArrayList::new
int[]::new
e.g, Arrays.sort(myIntegerArray, Integer::compare)
10
1013년	 10월	 22일	 화
Java 8 Closure
For both lambda bodies and inner classes, local
variables in the enclosing context can only be
referenced if they are final or effectively final.
A variable is effectively final if it is never assigned to
after its initialization.
11
1113년	 10월	 22일	 화
Java 8 Currying
Currying :A technique of transforming a multi-argument
function in such a way that it can be called as a chain
of functions, each with a single argument.
12
1213년	 10월	 22일	 화
New Object-oriented feature
mixin
a class which contains a combination of methods
from other classes.
can also be viewed as an interface with implemented
methods.
Mixins encourage code reuse and avoid well-known
pathologies associated with multiple inheritance.
13
1313년	 10월	 22일	 화
Java 8 Default Method
Java’s language addition of mixin-like thing
provides a default implementation for any class that
implements the interface without overriding the
method.
allows new functionality to be added to existing (and
perhaps already widely-distributed) interfaces.
More generally, it provides a mechanism for multiple
inheritance of behavior.
14
1413년	 10월	 22일	 화
Java 8 Changes to Interface
Now, interface method can be default, static and
abstract
all the non-default, non-static methods in the
interface are abstract as before
Default methods of super-interface can be accessed
<InterfaceName>.super.<methodName>()
15
1513년	 10월	 22일	 화
Java 8 Project Lambda
Language Changes
Still, No Function Type
Functional Interface
Default Method
Streams
invokeDynamic
java.util.Spliterator
16
1613년	 10월	 22일	 화
Java Lambda ABC
@interface java.lang.FunctionalInterface
Just a hint for compiler (compile error if does not have
SAM)
any interface which has SAM is functional interface
package java.util.function
lambda function does not create additional classes unlike
anonymous inner classes
it creates a private static lambda method
17
1713년	 10월	 22일	 화
Streams
handle aggregate operations DECLARATIVELY
stream pipeline
1 source : collection, array, generator ftn, IO, ...
0 or more intermediate operations : filter, map, ...
1 terminal operation : forEach, reduce, sum, ...
18
1813년	 10월	 22일	 화
Stages of Streams
txns.stream()
.filter(txn -> txn.getBuyer().getAge() >= 65)
.map(txn -> txn.getSeller())
.distinct()
.sort(comparing(seller -> seller.getName()))
.forEach(seller ->
System.out.println(seller.getName());
19
source
intermediate
intermediate
intermediate
intermediate
terminal
intermediate ops just setup pipeline
and returns new stream
1913년	 10월	 22일	 화
Parallel Streams
A stream pipeline can be created with an orientation of either
serial or parallel
Parallelism may be faster but introduces non-determinism
Internally uses fork-join framework
Collection c = ...;
List r1 = c.stream().map(...).collect(toList());
List r2 = c.parallelStream().map(...).collect(toList());
20
2013년	 10월	 22일	 화
Parallel Streams
21
2113년	 10월	 22일	 화
MethodHandle
java.lang.invoke 패키지
can store references to methods in the constant pool, load
with LDC (load constant)
can obtain a method handle for any method (or field access)
But
MethodHandle invocation performance is not good
Lambda is language level method, MethodHandle is VM
level method
22
2213년	 10월	 22일	 화
Lambda Invocation
desugar implementation method
private static boolean lambda$1(int minAge, Person p) { ... }
lambda metafactory에 MethodHandle argument로 전달
invokeDynamic 호출
Predicate $p = invokedynamic[bootstrap=LambdaMetaFactory, ... ]
moving more work from static compiler to runtime
performance
linkage, capture 비용은 inner class보다 싸지만 invoke 비용은 비싸다!
23
2313년	 10월	 22일	 화
invokeDynamic
invokeStatic
System.currentTimeMillis(), Math.log(1.0)
invokeVirtual
"hello".toUpperCase(), System.out.println()
invokeInterface
myList.add("happy happy"), myRunnable.run()
invokeSpecial (constructor or super call)
new ArrayList(), super.equals(other)
성능 비교
invokeStatic (2.7배) >> invokeDynamic (12.6배) >> reflection
24
2413년	 10월	 22일	 화
다음 시간 예정
JEUS Web Engine
25
여러분의 전성시대는 언제였나요?
2513년	 10월	 22일	 화

Java 8 고급 (6/6)

  • 1.
    Java 엿새째 TmaxSoft R&DCenter 1 113년 10월 22일 화
  • 2.
    자바 교육 계획 1일: Language, String, ClassLoader, Proxy 2일 : GC, Collections 3일 : Thread, Java Memory Model 4일 : AQS, ForkJoin, Concurrent Utils 5일 : IO, Generics, Annotation, RMI 6일 : Unsafe, Lambda (Java 8) 2 내겐 바스켓만 보여 (Flow 상태) 213년 10월 22일 화
  • 3.
    오늘 내용 sun.misc.Unsafe Lambda (Java8) 3 313년 10월 22일 화
  • 4.
  • 5.
    sun.misc.Unsafe 5 A collection ofmethods for performing low-level, unsafe operations park, unpark direct memory manipulation provide wrappers for malloc, realloc, free, memset, memcpy (not Java Heap) direct object memory manipulation CAS operations : compareAndSwap defineClass, defineAnonymousClass 513년 10월 22일 화
  • 6.
    Java is notsafe with Unsafe 6 can easily corrupt memory fast serialization super array (non-Java heap) allocateMemory(long size) can cause JVM crash 613년 10월 22일 화
  • 7.
    Lambda 7 The  issue  being  debated  is  not  whether  closures  are  a   good  idea  -­‐  because  they  clearly  are  -­‐  but  whether   the  benefits  of  retrofi7ng  the  Java  language  with   closures  are  worth  the  costs. -­‐  Brian  Goetz 713년 10월 22일 화
  • 8.
    Functional Programming 8 lambda anonymous functionwith a single argument closure a block of code that may contain free (unbound) variables currying handling multiple argument function with lambda function 813년 10월 22일 화
  • 9.
    Java 8 LambdaExpression SAM (single abstract method) of an interface Java lambda expression a list of formal parameters and a body—an expression or block—expressed in terms of those parameters e.g, s -> s.toUpperCase() (int a, int b) -> a + b 9 913년 10월 22일 화
  • 10.
    Method Reference expression methodreference : refer to a method without invoking it System::getProperty "abc"::length constructor reference : refer to a constructor without creating a new instance of the named class or array type ArrayList::new int[]::new e.g, Arrays.sort(myIntegerArray, Integer::compare) 10 1013년 10월 22일 화
  • 11.
    Java 8 Closure Forboth lambda bodies and inner classes, local variables in the enclosing context can only be referenced if they are final or effectively final. A variable is effectively final if it is never assigned to after its initialization. 11 1113년 10월 22일 화
  • 12.
    Java 8 Currying Currying:A technique of transforming a multi-argument function in such a way that it can be called as a chain of functions, each with a single argument. 12 1213년 10월 22일 화
  • 13.
    New Object-oriented feature mixin aclass which contains a combination of methods from other classes. can also be viewed as an interface with implemented methods. Mixins encourage code reuse and avoid well-known pathologies associated with multiple inheritance. 13 1313년 10월 22일 화
  • 14.
    Java 8 DefaultMethod Java’s language addition of mixin-like thing provides a default implementation for any class that implements the interface without overriding the method. allows new functionality to be added to existing (and perhaps already widely-distributed) interfaces. More generally, it provides a mechanism for multiple inheritance of behavior. 14 1413년 10월 22일 화
  • 15.
    Java 8 Changesto Interface Now, interface method can be default, static and abstract all the non-default, non-static methods in the interface are abstract as before Default methods of super-interface can be accessed <InterfaceName>.super.<methodName>() 15 1513년 10월 22일 화
  • 16.
    Java 8 ProjectLambda Language Changes Still, No Function Type Functional Interface Default Method Streams invokeDynamic java.util.Spliterator 16 1613년 10월 22일 화
  • 17.
    Java Lambda ABC @interfacejava.lang.FunctionalInterface Just a hint for compiler (compile error if does not have SAM) any interface which has SAM is functional interface package java.util.function lambda function does not create additional classes unlike anonymous inner classes it creates a private static lambda method 17 1713년 10월 22일 화
  • 18.
    Streams handle aggregate operationsDECLARATIVELY stream pipeline 1 source : collection, array, generator ftn, IO, ... 0 or more intermediate operations : filter, map, ... 1 terminal operation : forEach, reduce, sum, ... 18 1813년 10월 22일 화
  • 19.
    Stages of Streams txns.stream() .filter(txn-> txn.getBuyer().getAge() >= 65) .map(txn -> txn.getSeller()) .distinct() .sort(comparing(seller -> seller.getName())) .forEach(seller -> System.out.println(seller.getName()); 19 source intermediate intermediate intermediate intermediate terminal intermediate ops just setup pipeline and returns new stream 1913년 10월 22일 화
  • 20.
    Parallel Streams A streampipeline can be created with an orientation of either serial or parallel Parallelism may be faster but introduces non-determinism Internally uses fork-join framework Collection c = ...; List r1 = c.stream().map(...).collect(toList()); List r2 = c.parallelStream().map(...).collect(toList()); 20 2013년 10월 22일 화
  • 21.
  • 22.
    MethodHandle java.lang.invoke 패키지 can storereferences to methods in the constant pool, load with LDC (load constant) can obtain a method handle for any method (or field access) But MethodHandle invocation performance is not good Lambda is language level method, MethodHandle is VM level method 22 2213년 10월 22일 화
  • 23.
    Lambda Invocation desugar implementationmethod private static boolean lambda$1(int minAge, Person p) { ... } lambda metafactory에 MethodHandle argument로 전달 invokeDynamic 호출 Predicate $p = invokedynamic[bootstrap=LambdaMetaFactory, ... ] moving more work from static compiler to runtime performance linkage, capture 비용은 inner class보다 싸지만 invoke 비용은 비싸다! 23 2313년 10월 22일 화
  • 24.
    invokeDynamic invokeStatic System.currentTimeMillis(), Math.log(1.0) invokeVirtual "hello".toUpperCase(), System.out.println() invokeInterface myList.add("happyhappy"), myRunnable.run() invokeSpecial (constructor or super call) new ArrayList(), super.equals(other) 성능 비교 invokeStatic (2.7배) >> invokeDynamic (12.6배) >> reflection 24 2413년 10월 22일 화
  • 25.
    다음 시간 예정 JEUSWeb Engine 25 여러분의 전성시대는 언제였나요? 2513년 10월 22일 화