Java 닷새째
TmaxSoft R&D Center
1
113년	 10월	 18일	 금
자바 교육 계획
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
213년	 10월	 18일	 금
오늘 내용
Review : some more concurrent collections
Generics
Annotation
I/O
Object Serialization
3
313년	 10월	 18일	 금
지난 시간 리뷰 :
ForkJoin framework
Concurrent Collections
4
413년	 10월	 18일	 금
Fork/Join Task의 review (1)
5
ForkJoinPool.invoke(rootTask)
rootTask.join : unpush myself, exec, getRawResult
ForkJoinPool.invokAll(childTask1, childTask2)
childTask2.fork : push task, signal worker
childTask1.invoke : exec -> invokeAll or direct-calc, join
childTask2.join : unpush(pop) task, exec, getRawResult
513년	 10월	 18일	 금
Fork/Join Task review (2)
6
20
base top
deque thread 1
thread 2
thread 3
...
• Parallelism of ForkJoinPool is the maximum
active thread count (excluding the blocked
threads)
• work-steal occurs when the thread tries to join
613년	 10월	 18일	 금
Fork/Join Task review (2)
6
20
18
base top
deque
fork
thread 1
thread 2
thread 3
...
• Parallelism of ForkJoinPool is the maximum
active thread count (excluding the blocked
threads)
• work-steal occurs when the thread tries to join
613년	 10월	 18일	 금
Fork/Join Task review (2)
6
20 19
18
base top
deque
fork
thread 1exec
thread 2
thread 3
...
• Parallelism of ForkJoinPool is the maximum
active thread count (excluding the blocked
threads)
• work-steal occurs when the thread tries to join
613년	 10월	 18일	 금
Fork/Join Task review (2)
6
20 19
18
base top
deque
fork
thread 1
17
exec
thread 2
thread 3fork
...
• Parallelism of ForkJoinPool is the maximum
active thread count (excluding the blocked
threads)
• work-steal occurs when the thread tries to join
613년	 10월	 18일	 금
Fork/Join Task review (2)
6
20 19
18
base top
deque
fork
thread 1
17
thread 2
thread 3fork
exec18
...
• Parallelism of ForkJoinPool is the maximum
active thread count (excluding the blocked
threads)
• work-steal occurs when the thread tries to join
613년	 10월	 18일	 금
Concurrent Collections
CopyOnWriteArrayList : read-mostly, high contention
LinkedBlockingQueue : 2-lock queue algorithm
separation of takeLock and putLock
ConcurrentHashMap
lock striping
no lock when get (multiple access to volatile data)
ConcurrentSkipListMap
concurrent version of skip-list
a concurrent replacement for TreeMap
7
713년	 10월	 18일	 금
ConcurrentSkipListMap
8
813년	 10월	 18일	 금
Generics
9
913년	 10월	 18일	 금
Generics
10
Parameterized types
Type erasure (Generics는 VM type이 아님)
Generic instance creation (따라서 ... 골치아픔!)
Wildcards
Generic type declaration using wild card (?)
extends and super
Generic Class/Interface
Generic Method
Runtime Generics : Class<T>를 사용
1013년	 10월	 18일	 금
Generics and Array
Generic Array Creation is not allowed
Component type of an array cannot be used as a
generic type
Only unbounded wild card is allowed
new List<String>[10] : ERROR
new List<?>[10] : OK
Array type is OK as a generic type
<T> T[] toArray(T[] t) : OK
11
1113년	 10월	 18일	 금
Bridge Method
make override work in even Generics
e.g, compareTo(Byte byte) -> compareTo(Object obj)
make parametric return work in Generics
e.g, Object next() -> Integer next()
make covariant override work in Generics
e.g, Cloneable T clone()
12
1213년	 10월	 18일	 금
Annotations
13
1313년	 10월	 18일	 금
Annotating Additional
Information
14
AnnotatedElement interface
Class, Constructor, Field, Method, Package
Value types of Annotations
primitive types, String, Class, enum types, annotation
types, or arrays of the preceding types
이외의 다른 일반 객체는 value type이 될 수 없음
1413년	 10월	 18일	 금
Annotation Declaration
/** multiple member annotation */
public @interface MyAnnotationType {
int someValue();
String someOtherValue();
String yesSomeOtherValue() default "[blank]";
}
/** single member annotation */
public @interface Copyright { String value(); }
/** marker annotation (no member) */
@Target(value=METHOD)
@Retention(value=SOURCE)
public @interface Override {}
15
각 @interface는 java.lang.annotation.Annotation을
extends한 interface로 컴파일됨.
1513년	 10월	 18일	 금
Annotating code
@ClassLevelAnnotation(arg1="val1", arg2={"arg2.val1","arg2.val2"})
public class AnnotationExample {
@FieldLevelAnnotation()
public String field;
@ConstructorLevelAnnotation()
public AnnotationsTest() {
// code
}
@MethodLevelAnnotationA("val")
@MethodLevelAnnotationB(arg1="val1",arg2="val2")
public void someMethod(String string) {
// code
}
}
16
1613년	 10월	 18일	 금
Using Annotation information
Use java.lang.reflect.AnnotatedElement interface
methods
boolean isAnnotationPresent(Class<? extends
Annotation> annotationType);
<T extends Annotation> T getAnnotation(Class<T>
annotationType);
Annotation[] getAnnotations();
Annotation[] getDeclaredAnnotations();
17
1713년	 10월	 18일	 금
Retention
3가지 값
enum RetentionPolicy : SOURCE, CLASS, RUNTIME
SOURCE, CLASS : 런타임에 자바 코드에서 볼 수 없음
SOURCE : 컴파일러만 참고하고 bytecode에는 정보를 만들지 않음
CLASS : bytecode에 정보를 만드나, JVM이 class load할 때
discard함 (기본값. surprise!)
RUNTIME : 런타임에 자바 코드에서 reflection을 통해 값을 가져올 수
있음
18
1813년	 10월	 18일	 금
Built-in Annotations
java.lang.Override - METHOD/SOURCE
java.lang.Deprecated - .../RUNTIME
java.lang.SuppressWarning - .../SOURCE
java.lang.annotation.Documented – ANNOTATION_TYPE/
RUNTIME
java.lang.annotation.Inherited – ANNOTATION_TYPE/RUNTIME
java.lang.annotation.Retention - ANNOTATION_TYPE/RUNTIME
value: RetentionPolicy.SOURCE/CLASS(default)/RUNTIME
java.lang.annotation.Target - ANNOTATION_TYPE/RUNTIME
value: ElementType.TYPE/FIELD/METHOD/PARAMETER/
CONSTRUCTOR/LOCAL_VARIABLE/ANNOTATION_TYPE/
PACKAGE
19
1913년	 10월	 18일	 금
I/O
20
2013년	 10월	 18일	 금
Stream IO
21
java.io package
Byte Streams
In/OutputStream
Character Streams
Reader/Writer
InputStreamReader
OutputStreamWriter
Layered Streams
FilterIn/OutputStream
FilterReader/Writer I/O device
Input Stream Output Stream
BufferedInputStream BufferedOutputStream
Application
DataInputStream DataOutputStream
2113년	 10월	 18일	 금
NIO
java.nio package (NIO represents Non-blocking IO)
Buffer Processing
0 <= mark <= position <= limit <= capacity
reset(), clear(), flip(), rewind()
Position(), limit(), mark(), capacity()
BufferUnderflowException on get
BufferOverflowException on put
InvalidMarkException on reset
Channel : FileChannel, SocketChannel, ...
Selector
Why Buffer Processing?
Multiplexing/Nonblocking
File IO
Locks and memory-map
22
2213년	 10월	 18일	 금
NIO Direct Buffer
ByteBuffer.allocateDirect
Java Heap에 할당하지 않고, 그냥 malloc을 호출 (native heap에 할당)
내부적으로 page 크기 단위로 align해서 할당 (JDK 6까지, JDK 7부터는 요청한
크기만 할당)
불필요하게 과다 할당 가능성 (특히 large page size 사용시)
-XX:MaxDirectMemorySize=<size> : direct memory 최대 크기 지정 VM 옵션
FileChannel, SocketChannel 등에서 read/write 시에 내부적으로 direct buffer 사용
일반 buffer일 경우 임시 direct buffer를 생성하여 복사
direct buffer는 Java Heap이 아니므로 바로 native call 가능
23
2313년	 10월	 18일	 금
Object Serialization
24
2413년	 10월	 18일	 금
Object Serialization
25
Serializable/Externalizable
transient/serialPersistentFields
readObject/writeObject
readExternal/writeExternal
Versioning : serialVersionUID
2513년	 10월	 18일	 금
resolveClass
ObjectInputStream.resolveClass(ObjectStreamClass desc)
어떤 클래스로더를 사용해서 deserialize할 것인가?
private static native ClassLoader latestUserDefinedLoader();
the first non-null class loader up the execution stack, or
null if only code from the null class loader is on the stack
ObjectInputStream 클래스를 로드한 클래스로더는 null이므로
보통 readObject 를 호출한 클래스가 스택 상 첫번째 non-null
클래스로더에 의해 로드되었을 것임
26
2613년	 10월	 18일	 금
RMI class resolution
sun.rmi.server.MarshalOutputStream
overrides ObjectOutputStream.annotateClass(Class)
writeLocation(java.rmi.server.RMIClassLoader.getClassAnnota
tion(cl));
sun.rmi.server.MarshalInputStream
overrides ObjectInputStream.resolveClass(ObjectStreamClass)
RMIClassLoader.loadClass(codebase, className,
defaultLoader)
defaultLoader is null or latestUserDefinedLoader()
27
2713년	 10월	 18일	 금
다음 시간 예정
sun.misc.Unsafe
invokeDynamic
Lambda (Java 8)
28
2813년	 10월	 18일	 금

