예외 처리 코드란 : 프로그램에서 예외가 발생 하였을 때 갑작스러운 종료를 막기위해 처리하는 코드.
NullPointerException = 객체 참조가 없을때!
ArrayIndexOutOfBoundsException = 배열에서 인덱스 범위를 초과했을때
NumberFormatException = 문자열인데 숫자로 변경했을때
ClassCastException = 안맞는 타입 변환(casting)을 했을 경우. Instanceof 활용 ok
모든 예외 객체는 exception를 상속하기 때문에 exception에 있는 getMessage 그리고 printStackTrace를 많이 사용한다
getMessage는 오류 메시지를 얻고,
printStackTrace는 오류의 경로를 추적할 때 사용한다
throw는 강제로 예외를 발생하는 것
throws는 예외의 책임을 다른데에 전달하는 것
java.lang안에 있는 클래스는 import할 필요가 없다
object는 자바의 최상위 부모 클래스
object의 equals의 원리는 모든 객체는 object를 상속받아서 비교할 때 자동으로 object타입으로 형변환이된다.
객체 해시코드란 객체를 식별할 하나의 정수값을 말한다.
System은 다 정적으로 이루어져있다
String은 내부 문자열을 수정할 수 없다, 그래서 수정을 할 때 마다 새로운 객체를 생성하는것이며, 메모리에 과부화, 즉 성능 저하가 될 요인이 될 수 있다.
그래서 stringbuilder 그리고 stringbuffer를 사용하는 것이 바람직하다.
Stringbuilder와 stringbuffer의 큰 차이점은 stringbuffer는 multi-thread 환경에서 사용할 수 있도록 동기화가 되었있다.
Calendar은 추상 클래스여서 정적인 getInstance를 통해 생성이가능하다. 그 이유는 각 지역마다 사용하는 시간법이 달라서, 만약 한국인데 la시간을 사용하고 싶다면 TimeZone를 사용하며 된다. TimeZone.getAvailableIDs();를 사용하면 가능한 timezone들이 보인다.
Java.lang.OutOfMemoryError ==not able to use heap because heap is full, NEED TO CHECK FOR MEMORY LEAKS!!!
Garbage collection has 3 steps:
Mark- starts from root node of your application, walks object graph and marks objects that are reachable as live
Sweep/delete – delete unreachable objects, sweeps from heap
Compacting- Arranging everything in order, when unreachable objects are sweeped, there are holes empty places so then compacting comes in and arranges objects in order.
Heap is divided into two spaces, young generation and old(tenured) generation :
Eden space – a place where new objects are created, references to a book of genesis
When eden space is full, that is when minor(small) garbage collector kicks in removes unreachable objects and moves them to survivor space
Survivor space - Having two survivor space prevents compacting step to be used again.
Old generation – a place in heap where long survived objects are stored
Major garabage collector kicks when old generation is almost full, marks, sweep and compacts new and old generation. Application comes to a halt while this is happening.
-XX:MaxTenuringThreshold= how many times object need to survive to be placed into old generation
*Performance*
responsiveness/latency- how quickly an application response with a requested piece of data
ex. If a ui on a web application focuses on responsiveness, large pause times are not acceptable.
Throughput = throughput focuses on maximizing the amount of work by an application in a specific period of time.
Ex. The number of jobs that a batch of program can complete in an hour
The number of database queries that can be completed in an hour
*Type of garbage collectors*
A serial garbage collector – basic garbage collector that runs in a single thread, can be used for basic applications
Pause, runs, pause, runs
A concurrent collector – a thread that performs gc along with application execution as the application runs, does not wait for the old generation to be full – stop the world only during mark/re-mark
A parallel collector - Uses multiple cpus to perform gc. Multiple threads doing mark/sweep etc. does not kick in until heap is full or near full.
Use concurrent collector when(responsiveness/latency)
There is more memory
There is high number of cpus to spare
Application demands short pauses
Use a parallel collector when(throughput!)
Application demands high throughput and can withstand pauses
Most application use concurrent garbage collector because of high responsiveness! Of course!
As of Java 1.7, g1 was introduced
G1 divides heap into small regions. When a certain region has a lot of unreachable objects, gc kicks in. g1 does not care for young or old or eden survivor space.
-Parallelism and concurrency together
-Low pauses with fragmentation
-Better heap utilization
Uptil 1.6, parallelgc was default
1.7 + g1gc is the default
Xmsvalue = setting the minimum value to heap
Xmxvalue = maxium value to heap(default 256)
Xx:newratio=ratio (2means 1/3 Y + 2/3 O(T))
Xx:newsize=sizehow much amount of memory set aside for eden space
Xx:permsizea size assigned to meta-data(static class data etc)
Xx:maxpermsizedef 64m
게임회사에서 면접을 보면서 대답을 못 한 질문이 많았지만 개발자로서 꼭 알아야 하는 이론인데 공부를 하지 않아서 답변 못 했던 질문이 2개였는데 하나가
1. 가비지 컬렉터가 어떻게 돌아가는지
2. Big O에 대해서
전에 자바 메모리 구조 포스트에 올렸듯이 meta-data에는 static 그리고 클래스 자료들이 저장되고, stack 안에서는 local variable들이 저장되면서 객체의 변수도 같이 저장되는데 heap 영역에서 객체의 자료가 저장된다. stack에서는 heap의 참고 주소만 가지고 있어서 만약 heap에서 자료를 참고하지 않으면 가비지 컬렌터가 돌아간다는 까지 알고 있었는데, 힙 영역 안에서 어떻게 작동하는 원리를 물어보셔서 많이 당황한 기억이 난다.
그래서 집에 와서 공부한 게 빅오랑 가비지 컬렉터다.
영어로 배워서 영어로 위에 설명을 적었는데 나중에 면접 가서 설명은 한국말로 해야 해서 간략하게 정리해보겠습니다
가비지 컬렉터는 3가지 단계로 작동을 한다
mark, sweep, compact
힙안에는 new generation 그리고 old generation이 존재한다
new generation 안에는 eden 그리고 2개의 survivor 영역
old generation은 그냥 old generation
가비지 컬렉터는 new generation에 eden이 다 찾을 때 minor garbage collector가 작동하면서 참조 안 되는 객체는 지우면서 참조되는 자료는 survivor 영역으로
만약 오래 존재하는 자료면 old generation으로 이동
old generation 메모리 영역이 거의 다 찼을 때 major gc 발동. major gc는 new와 old다 mark sweep compact 함
이런 식으로 메모리가 정리된다
가비지 컬렉터의 종류는 현재 4가지
원래는 parallel gc 를 default로 사용했지만 1.7 이후부터 g1 gc 사용
g1서부터는 old new generation 구분 없이 영역을 나누어서 해당 영역이 차면 gc 발동, g1이 parallel 그리고 concurrent와 같이 사용하는 느낌
Comparable is a interface you need to implement to a Object where a specific compare standard has to be defined by overriding compareTo method.
compareTo needs to be returned as an int value, + for moving up a list, - for moving down, 0 for staying at the same place.
Wrapper type data does NOT need comparable interface to be compared since all Wrapper class already has been implemented with a Comparable interface. String, char are compared by unicode, numbers are obviously compared by numbers. You could implement Comparable on an object class if standard comparing method does not suit your needs.
Comparator on the other hand is another interface used with purpose of for Collections.sort or Arrays.sort to directly assign comparable standards. anonymous class(?) is assigned on the back of collections.sort or arrays.sort and overrides compare method. the compare method is also an int return method and is same as compareTo method but the difference is number of parameter. compare requires two while compareTo only requires one. This is very simple to understand because you implement comparable to a object class, comparing class variable to parameter while for comparator you do not have a class object to compare to so you need two parameter to be compared.
There are three things to consider when choosing which code to use
1. Time complexity(Big o)
2. Space complexity(How much memory it would consume)
3. Code readability
면접날 빅오 대해서 질문을 받았는데 답변을 못해서 집에서 찾아보니 코드를 선택할 때 세가지 요소가 있다는걸 발견했다.
간단하게 첫번째인 빅오에대해서 설명을 적어보도록 하겠습니다
입출력 상관없이 똑같은 속도를 유지하는 것은 O(1), 파라미터, 값에 변화에 영향을 받지 않고 똑같은 속도(constant complexity) O(n)는 증가하는 값에 따라 같이 변화하는 것, linear complexity ex. for loop O(n^2)는 제일 오래 걸리는 속도, quadratic complexity ex·이중 포문
O(1) = 주방장이 손님 수 상관없이 대량으로 조리해주는 속도
O(log n) = 주방장이 주문들어온 음식들을 한번에 같이 조리해서 주는 속도 O(n) = 주방장이 손님마다 하나의 음식을 조리해서 주는 속도 O(n^2) = 주방장이 각 손님이 한에 모든 요리를 하나씩 다 조리해 주는 속도