여기 없는내용은 스터디 할래 강의 내용 혹은 제가 java Doc보고작성하거나 예제를 만들어 추가했습니다.
그외는 같이 출처가 써있습니다.
제네릭
data type을 클래스, 메소드에서 내부 데이터 타입을 제네릭으로 지정, "컴파일과정에서 문제제거" - jdk1.5 부터 도입 - jdk 1.7 Diamond <>: 타입안에 안써도됨, 타입추론 - 클래스나 메소드 내부에서 사용되는 객체의 타입을 컴파일과정에서 문제제거 - 반환값에 대한 타입변환 및 타입 검사에 들어가는 노력줄인다. - 타입국한 효과로 타입변환이 불필요해져 성능향상효과
----- .java List<Integer> numbers = new ArrayList<>(); numbers.add(3); ------.class List<Integer> numbers = new ArrayList(); numbers.add(3); 컴파일할때 소거자에 대해 타입정보가 사라지는것 > 구체화타입ex) List
제네릭 사용법 제네릭 메소드 만들기
interface fruit<K,V>{ //클래스 public default K getKey() {return null;} public default V getValue() {return null;} } class Banana<K,V> implements fruit<K,V>{ // 상속시
public <T> boolean isBTime(List<T> list, T addvlaue) { //메서드 T value = list.get(0); V[] vArray =(V[]) new Object[2]; // 배열 선언 if (value == addvlaue) return true; return false; } }
매개변수가 반환타입소거시 가끔 브리지메서드를 생성하는데 stackTrace에 가끔 나타나니 알아두기 public class A extends ArrayList<String>{ public boolean add(String e){ return super.add(e) } } A a = new A(); a.add("text"); https://rockintuna.tistory.com/102
여기 없는내용은 스터디 할래 강의 내용 혹은 제가 java Doc보고작성하거나 예제를 만들어 추가했습니다.
그외는 같이 출처가 써있습니다.
I/O
Input & Ouput 입출력 java.io // 데코레이션 패턴으로 만들어짐 : 컴퓨터 내부 또는 외부장치와 프로그램간 데이터 주고받기. ex) 키보드 데이터 입력, System.out.println()
데코레이션패턴
객체의 타입, 메소드 그대로 유지하면서 새로운 책임을 추가할때 사용. 탈부착가능한 책임. 하기 코드 참고. ex) BufferedInputStream 담아 보내면 모아서 보내서 시스템 콜 횟수가 줄어서 성능이익
Stream
스트림이란 데이터를 운반하는데 사용되는 연결 통로. 단방향 통신만 가능. 먼저 보낸데이터 먼저, 중간에 건넘뜀없이 연속적 바이트 단위로 데이터 전송 AutoCloseable(1.7) <-Closeable(1.5) <- InputStream (1.0) <- FileInputStream (1.0) <- OutputStream (1.0) <- FileOutputStream (1.0) InputStream/OutputStream 상속받은 클래스 종류
- FileInputStream / FileOutputStream : 파일 - ByteArrayInputStream / ByteArrayOutputStream : 메모리(Byte배열) > 메모리만써서 close필요없음 - PipedInputStream / PipedOutputStream : 프로세스간 통신 - AudioInputStream / AudioOutputStream :오디오 장치
public abstract class InputStream implements Closeable { public abstract int read() * byte단위 전송, int값을 가져옴- 4byte중 1byte 이용 범위가 0~255 와 -1 이기때문.
public int read(byte b[]) public int read(byte b[], int off, int len) public long skip(long n) // 주어진길이만큼 건너뜀 public int available() //스트림으로부터읽을수 있는 데이터 크기 반환 public void close() // 닫고 사용하던자원반환 public synchronized void mark(int readlimit) //현재 위치 표시. reset에의해 다시돌아감 public synchronized void reset() //스트림위치를 마지막 mark호출된위치 되돌림 public boolean markSupported() // mark reset 기능 제공하는지 확인
OutputStream
OutSteream 의 추상메서드 write() --> writer
public abstract class OutputStream implements Closeable, Flushable {
public abstract void write(int b) 주어진값출력소스에 쓴다. public void write(byte b[]) public void write(byte b[], int off, int len) public void flush() : 스트림의 버퍼에 있는 모든 내용을 출력소스에 쓴다. public void close() : 입력소스 닫음으로써 사용하던 자원반납
Serializable , 파일 읽을때쓸때, 웹에서 데이터 보내고 받을때 줄로보냄. 그때 사용. transient - 직렬화 제외 serialVersionUID = 버전관리,
NIO
New Input / Output 새로운 입출력(jdk1.4) java.nio.channels : 파일채널, TCP, UDT 채널 java.nio.channels.spi java.nio.channels 위한 서비스 제공자. java.nio.charset 문자셋 인코더 디코더 API java.nio.charset.spi java.nio.file 파일 파일시스템 접근위한 서비스 java.nio.file.attribute 속성접근 java.nio.file.spi java.nio.buffer ... 입출력방식은 IO는 스트림 NIO 는 채널방식 : 스트림은 매번 생성, 채널은 만들필요없음 버퍼 방식은 IO 넌버퍼, NIO 는 버퍼 : IO는 넌버퍼라서 bufferedInputStream 연결사용 비동기방식 IO 지원안함 , NIO 지원 : 프로킹/넌블로킹 IO 블로킹방식만 지원 : 동기, NIO 블로킹/넌블로킹 모두 지원 블로킹(대기상태): IO는 인터럽트안되나 NIO는 가능 넌블로킹(쓰레드가 입출력시 블로킹안됨) * NIO 전 FileReader 사용했음. FileWriter 사용 추천.
Buffer
읽고 쓰기가 가능한 메모리 배열(일반) 데이터를 전송하는 상호간 장치에서 OS system core (저속)와 java api호출(고속) 장치간의 속도차이로 인해 저속 장치가 작업을 추리하는 동안 기다리는 현상 줄어짐 buffer는 사이즈 지정이 가능, 효율관런 고려 가능
package java.nio; public abstract class Buffer (1.4)) 버퍼에 담았다 한번에 모아서 보냄. 입출력 횟수 줄어 성능이점 ByteBuffer, CharBuffer, DoubleBuffer, FloatBuffer, IntBuffer, LongBuffer, ShortBuffer 할당: 바이트버퍼.allocatedDirect(크기); - 다이렉트 Direct : 운영체제 관리 메모리공간 :생성시간 느림, 한번생성재사용, IMDG 참고 바이트버퍼.allocated(크기); - 넌다이렉트 NonDirect : JVM 관리 힙 메모리 공간. :생성시간은빠름, 큰크기사용힘듬 https://docs.oracle.com/javase/7/docs/api/java/nio/Buffer.html
Channel
파일, 소켓, 데이터그램등과 같은 I/O소스로부터 데이터 블록을 버퍼로 쓰거나 읽음. - Socket과 연결, 입출력 역할 수행 - 입력과 출력을 동시 수행 - Selector와 연결, 하나Selector에 다수 채널 존재 - Blocking 스레드 깨우거나 다시 Blocking할수 있다. 기존 IO 에서 쓰레드에 Reader, Writer만 존재해 Reader로 블로킹, Writer로 블로킹풀어줌 NIO 에서 Non-blocking방식, 쓰레드 -버퍼사이 터널을 만들어주는데 이것이 채널하는역할 package java.nio.channels; public interface Channel extends Closeable { https://adrian0220.tistory.com/150
selector
java NIO에서 하나의 쓰레드에 여러개 연결이 있어 Selector를 이용해 어떤채널과 연결 선택, 선택된 채널이 스레드와 버퍼 연결 진행하는게 NIO 매커니즘.
java.lang.Annotation 구현 from Bytecode 장점 : 유효성검사등 명시 , AOP 을 쉽게 구성할 수 있게해준다. 용도 : 문서화, 컴파일러 체크, 코드 분석 자동생성, 런타임 프로세싱 완전히 정적이어야 한다. final.
빌트인 어노테이션
Java에 내장되어 있는 어노테이션, 컴파일러를 위한 어노테이션 @Override @Deprecated @SuppressWarning 개발자가 의도를 가지고 만들었는데 컴파일이 알지못하고 경고를 띄울수있어 제거하는목적 @SafeVarargs jdk7 제네릭 같은 가변인자 매개변수 사용시 경고 무시 @FunctionalInterface
메타 어노테이션
어노테이션 정의 하기 위해 사용 @Retention, @Target, @Documented, @Inherited, @Repeatable
@Retention
어노테이션 LIfe Time 적용범위 public enum RetentionPolicy { SOURCE, // 소스파일에만 존재, 클래스파일존재 안함 CLASS, // 클래스파일에만 존재, 런타임유지 필요없음 // default : class RUNTIME // 클래스파일에도 존재하고 런타임에 VM에 의해 유지, ==> 리플렉션 정보읽기가능 } // 정말 Runtime 설정이 필요한 정보인가? 리플렉션 XXXController.class.getAnnotation(); XXXController.class.getDeclardAnnotations();//클래스에 정의되어 있는것만
어노테이션 정보 javaDoc 작성된 문서에 포함. 생성된문서가 어노테이션인지 여부가 차이가남.
@Inherited
부모에 이설정이 있는 어노테이션이 있으면 자식도 같이 씀. (하기 예시참조)
@Repeatable
어노테이션을 반복적으로 선언할 수 있게 하는 어노테이션
애노테이션 프로세서
어노테이션을 프로세싱 하는기술. 컴파일타임에 어노테이션들을 프로세싱하는 javac에 속한 빌드 툴로 어노테이션 소스코드를 분석하고 처리하기 위해 사용되는 훅. - 보일러플레이트코드 제거하는데 도움이 된다. : AbstractProcessort 구현하여 만들고 getter/setter 컴파일타임에 만들어서 보일러 플레이트 코드 제거.
marker annotation
메서드 선언 없는 인터페이스 ex) Serializable, Cloneable public interface Serializable { }
어노테이션 에노테이션 에너테이션 어너테이션
책추천:
아웃라이어... 1만시간....
부의 추월차선.....사업. 5일을 노예처럼일하고. 노예처럼일하기위해 2일을 쉰다.
XDoclet 엑스닥렛 java5.... 에노테이션 전신
ServiceLoader : JAR 파일에 포함된 구성 파일을 읽어서 인터페이스 구현을 찾고, 구현을 선택한 오브젝트의 목록으로 사용.
serviceLoader.load(XXXX.class)
@Inherited
package study;
import java.lang.annotation.Annotation;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface InheritedAnnotation {
}
@Retention(RetentionPolicy.RUNTIME)
@interface notInherit{
}
@InheritedAnnotation
class A {}
@notInherit
class B {}
class AA extends A {}
class BB extends B {}
class test{
public static void main(String[] args) {
Class AAClass = AA.class;
Class BBClass = BB.class;
Annotation[] AAAnnotations =AAClass.getAnnotations();
for (int i = 0; i < AAAnnotations.length; i++) {
System.out.println(AAAnnotations[i]);
}
Annotation[] BBAnnotations =BBClass.getAnnotations();
for (int i = 0; i < BBAnnotations.length; i++) {
System.out.println(BBAnnotations[i]);
}
}
}
public int getStartTime() { return this.startTime; }
public int getEndTime() { return this.endTime; } }
내부 static
values() vs valueOf()
values : 선언 상수를 배열로 반환, 컴파일되며 생김 valueOf : enum 존재 상수를 가져올때. 상속 받음, jdk8기준 없으면 illegalArgumentException
ordinal()
TODAY_TIME.AFTERNOON.ordinal() //1 ordinal 서수 , enum 클래스에 나열된 상수가 몇번째 나열되어있는지. zero base 로 넘버링 한 위치를 반환. EnumSet, EnumMap 에서 사용.. 내부용
java.lang.Enum
enum 은 java.lang.Enum 클래스 상속받음. - 아래 바이트 코드 참고. 생성자 : Sole constructor : 컴파일러 사용, 사용자 직접 호출사용불가. /** * Sole constructor. Programmers cannot invoke this constructor. * It is for use by code emitted by the compiler in response to * enum type declarations. * * @param name - The name of this enum constant, which is the identifier * used to declare it. * @param ordinal - The ordinal of this enumeration constant (its position * in the enum declaration, where the initial constant is assigned * an ordinal of zero). */ protected Enum(String name, int ordinal) { this.name = name; this.ordinal = ordinal; }
쓰레드.setPriority(int newPriority) public final static int MIN_PRIORITY = 1; //최소 public final static int NORM_PRIORITY = 5; //기본값 public final static int MAX_PRIORITY = 10; //최대
동기화 : 여러개의 쓰레드가 한 개의 리소스를 사용하려고 할 때 사용 하려는 쓰레드를 제외한 나머지 접근못하게 함. (Thread-safe)
구현 - Synchronized 키워드 : 동기화블록, 메소드 선언시, 메소드내 특정 문장 감싸기 범위가 좁게 사용하는것을 추천. 그래서 동기화블록사용이 적합.. - Atomic 클래스: java.util.concurrent : 여러쓰레드 접근해도 원자적 접근 데이터 구조 ,한쓰레드씩 접근사용. - Volatile 키워드 : java 변수를 메인메모리 저장 명시, multi thread 환경 cpu cache값 불일치 문제 때문에 사용. ,한쓰레드씩 접근사용.
Lock
jdk1.5 락. : 상호 배재를 사용할수 있는 클래스 제공 package java.util.concurrent.locks; public interface Lock { void lock(); // 잠근다. void lockInterruptibly() throws InterruptedException; boolean tryLock(); boolean tryLock(long time, TimeUnit unit) throws InterruptedException; void unlock(); //해지한다. Condition newCondition(); } lock구현체 - ReentrantLock : 재진입가능, 가장일반적임 - ReentrantReadWriteLock : 읽기공유가능 쓰기 lock - StampedLock : ReentrantReadWriteLock 에 기능추가.
DeadLock
교착상태 둘 이상의 쓰레드가 lock 을 획득하기 위해 대기 하는데 대기하는 쌍방이 우위를 가리수 없어 어느쪽도 진행되지 않는상태(block)
Thread 1 rocks A, waits for B Thread 2 locks B, waits for A
동시성 vs 병렬성
concurrency programming model, : 동시성 프로그래밍 모델 ex_자바쓰레드
Parallelism programing model : 병렬성 프로그래밍 모델 - critical path : 동시 실행 하는것중 가장 긴거.. 이것을 줄여야 수행시간이 줄다. ---- ----------- ---- ----------------- ----- ------- --------- ------------- -------- race condition: 어떻게 접근하느냐에 따라 결과가 달라지는 경우.
추천책 : 자바 병렬프로그래밍...이출판사 번역신경쓰니참고.
thread.. 서버 수준 구현 할때만 필요. ex) tomcat
톰캣 최종분석...톰캣을 만들어봄.... ㅋㅋㅋOTL
요즘 컨테이너는 NIO Connector 사용...
동시 프로그래밍 모델: concurrency programing model
- 예 자바 쓰레드, Actor Model -아카..., STM(Software Trancsaction memory)- closer
당시 actor가 가장빠름. contention 이 없어서.. 자원충돌날것이 없음.
동시성 vs 병렬성
free lunch is over
: CPU 클럭속도 한계가 와서 더많은 코어를 잘쓸수있는 방향으로. >>멀티쓰레딩 패러다임이 바뀌고 있다.
무어의 법칙이... 주춤해짐...년 혹은 18개월마다 반도체의 집적도는 2배가 된다
Volatile 볼레틸 휘발성
Thread, runnable 구현
package study;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ThreadExample {
public static void main(String[] args) {
Thread byThread = new ThreadByThread();
byThread.start();
Runnable runnable = new ThreadByRunnable();
Thread byRunnable = new Thread(runnable);
//byRunnable.run();
byRunnable.start();
Lock lock= new ReentrantLock();
}
public static void print(String threadInfo , int num){
for (int i =0; i<100;i++)
System.out.println(threadInfo + " | " + num);
}
}
class ThreadByThread extends Thread{
@Override
public void run() {
ThreadExample.print(Thread.currentThread().getName(), 1);
}
}
class ThreadByRunnable implements Runnable{
@Override
public void run() {
ThreadExample.print(Thread.currentThread().getName(),0);
}
}
강사님 설명소스.
package study;
public class ThreadExample {
public static void main(String[] args) {
Thread byThread = new ThreadByThread();
byThread.start();
new Thread(()->ThreadExample.print(Thread.currentThread().getName(), 0)).start();
}
public static void print(String threadInfo , int num){
for (int i =0; i<100;i++)
System.out.println(threadInfo + " | " + num);
}
}
class ThreadByThread extends Thread{
@Override
public void run() {
ThreadExample.print(Thread.currentThread().getName(), 1);
}
}
예외 발생시 발생메서드의 Stack Trace를 모두 메모리에 담고있어야함>> 비용 예외처리로 비즈니스로직 처리 피하는 이유 로직으로 할수 있는것은 예외던지는것보다 값을 리턴하는게 비용적으로 이득.
try - catch - finally
catch 여러 줄일때 상속관계 인지 주의 할것. 상위 상속관계가 뒤에 finally 안에 return 을 쓰는 것은 anti 패턴. finally에 리턴이 있음 try 리턴작동안함.
e.printStackTrace
로그로 출력하면 안되는 정보들 주의 -개인정보
Multicatch블록
JDK 1.7, 역시 부모자식관계 주의 try{ }catch(예외1 | 예외2 | 예외3 e) { }
메서드체이닝
여러 메서드 호출을 연결해 하나의 실행문 표현. Init init = new Init(); init.set1(1); init.set2(2); init.set3(3); 메서드 체이닝 : init.set1(1).set2(2).set3(3); - setN메서드의 리턴값으로 this를 반환 해서 만듬.
try-with-resource
-알아서 close처리. finally 생략 가능해짐 --컴파일코드 보면 다중 try catch 문이 생기고 catch 블록에서 Throwble로 잡아 close를 해줌. 마지막에도 close()호출. (아래 컴파일 전후 확인) 메이븐 >라이프사이클>컴파일> 타켓 폴더 생성 해당 class파일 확인
@Cleanup -lombok
close를 호출해줌. 알고만있고 try-with -resource.로~
트랜젝션
스프링 기본 트랜젝션 전략에서... 설정을 확인할필요. 기본적으로 Checekd Exception은 Rollback 하지 않고 unchecked Exception 은 Rollback됨.
java9 File의 private static String slashify(String path, boolean isDirectory) { String p = path; if (File.separatorChar != '/') p = p.replace(File.separatorChar, '/'); if (!p.startsWith("/")) p = "/" + p; if (!p.endsWith("/") && isDirectory) p = p + "/"; return p; }
자바 8 이후 추상클래스
자바8 , 9 기준 인터페이스 에서 못하는부분이 남아있음.
public abstract class AbstractJoinMember { private String message ="" public void setMessage(String message){ } }
인터페이스 구현불가 : private 상수. 자바8기준 private 안됨.
Constant Interface
안티패턴임. 사용하지 마세요~ 1. 상수포함하여 모두 가져오고 계속가지고있음 2. 컴파일때 사용 런타임때 용도없음 3. 이진호환성을 필요로할때 계속유지 4. IDE가 없으면 상수 implement한 클래스에서 상수 사용할 때 네임스페이스 사용하지 않음 네임스페이스도 인터페이스 상수들로 오염 5. 인터페이스 구현해 클래스를 만드는 것은 클라이언트에게 알리는 행위... 혼동 6. 의도치 않은 현상 발생 https://jessyt.tistory.com/78
안티패턴
소프트웨어 공학 분야 용어이며, 실제 많이 사용되는패턴이지만 비효율적이거나 비생산적인패턴을 의미한다.
둘다 or javac or java >> 둘다 쓸수 있다. cf) maven pom.xml scop- runtime, provied.. 의존성설정 관련되어있다고함.
클래스 로더.
java 에 3가지 기본 클래스 로더 존재 Bootstrap class loader : 최상위 클래스 로더, jre/lib/rt.jar 에 담긴 JDK 클래스 파일 로딩 : 원시 클래스 로더 : Primordial ClassLoader Extension class loader : jre/lib/ext , java.ext.dirs 로 지정된 클래스파일 로딩. Application class loader : classpath 나 jar 파일 안에 있는 Manifest파일의 class-path 속성값으로 지정된 폴더의 클래스 로딩 : 자가 애플리케이션 구동을 위해 직접 작성한 대부분클래스는 애플리케이션 클래스 로더에 의해로딩
동작 3원칙 1. 위임 : 클래스 로딩 작업을 상위 클래스 로더 위임 2. 가시범위 원칙 : 하위클래스 로더 상위클래스로더 볼수 있지만 상위는 하위클래스로더 로딩 볼수없음 3. 유일성 원칙 : 하위 클래스로더는 상위 클래스 로더가 로딩한 클래스를 다시로딩하지 못함
여기 없는내용은 스터디 할래 강의 내용 혹은 제가 java Doc보고작성하거나 예제를 만들어 추가했습니다.
그외는 같이 출처가 써있습니다.
자바상속 특징
다중상속 금지 : extends A, B X 최상위 클래스 Object
디스패치
프로그램이 어떤 메소드를 호출할 것인가를 결정하여 그것을 실행하는 과정. - 동적 디스패치 - 정적 디스패치
Static Dispatch 정적 디스패치
어떤 메소드 실행될지 컴파일시점에서 알수 있음. static class Do{ void run(){} void run(int number){} } Do.run(); <<< 정적디스패치는 ... 메소드 오버로딩의 경우.
Dynamic Method Dispatch 동적 디스패치
컨파일타임에 알수 없는 메서드 의존성을 런타임에 늦게 바인딩 abstract class Do{ void run(){} } class MoningDo extends Do{ @Overried void run(){ System.out.println("1"); } } class EveningDo extends Do{ @Overried void run(){ System.out.println("2"); } } EveningDo ed = new EveningDo(); ed.run() <<<<< 컨파일때는 알수 없고, 런타임때 알수 있다. 바이트코드 : imvokvirtual : 동적디스패치 cf) 바이트코드 : imvorkspecial : 생성자 호출.
더블 디스패치
동적 디스패치 두번 발생 - 방문자 패턴: visitor partten 더블 디스패치 사용한 대표적 패턴. interface Post{ void postOn(SNS sns); } class Text implements Post{ public void postOn(Sns sns){ sns.post(this);} } class Picture implements Post{ public void postOn(Sns sns){ sns.post(this);} } --------------------------- POST 구현하는클래스2개 postOn 생성. interface SNS{ void post(Text text); void post(Picture picture); } class Facebook implements SNS{ public void post(Text text){} public void post(Picture Picture){} } class Twitter implements SNS{ public void post(Text text){} public void post(Picture Picture){} } --------------------------상기 상속받은 클래스를 매개변수로 쓰는 SNS 상속클래스 2개
public static void main(String[] args) { List<Post> posts = Arrays.asList(new Text(), new Picture()); List<SNS> sns = Arrays.asList(new Facebook(), new Twitter()); posts.forEach(p -> sns.forEach(s -> p.postOn(s))); //1. 어떤 구현체의 PostOn. 2. 어떤 SNS의 post : 두번발생. } 출처 : https://blog.naver.com/swoh1227/222181505425
방문자 패턴
visitor pattern - SAX Parser (cf _DOM Parser)
final
class variable method
Object 클래스
clone: 해당객체 복제본생성 finalize() 해당객체 더는 아무도 참조지 않아 GC 호출함 notify() 해당객체 대기하고 있는 스레드 다시실행 할때 호출 wait() notify, notifyall 메소드 호출전까지 현재 스레드 일시적 대기.
varargs
가변인자, 변수의 마지막선언 내부적으로 배열로 받음. String... message == String[] message ------------------- void sum (String A, String...str){} void sum (String...str){} 컴파일에러. ------------------ var = variable args = 아그 독립변수. 변수 독립변수.
public class Object {
private static native void registerNatives();
static {
registerNatives();
}
public final native Class<?> getClass();
public native int hashCode();
public boolean equals(Object obj) {
return (this == obj);
}
protected native Object clone() throws CloneNotSupportedException;
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
public final native void notify();
public final native void notifyAll();
public final native void wait(long timeout) throws InterruptedException;
public final void wait(long timeout, int nanos) throws InterruptedException {
if (timeout < 0) {
throw new IllegalArgumentException("timeout value is negative");
}
if (nanos < 0 || nanos > 999999) {
throw new IllegalArgumentException(
"nanosecond timeout value out of range");
}
if (nanos > 0) {
timeout++;
}
wait(timeout);
}
public final void wait() throws InterruptedException {
wait(0);
}
protected void finalize() throws Throwable { }
}
여기 없는내용은 스터디 할래 강의 내용 혹은 제가 java Doc보고작성하거나 예제를 만들어 추가했습니다.
그외는 같이 출처가 써있습니다.
LinkedList vs ArrayList
Vactor: Java1.0 시작 생성시 capacity 10로 정해져 10개씩 늘어남. thread에 대한 접근 동기화 보장 성능이슈 Java1.2 : List 인터페이스 대체 Collections.synchronizedList(List<T> list); // Thread-safe 가필요할 때사용. ArrayList :내부적으로 데이터를 배열에서 관리, 추가 삭제를 위해 임시배열을 생성 데이터 복사 *** 대량의 자료를 추가/삭제 하는 경우 그만큼 데이터의 복사가 많이 일어나 성능저하 *** 반면 각 데이터는 인덱스를 가지고 있기 때문에 한번에 참조가 가능 검색에는 유리 LinkedList: 데이터를 저장하는 각 노드가 이전 노드와 다음 노드의 상태만 알고 있다. ***추가 삭제 유리하지만 검색시 처음부터 노드를 순회해야함 성능상 불리
접근제어자
public 동일클래스, 동일패키지, 자손클래스, 그외의 영역 protected 동일클래스 , 동일패키지, 자손클래스 (default) 동일클래스, 동일 패키지 >>자바파일안 클래스 동등두개 선언시 파일명 다른것. private 동일클래스
초기화블럭 vs 생성자
public class Init { private int number; private static int staticNum; {System.out.println("초기"); } static {System.out.println("정적초기");} public Init(){ System.out.println("생성");} public static void main(String[] args) { Init init = new Init(); } } // 정적초기 > 초기 > 생성
this()
생성자에서 다른생성자 호출. public Init(){} public Init(String start){ this(); } - this() 는 숨어있지않음, super()만 숨어있음 - this() 호출은 첫줄에서
기본생성자
선언하지 않아도 기본생성자 자동생성 변수가 들어간 생성자가 생기면 기본생성자를 자동 생성하지 않음
final
public final class String :: 상속 막을 때 상속이 적절하지 않을때 :: 특수한 String이 생겨버림.
abstract
public abstract class Init ::인스턴스 생성막을 떄
Nested Class
중첩클래스 : 클래스 내부 다른클래스 1. static nested class 2. inner class
static nested class
public class Outer { public static class Nested { } }
InnerClass
inner class >> Outter 호출후 사용. public class OuterClass{ static class StaticNestedCalss{} class InnerClass{ class InnerInnerClass{} } } >>컴파일시 클래스파일 각각 3개 생성 OuterClass$InnerClass$InnerInnerClass.class OuterClass$InnerClass.class OuterClass.class
Local class
코드블럭 안에 정의된 클래스. 특정메소드 내에서만 필요한 객체가 필요할때 public class Main{ public static boolean methodExample(String... values){ Class Value{ } } }
Anonymous class
익명클래스= 이름없는 클래스 클래스의 정의와 인스턴스화를 한번에 작성. 인스턴스 구현, 추상클래스상속한 처리 부분적이용.
상기링크 참조 import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method Class carClass = Car.class; Method move = carClass.getMethod("move"); move.invoke(obj, null); import java.lang.reflect.Field; Field[] fields = Class.forName("java.com.whiteship.demo.Init").getDeclaredFields(); 리플렉션을 사용하기 때문에 실제 Exception이 일어날 수 없어 Exception 처리를 용이하기 위함입니다. >>리플렉션 사용예 .https://woowabros.github.io/experience/2020/10/08/excel-download.html
Heap 메모리
Heap 자료구조를 쓰기 때문. _ 완전이진트리. 항상 위의값이 아랫값보다 큼. min Heap , max Heap
java8 변화
추상클래스가 없어지고 인터페이스+디폴트메소드로 옮겨가고 있음. 인터페이스 : 규약. 토비스프링3. ..참고.
여기 없는내용은 스터디 할래 강의 내용 혹은 제가 java Doc보고작성하거나 예제를 만들어 추가했습니다.
그외는 같이 출처가 써있습니다.
Error : A JNI error has occurred, ....(중략).... version of the Java Runtime (class file version 53.0), this version of the Java Runtime only recognizes class file versions up to 52.0 at java.lang
C:\Program Files\Java\jdk1.8.0_144\bin>javac
Usage: javac <options> <source files>
where possible options include:
-g Generate all debugging info
-g:none Generate no debugging info
-g:{lines,vars,source} Generate only some debugging info
-nowarn Generate no warnings
-verbose Output messages about what the compiler is doing
-deprecation Output source locations where deprecated APIs are used
-classpath <path> Specify where to find user class files and annotation processors
-cp <path> Specify where to find user class files and annotation processors
-sourcepath <path> Specify where to find input source files
-bootclasspath <path> Override location of bootstrap class files
-extdirs <dirs> Override location of installed extensions
-endorseddirs <dirs> Override location of endorsed standards path
-proc:{none,only} Control whether annotation processing and/or compilation is done.
-processor <class1>[,<class2>,<class3>...] Names of the annotation processors to run; bypasses default discovery process
-processorpath <path> Specify where to find annotation processors
-parameters Generate metadata for reflection on method parameters
-d <directory> Specify where to place generated class files
-s <directory> Specify where to place generated source files
-h <directory> Specify where to place generated native header files
-implicit:{none,class} Specify whether or not to generate class files for implicitly referenced files
-encoding <encoding> Specify character encoding used by source files
-source <release> Provide source compatibility with specified release
-target <release> Generate class files for specific VM version
-profile <profile> Check that API used is available in the specified profile
-version Version information
-help Print a synopsis of standard options
-Akey[=value] Options to pass to annotation processors
-X Print a synopsis of nonstandard options
-J<flag> Pass <flag> directly to the runtime system
-Werror Terminate compilation if warnings occur
@<filename> Read options and filenames from file
C:\Program Files\Java\jdk1.8.0_144\bin>java
사용법: java [-options] class [args...]
(클래스 실행)
또는 java [-options] -jar jarfile [args...]
(jar 파일 실행)
여기서 options는 다음과 같습니다.
-d32 사용 가능한 경우 32비트 데이터 모델을 사용합니다.
-d64 사용 가능한 경우 64비트 데이터 모델을 사용합니다.
-server "server" VM을 선택합니다.
기본 VM은 server입니다..
-cp <디렉토리 및 zip/jar 파일의 클래스 검색 경로>
-classpath <디렉토리 및 zip/jar 파일의 클래스 검색 경로>
클래스 파일을 검색할 ;(으)로 구분된 디렉토리,
JAR 아카이브 및 ZIP 아카이브 목록입니다.
-D<name>=<value>
시스템 속성을 설정합니다.
-verbose:[class|gc|jni]
상세 정보 출력을 사용으로 설정합니다.
-version 제품 버전을 인쇄한 후 종료합니다.
-version:<value>
경고: 이 기능은 사용되지 않으며
이후 릴리스에서 제거됩니다.
실행할 버전을 지정해야 합니다.
-showversion 제품 버전을 인쇄한 후 계속합니다.
-jre-restrict-search | -no-jre-restrict-search
경고: 이 기능은 사용되지 않으며
이후 릴리스에서 제거됩니다.
버전 검색에서 사용자 전용 JRE를 포함/제외합니다.
-? -help 이 도움말 메시지를 인쇄합니다.
-X 비표준 옵션에 대한 도움말을 인쇄합니다.
-ea[:<packagename>...|:<classname>]
-enableassertions[:<packagename>...|:<classname>]
세분성이 지정된 검증을 사용으로 설정합니다.
-da[:<packagename>...|:<classname>]
-disableassertions[:<packagename>...|:<classname>]
세분성이 지정된 검증을 사용 안함으로 설정합니다.
-esa | -enablesystemassertions
시스템 검증을 사용으로 설정합니다.
-dsa | -disablesystemassertions
시스템 검증을 사용 안함으로 설정합니다.
-agentlib:<libname>[=<options>]
<libname> 고유 에이전트 라이브러리를 로드합니다(예: -agentlib:hprof).
-agentlib:jdwp=help 및 -agentlib:hprof=help도 참조하십시오.
-agentpath:<pathname>[=<options>]
전체 경로명을 사용하여 고유 에이전트 라이브러리를 로드합니다.
-javaagent:<jarpath>[=<options>]
Java 프로그래밍 언어 에이전트를 로드합니다. java.lang.instrument를 참조하십시오.
-splash:<imagepath>
이미지가 지정된 스플래시 화면을 표시합니다.
자세한 내용은 http://www.oracle.com/technetwork/java/javase/documentation/index.html을 참조하십시오.
바이트코드 Bytecode
특정 하드웨어가 아닌 가상 컴퓨터에서 돌아가는 실행 프로그램을 위한 이진 표현법이다.
클래스파일 안에 들어있음.
컴파일러에 의해 변환되는 코드명령어(opcode, operator code) 크기가 1바이트
Project Loom : 프로젝트 Loom에서는 자바의 Thread를 개선해서 Virtual Thread라는 것을 제공할 것으로 보이며 Structured 동시성(Concurrency) (코드의 구조 자체가 컨커런시를 제어하는 시작과 끝을 나타내는 것) 를 제공하는게 목표라고 하네요.