Java 8 고급 (5/6)

  • 1.
    Java 닷새째 TmaxSoft R&DCenter 1 113년 10월 18일 금
  • 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 213년 10월 18일 금
  • 3.
    오늘 내용 Review :some more concurrent collections Generics Annotation I/O Object Serialization 3 313년 10월 18일 금
  • 4.
    지난 시간 리뷰: ForkJoin framework Concurrent Collections 4 413년 10월 18일 금
  • 5.
    Fork/Join Task의 review(1) 5 ForkJoinPool.invoke(rootTask) rootTask.join : unpush myself, exec, getRawResult ForkJoinPool.invokAll(childTask1, childTask2) childTask2.fork : push task, signal worker childTask1.invoke : exec -> invokeAll or direct-calc, join childTask2.join : unpush(pop) task, exec, getRawResult 513년 10월 18일 금
  • 6.
    Fork/Join Task review(2) 6 20 base top deque thread 1 thread 2 thread 3 ... • Parallelism of ForkJoinPool is the maximum active thread count (excluding the blocked threads) • work-steal occurs when the thread tries to join 613년 10월 18일 금
  • 7.
    Fork/Join Task review(2) 6 20 18 base top deque fork thread 1 thread 2 thread 3 ... • Parallelism of ForkJoinPool is the maximum active thread count (excluding the blocked threads) • work-steal occurs when the thread tries to join 613년 10월 18일 금
  • 8.
    Fork/Join Task review(2) 6 20 19 18 base top deque fork thread 1exec thread 2 thread 3 ... • Parallelism of ForkJoinPool is the maximum active thread count (excluding the blocked threads) • work-steal occurs when the thread tries to join 613년 10월 18일 금
  • 9.
    Fork/Join Task review(2) 6 20 19 18 base top deque fork thread 1 17 exec thread 2 thread 3fork ... • Parallelism of ForkJoinPool is the maximum active thread count (excluding the blocked threads) • work-steal occurs when the thread tries to join 613년 10월 18일 금
  • 10.
    Fork/Join Task review(2) 6 20 19 18 base top deque fork thread 1 17 thread 2 thread 3fork exec18 ... • Parallelism of ForkJoinPool is the maximum active thread count (excluding the blocked threads) • work-steal occurs when the thread tries to join 613년 10월 18일 금
  • 11.
    Concurrent Collections CopyOnWriteArrayList :read-mostly, high contention LinkedBlockingQueue : 2-lock queue algorithm separation of takeLock and putLock ConcurrentHashMap lock striping no lock when get (multiple access to volatile data) ConcurrentSkipListMap concurrent version of skip-list a concurrent replacement for TreeMap 7 713년 10월 18일 금
  • 12.
  • 13.
  • 14.
    Generics 10 Parameterized types Type erasure(Generics는 VM type이 아님) Generic instance creation (따라서 ... 골치아픔!) Wildcards Generic type declaration using wild card (?) extends and super Generic Class/Interface Generic Method Runtime Generics : Class<T>를 사용 1013년 10월 18일 금
  • 15.
    Generics and Array GenericArray Creation is not allowed Component type of an array cannot be used as a generic type Only unbounded wild card is allowed new List<String>[10] : ERROR new List<?>[10] : OK Array type is OK as a generic type <T> T[] toArray(T[] t) : OK 11 1113년 10월 18일 금
  • 16.
    Bridge Method make overridework in even Generics e.g, compareTo(Byte byte) -> compareTo(Object obj) make parametric return work in Generics e.g, Object next() -> Integer next() make covariant override work in Generics e.g, Cloneable T clone() 12 1213년 10월 18일 금
  • 17.
  • 18.
    Annotating Additional Information 14 AnnotatedElement interface Class,Constructor, Field, Method, Package Value types of Annotations primitive types, String, Class, enum types, annotation types, or arrays of the preceding types 이외의 다른 일반 객체는 value type이 될 수 없음 1413년 10월 18일 금
  • 19.
    Annotation Declaration /** multiplemember annotation */ public @interface MyAnnotationType { int someValue(); String someOtherValue(); String yesSomeOtherValue() default "[blank]"; } /** single member annotation */ public @interface Copyright { String value(); } /** marker annotation (no member) */ @Target(value=METHOD) @Retention(value=SOURCE) public @interface Override {} 15 각 @interface는 java.lang.annotation.Annotation을 extends한 interface로 컴파일됨. 1513년 10월 18일 금
  • 20.
    Annotating code @ClassLevelAnnotation(arg1="val1", arg2={"arg2.val1","arg2.val2"}) publicclass AnnotationExample { @FieldLevelAnnotation() public String field; @ConstructorLevelAnnotation() public AnnotationsTest() { // code } @MethodLevelAnnotationA("val") @MethodLevelAnnotationB(arg1="val1",arg2="val2") public void someMethod(String string) { // code } } 16 1613년 10월 18일 금
  • 21.
    Using Annotation information Usejava.lang.reflect.AnnotatedElement interface methods boolean isAnnotationPresent(Class<? extends Annotation> annotationType); <T extends Annotation> T getAnnotation(Class<T> annotationType); Annotation[] getAnnotations(); Annotation[] getDeclaredAnnotations(); 17 1713년 10월 18일 금
  • 22.
    Retention 3가지 값 enum RetentionPolicy: SOURCE, CLASS, RUNTIME SOURCE, CLASS : 런타임에 자바 코드에서 볼 수 없음 SOURCE : 컴파일러만 참고하고 bytecode에는 정보를 만들지 않음 CLASS : bytecode에 정보를 만드나, JVM이 class load할 때 discard함 (기본값. surprise!) RUNTIME : 런타임에 자바 코드에서 reflection을 통해 값을 가져올 수 있음 18 1813년 10월 18일 금
  • 23.
    Built-in Annotations java.lang.Override -METHOD/SOURCE java.lang.Deprecated - .../RUNTIME java.lang.SuppressWarning - .../SOURCE java.lang.annotation.Documented – ANNOTATION_TYPE/ RUNTIME java.lang.annotation.Inherited – ANNOTATION_TYPE/RUNTIME java.lang.annotation.Retention - ANNOTATION_TYPE/RUNTIME value: RetentionPolicy.SOURCE/CLASS(default)/RUNTIME java.lang.annotation.Target - ANNOTATION_TYPE/RUNTIME value: ElementType.TYPE/FIELD/METHOD/PARAMETER/ CONSTRUCTOR/LOCAL_VARIABLE/ANNOTATION_TYPE/ PACKAGE 19 1913년 10월 18일 금
  • 24.
  • 25.
    Stream IO 21 java.io package ByteStreams In/OutputStream Character Streams Reader/Writer InputStreamReader OutputStreamWriter Layered Streams FilterIn/OutputStream FilterReader/Writer I/O device Input Stream Output Stream BufferedInputStream BufferedOutputStream Application DataInputStream DataOutputStream 2113년 10월 18일 금
  • 26.
    NIO java.nio package (NIOrepresents Non-blocking IO) Buffer Processing 0 <= mark <= position <= limit <= capacity reset(), clear(), flip(), rewind() Position(), limit(), mark(), capacity() BufferUnderflowException on get BufferOverflowException on put InvalidMarkException on reset Channel : FileChannel, SocketChannel, ... Selector Why Buffer Processing? Multiplexing/Nonblocking File IO Locks and memory-map 22 2213년 10월 18일 금
  • 27.
    NIO Direct Buffer ByteBuffer.allocateDirect JavaHeap에 할당하지 않고, 그냥 malloc을 호출 (native heap에 할당) 내부적으로 page 크기 단위로 align해서 할당 (JDK 6까지, JDK 7부터는 요청한 크기만 할당) 불필요하게 과다 할당 가능성 (특히 large page size 사용시) -XX:MaxDirectMemorySize=<size> : direct memory 최대 크기 지정 VM 옵션 FileChannel, SocketChannel 등에서 read/write 시에 내부적으로 direct buffer 사용 일반 buffer일 경우 임시 direct buffer를 생성하여 복사 direct buffer는 Java Heap이 아니므로 바로 native call 가능 23 2313년 10월 18일 금
  • 28.
  • 29.
  • 30.
    resolveClass ObjectInputStream.resolveClass(ObjectStreamClass desc) 어떤 클래스로더를사용해서 deserialize할 것인가? private static native ClassLoader latestUserDefinedLoader(); the first non-null class loader up the execution stack, or null if only code from the null class loader is on the stack ObjectInputStream 클래스를 로드한 클래스로더는 null이므로 보통 readObject 를 호출한 클래스가 스택 상 첫번째 non-null 클래스로더에 의해 로드되었을 것임 26 2613년 10월 18일 금
  • 31.
    RMI class resolution sun.rmi.server.MarshalOutputStream overridesObjectOutputStream.annotateClass(Class) writeLocation(java.rmi.server.RMIClassLoader.getClassAnnota tion(cl)); sun.rmi.server.MarshalInputStream overrides ObjectInputStream.resolveClass(ObjectStreamClass) RMIClassLoader.loadClass(codebase, className, defaultLoader) defaultLoader is null or latestUserDefinedLoader() 27 2713년 10월 18일 금
  • 32.