클래스 안에서 클래스끼리 비교할 때 override해두면 Collections.sort, Arrays.sort 등에서 사용됨
하나뿐인 아래 함수를 상속받고 구현하면 됨, 구현해야지만 사용할 수 있음(not functional interface)
public int compareTo(T o);
해당 함수로 현재 객체(this)와 다른 객체(o)를 비교할 수 있으며 반환 값은 아래와 같음
this < o : -1 정방향
this == o : 0
this > o : 1 역방향
참고로 String 객체는 해당 interface의 함수를 이미 구현하고 있어서 별도의 설정을 하지 않아도 알파벳 순 정렬을 할 수 있다.
String.java
import java.util.*;
@Getter
@ToString
@AllArgsConstructor
public class Person implements Comparable<Person> { ///
private String name;
private int age;
@Override
public int compareTo(Person other) { ///
return Integer.compare(this.age, other.age); // Natural order by age
}
// Main method for testing
public static void main(String[] args) {
List<Person> people = Arrays.asList(
new Person("Alice", 30),
new Person("Bob", 25),
new Person("Charlie", 35)
);
// Sort using the natural order defined by Comparable
// 안줘도 자동으로 있는거 사용
Collections.sort(people);
System.out.println("Sorted by age (natural order): " + people);
}
}
Comparator Interface
Comparator is intended to be used for defining external comparison logic rather than internal natural ordering. However, you can create a Comparator for Person as a separate class, an inner class, or even as a static field in the Person class to provide custom sorting criteria.
객체 자체의 natural ordering 이 없거나, 좀 더 복잡한 정렬 방법이 있을 경우 사용(flexibility)
아래 함수를 상속받고 구현하면 됨(functional interface) ; 람다로 사용가능
int compare(T o1, T o2);
int를 반환하도록 되어있는데, 비교 값은 아래와 같다.
앞 < 뒤 : -1 정방향
앞 == 뒤 : 0
앞 > 뒤 : 1 역방햐
String 객체에 역시 이미 정의 되어 있다.
String.java
기본함수
Comparator<T> reversed():
Returns a comparator that reverses the order of this comparator.
Comparator<T> thenComparing(Comparator<? super T> other):
Returns a comparator that first compares using this comparator, and if the comparison is equal, uses the provided comparator. 앞에 비교한 결과가 같으면 추가 사용!
import java.util.*;
@Getter
@ToString
@AllArgsConstructor
public class Person { //여기서 comparator implement못하고 별도의 클래스로 빼야 함
private String name;
private int age;
// Main method for testing
public static void main(String[] args) {
List<Person> people = Arrays.asList(
new Person("Alice", 30),
new Person("Bob", 25),
new Person("Charlie", 35)
);
// Sort by name
// 별도로 만들어서 사용 , 람다 사용가능
Comparator<Person> nameComparator = Comparator.comparing(Person::getName);
Collections.sort(people, nameComparator);
System.out.println("Sorted by name: " + people);
// Sort by age in reverse order
Comparator<Person> ageComparator = Comparator.comparingInt(Person::getAge).reversed();
Collections.sort(people, ageComparator);
System.out.println("Sorted by age (reverse order): " + people);
}
}
//or 아래처럼 함수로 빼고 new AgeComparator() 삽입
// Comparator for sorting by age
public static class AgeComparator implements Comparator<Person> {
@Override
public int compare(Person p1, Person p2) {
return Integer.compare(p1.getAge(), p2.getAge());
}
}
어떤 것을 사용해야 하나
The Comparable interface is a good choice to use for defining the default ordering, or in other words, if it’s the main way of comparing objects.
Synchronization: Use the synchronized keyword to ensure that only one thread can access a critical section of code at a time. This helps prevent race conditions where multiple threads might try to modify shared data simultaneously.
Locks: Java provides various lock implementations like ReentrantLock, ReadWriteLock, and StampedLock which offer more flexibility and functionality compared to intrinsic locks (synchronized). They llow finer control over locking mechanisms and can help avoid deadlock situations.
Thread-safe data structures: Instead of using standard collections like ArrayList or HashMap, consider using their thread-safe counterparts from the java.util.concurrent package, such as ConcurrentHashMap, CopyOnWriteArrayList, and ConcurrentLinkedQueue. These data structures are designed to be safely accessed by multiple threads without external synchronization.
Atomic variables: Java's java.util.concurrent.atomic package provides atomic variables like AtomicInteger, AtomicLong, etc., which ensure that read-modify-write operations are performed atomically without the need for explicit locking.
Immutable objects: Immutable objects are inherently thread-safe because their state cannot be modified once created. If an object's state needs to be shared among multiple threads, consider making it immutable.
멀티 스레드 환경에서 안전하게 코딩하는 기본적인 다섯가지 방법에 대해 살펴본다. 자바 기준
1. synchronized 키워드 사용(직접적인 락은 아니지만 락과 같은 것; monitor lock)
함수 자체 그리고 함수 안에서도 블락으로 지정하여 사용 가능
allowing only one thread to execute at any given time.
The lock behind the synchronized methods and blocks is a reentrant. This means the current thread can acquire the same synchronized lock over and over again while holding it(https://www.baeldung.com/java-synchronized)
2. 명시적으로 lock interface를 구현한 구현체를 사용
lock()/tryLock() 함수로 락을 걸고 unlock()함수로 반드시 락을 해제해야한다.(아니면 데드락..)
Condition 클래스를 통해 락에 대한 상세한 조절이 가능
ReentrantLock implements Lock
synchronized와 같은 방법으로 동시성과 메모리를 핸들링하지만 더 섬세한 사용이 가능하다.
ReentrantReadWriteLock implements ReadWriteLock
Read Lock– 쓰기락이 없거나 쓰기락을 요청하는 스레드가 없다면, 멀티 스레드가 락 소유 가능
Write Lock– 쓰기/읽기 락 모두가 없는 경우 반드시 하나의 스레드만 락을 소유한다.
ConcurrentHashMap, ConcurentLinkedQueue, ConcurrentLinkedDeque 등
ConcurrentHashMap: This class is a thread-safe implementation of the Map interface. It allows multiple threads to read and modify the map concurrently without blocking each other. It achieves this by dividing the map into segments, each of which is independently locked.
CopyOnWriteArrayList: This class is a thread-safe variant of ArrayList. It creates a new copy of the underlying array every time it is modified, ensuring that iterators won't throw ConcurrentModificationException. This makes it suitable for scenarios where reads are far more frequent than writes.
ConcurrentLinkedQueue: This class is a thread-safe implementation of the Queue interface. It is designed for use in concurrent environments where multiple threads may concurrently add or remove elements from the queue. It uses non-blocking algorithms to ensure thread safety.
BlockingQueue: This is an interface that represents a thread-safe queue with blocking operations. Implementations like LinkedBlockingQueue and ArrayBlockingQueue provide blocking methods like put() and take() which wait until the queue is non-empty or non-full before proceeding.
ConcurrentSkipListMap and ConcurrentSkipListSet: These classes provide thread-safe implementations of sorted maps and sets, respectively. They are based on skip-list data structures and support concurrent access and updates.
4. thread safe 한 변수 사용
java.util.concurrent.atomic 패키지 참고(from java 5)
AtomicInteger, AtomocLong, AtomicBoolean 등
스레드 끼리 동기화 필요한 변수에 사용(상태 공유 등); 관련 성능 향상 시
락으로 인한 오버헤드나 컨테스트 스위칭 비용 감소
non blocking 상황에서(스레드 별 독립적인 작업 시)
5. immutable object 불변 객체 사용
String, Integer, Long, Double 등 과 같은 wrapper 클래스 사용
private final로 선언
생성자 이용하여 initialize
setter 함수나 수정가능 함수 제공하지 않기
6. volatile
변수를 Main Memory에 저장하겠다고 명시하는 것
각 스레드는 메인 메모리로 부터 값을 복사해 CPU 캐시에 저장하여 작업하는데 volatile은 CPU 캐시 사용 막고 메모리에 접근해서 실제 값을 읽어오도록 설정하여 데이터 불일치를 막음
자원의 가시성: 메인 메모리에 저장된 실제 자원의 값을 볼 수 있는 것
멀티쓰레드 환경에서 하나의 쓰레드만 read&write하고 나머지 쓰레드가 read하는 상황에 사용
Read : CPU cache에 저장된 값 X , 메인 메모리에서 읽음
Write : 메인 메모리에 작성
CPU Cache보다 메인 메모리가 비용이 더 큼(성능 주의)
가장 최신 값 보장
what to choose
synchronized
여러 쓰레드가 write하는 상황에 적합
가시성 문제해결 : synchronized블락 진입 전/후에 메인 메모리와 CPU 캐시 메모리의 값을 동기화 하여 문제 없도록 처리
@RequestMapping("/api/member")
@RestController
@RequiredArgsConstructor
public class MemberController {
private final UserService userService;
@GetMapping("/loss-game-money")
public BaseResponse<MemberLossGameMoneyResponse> getMemberLossGameMoney(@ModelAttribute MemberLossGameMoneyRequest request) {
return userService.getMemberLossGameMoney(request);
}
@GetMapping("/{id}")
public BaseResponse<MemberInfoResponse> getMember(@PathVariable String id) {
return new BaseResponse<>(userService.getMemberInfo(id));
}
}
이 상황에서 아래 api를 요청한다면? endpoint가 정의되어 있지 않아 404가 날 것이라 기대했다.
http://localhost:8600/api/member
하지만 200 ok 가 떨어졌다.
분명 컨트롤러에 정의되어 있지 않고, 그렇다고 에러 내용이 controller advice에 정의되어 있지도 않은데..
그리고 과거에는 404로 떨어졌던 기억도 있던 터라 구글링을 해본다..
의심 1. 스프링 버전 이슈?
구글링 하다가 스프링 버전 2.3 이후부터 바뀐 스펙이라고 적힌 것을 봐서.. 스프링 버전의 문제인가 의심했다.(개소리로 판명)
The change in behavior where Spring Boot started returning a 200 OK response with an empty body for unmatched endpoints instead of a 404 response happened around Spring Boot version 2.3.x. In versions prior to 2.3.x, the default behavior was to return a 404 Not Found response for unmatched endpoints. However, starting from version 2.3.x, the default behavior was changed to return a 200 OK response with an empty body.
공식 문서를 찾다가 실패하여 신규 프로젝트에 버전을 아래와 같이 중간 버전만 하나씩 올려서 테스트해 봤는데
위 함수에서 컨트롤러에 정의된 api는 if (handler instanceof HandlerMethod) 구문에 true를 반환하여 작업을 하고 마지막에 true를 반환하지만 정의되지 않은 api는 false를 타게 된다. false를 타면 상태코드 200에 empty body로 리턴된다..! false를 반환한다는 의미가 controller를 타지 않고 작업을 종료한다는 의미고 그게 잘 되었으니 어쩌면 맞을 수도..
혹시나 싶어서 신규 프로젝트로 기본 세팅만 한 후 재현해 본다.
1.@EnableWebMvc 없고 + return false
@Component
public class TestInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
return false;
}
}
@Component
@RequiredArgsConstructor
public class WebMvcConfig implements WebMvcConfigurer {
private final TestInterceptor interceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
//TestInterceptor가 이미 빈으로 등록되어 있으므로 주입하여 사용하기위해 아래 주석;
//TestInterceptor에 @Component가 없으면 빈이 아니므로 아래 주석이 작동함
// registry.addInterceptor(new TestInterceptor()).addPathPatterns("/**");
registry.addInterceptor(interceptor);
}
}
@RequestMapping("/api")
@RestController
public class TestController {
@GetMapping("/test")
public String test( ) {
return "hello";
}
}
아래와 같이 false 반환대신 에러를 던지면 throw 절을 만나게 되고 BasicErrorController를 타고 500으로 떨어진다.
(어떤 종류의 exception이건 500으로 떨어진다. 그 이유는 Exception이 처리가 이뤄지지 않은 상태로 WAS에게 전달되었기 때문이다. WAS 입장에서는 처리되지 않은 Exception을 받으면 이를 예상치 못한 문제로 인해 발생했다고 간주하고 status코드 500에 Internal Server Error를 메시지에 설정하게 된다.)
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (! (handler instanceof HandlerMethod)) {
throw new RuntimeException("nono");
}
return true;
}
@EnableWebMvc 어노테이션의 유무
1. @EnableWebMvc 있고 + 인터셉터에서 return true로 진행시키면
여기서 @EnableWebMvc 어노테이션을 추가하면 (어떤 에러를 던지건) 404로 에러가 바뀐다....
spring-web dependency가 있으면 @EnableWebMvc를 선언하지 않아도 된다고 알고 있는데 결과가 다르다니..(아래에서 계속)
더 확인해 보니 @EnableWebMvc를 선언하면 아래 부분이 true로 내려와서
handler instanceof HandlerMethod == true
결국 preHandler가 true로 return 되어 에러를 만나지 않고, controller 단에 가서 url을 찾다가 없어서 404 -> BasicErrorController를 타는 플로우였다.
2. @EnableWebMvc+ 인터셉터 내부에서 에러 발생 시키면
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
throw new HttpClientErrorException(HttpStatus.MULTI_STATUS);
}
2024-04-18 09:56:29.978 WARN 12950 --- [nio-8080-exec-8] o.s.web.servlet.PageNotFound : No mapping for GET /api/test3
2024-04-18 09:56:29.980 ERROR 12950 --- [nio-8080-exec-8] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] threw exception
org.springframework.web.client.HttpClientErrorException: 207 MULTI_STATUS
at com.example.demo.interceptor.TestInterceptor.preHandle(TestInterceptor.java:16) ~[main/:na]
...
2024-04-18 09:56:29.982 ERROR 12950 --- [nio-8080-exec-8] o.a.c.c.C.[Tomcat].[localhost] : Exception Processing ErrorPage[errorCode=0, location=/error]
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.web.client.HttpClientErrorException: 207 MULTI_STATUS
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1014) ~[spring-webmvc-5.3.22.jar:5.3.22]
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898) ~[spring-webmvc-5.3.22.jar:5.3.22]
...
해당 부분에서도 항상 에러를 뱉게 하면 에러가 발생해도 404로 떨어진다.
그 의미는 에러가 발생해도 controller 쪽으로 요청이 들어온다는 것인데, 그 이유는 WAS의 에러페이지를 위한 요청 때문이다.
https://cs-ssupport.tistory.com/494
interceptor에 에러를 반환하고 exception handler를 통해 에러를 반환하려고 하면 어떻게 해야 할까?
interceptor는 dispatcher servlet 이후 스프링 컨텍스트 안에 있기 때문에 controller advice를 통한 처리가 가능하다.
1. @EnableWebMvc + controllerAdvice
@EnableWebMvc를 선언한 상태에서 interceptor에서 에러를 뱉게 아래와 같이 수정하고
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
throw new RuntimeException("yesyes");
}
controllerAdvice를 통해 exception handler를 작성하면 의도한 대로 상태코드 400에 에러 메시지가 나온다!
@RestControllerAdvice
public class InterceptorExceptionHandler {
@ExceptionHandler({RuntimeException.class})
@ResponseStatus(HttpStatus.BAD_REQUEST)
public String error(RuntimeException exception){
return "Exception : " + exception.getMessage();
}
}
WARN 23846 --- [nio-8080-exec-1] o.s.web.servlet.PageNotFound : No mapping for GET /api/test3
로그에는 page not found 가 적힌다.
2.@EnableWebMvc 제거 + controllerAdvice
여기서 @EnableWebMvc를선언을 제거한다면?
그래도 api는 동일한 결과가 반환된다.
그런데 로그는 다르게 찍힌다. 반환한 에러에 대한 값이 찍힌다.
ERROR 24122 --- [nio-8080-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.RuntimeException: yesyes] with root cause
java.lang.RuntimeException: yesyes
at com.example.demo.interceptor.TestInterceptor.preHandle(TestInterceptor.java:14) ~[main/:na]
at org.springframework.web.servlet.HandlerExecutionChain.applyPreHandle(HandlerExecutionChain.java:148) ~[spring-webmvc-5.3.22.jar:5.3.22]
...
@EnableWebMvc 어노테이션 관련..
spring-web dependency가 있으면 @EnableWebMvc를 선언하지 않아도 된다고 알고 있는데 결과가 다르다니..
에 대해 좀 더 알아본다.
우선 맞다. springboot에 spring boot starter web 디펜덴시가 있으면 @SpringBootApplicaion 어노테이션에 의해 @EnableAutoConfiguration 어노테이션이 작동하고 웹의 기능(DispatcherServlet 등)을 사용하기 위한 기본 세팅을 자동으로 해준다.
@EnableWebMvc 어노테이션이 사용되면 스프링은 웹 애플리케이션을 위한 준비를 하게 되는데, 기본 설정값으로 아래 클래스를 읽어온다.
public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport
The @EnableWebMvc annotation is used in Spring to enable the Spring MVC framework for a web application. When this annotation is used, it imports the Spring MVC configuration from WebMvcConfigurationSupport and helps in setting up the necessary components for handling web requests, such as controllers, views, and more. This annotation is often used in conjunction with the @Configuration annotation to enable Spring MVC configuration in a Java-based configuration approach.
우리가 기본 세팅을 커스터마이징 하려면 WebMvcConfigurerAdapter라는 클래스를 extend 해야 하는데, 이 클래스는 spring5.0 이래로 deprecated 되었고, WebMvcConfigurer interface를 implement 해야 한다.
그런데 여기서 주의해야 할 점은 커스텀 세팅을 사용하려면 @EnableWebMvc 어노테이션이 없어야 한다는 것이다.
만약 @EnableWebMvc 어노테이션과 커스텀 세팅을 사용하려면 빈으로 등록된 DelegatingWebMvcConfiguration 클래스를 확장하여 재정의해야 한다. 기본 값을 사용하지 않기에 모든 함수를 재정의해야 함에 주의하자.
로컬에서 개발할 때, 그리고 운영 환경으로 배포할 때 내용물에 따라 설정파일을 분리할 수 있으며, 환경에 따라 다르게 가져가야 한다.
-- 소스 실행
mvn spring-boot:run -Dspring-boot.run.arguments=--spring.profiles.active=production
-- jar 로 빌드해서 배포
java -Dspring.profiles.active=production service.jar
설정파일은 파일명 자체를 여러가지로 둘 수도 있고, 그 안에서 환경(profile)을 줄 수도 있다.
그리고 JPA/mysql-connector 내부적으로도 반올림하는 부분이 있어 시간에 민감한 데이터인 경우 LocalDateTime.now()를 사용하는 것도 문제가 될 수 있다고 한다. 이럴 땐 DB connect 시 설정에 sendFractionalSeconds=false를 추가해줘야 한다.
2024-02-08 15:54:27.567 INFO [order-service,89bf1666da761e42,730648c3fe5dad8a] 4968 --- [o-auto-1-exec-4] c.e.o.controller.OrderController : before get orders
Hibernate: select order0_.id as id1_0_, order0_.created_at as created_2_0_, order0_.order_id as order_id3_0_, order0_.product_id as product_4_0_, order0_.qty as qty5_0_, order0_.total_price as total_pr6_0_, order0_.unit_price as unit_pri7_0_, order0_.user_id as user_id8_0_ from orders order0_ where order0_.user_id=?
2024-02-08 15:54:28.069 INFO [order-service,89bf1666da761e42,730648c3fe5dad8a] 4968 --- [o-auto-1-exec-4] c.e.o.controller.OrderController : after call orders msa