자바에서 ExecutorExecutorService는 자바의 동시성(concurrency) 프로그래밍을 위한 핵심 인터페이스입니다. 이들은 작업 실행을 추상화하여 개발자가 스레드 관리의 복잡성으로부터 벗어날 수 있게 돕습니다. 아래에서 각각에 대해 자세히 설명하겠습니다.
 

 
 
 
 

Executor

Executor 인터페이스는 java.util.concurrent 패키지에 속해 있으며, 단일 추상 메소드 execute(Runnable command)를 가지고 있습니다. 이 메소드는 주어진 작업(Runnable 객체)을 실행하는 방법을 정의합니다. Executor를 구현하는 클래스는 이 execute 메소드를 통해 어떻게 그리고 언제 작업을 실행할지 결정합니다. 이 인터페이스는 작업의 실행을 간단하게 추상화하여, 실행 메커니즘(예: 스레드 사용 방법)을 사용자로부터 숨깁니다.

Executor executor = anExecutor;
executor.execute(new Runnable() {
    public void run() {
        // 작업 내용
    }
});

 
Executor 인터페이스는 개발자들이 해당 작업의 실행과 쓰레드의 사용 및 스케줄링 등으로부터 벗어날 수 있도록 도와준다. 단순히 전달받은 Runnable 작업을 사용하는 코드를 Executor로 구현하면 다음과 같다

@Test
void executorRun() {
    final Runnable runnable = () -> System.out.println("Thread: " + Thread.currentThread().getName());

    Executor executor = new RunExecutor();
    executor.execute(runnable);
}

static class RunExecutor implements Executor {

    @Override
    public void execute(final Runnable command) {
        command.run();
    }
}
출처: https://mangkyu.tistory.com/259 [MangKyu's Diary:티스토리]

 

ExecutorService

ExecutorService는 Executor를 확장한 더 복잡한 인터페이스로, 생명주기 관리(lifecycle management)와 작업 실행 결과를 추적할 수 있는 기능을 제공합니다. ExecutorService를 사용하면, 비동기 작업을 제출하고, 작업이 완료될 때까지 기다리며, 작업 실행을 취소하고, 실행자 서비스를 종료할 수 있습니다. ExecutorService에는 작업을 제출하기 위한 다양한 submit 메소드가 있으며, 이들은 Future 객체를 반환하여 나중에 작업의 결과를 검색할 수 있게 합니다.

ExecutorService는 주로 다음과 같은 메소드들을 제공합니다:

  • shutdown(): 실행자 서비스를 순차적으로 종료시키며, 이미 제출된 작업은 실행되지만 새 작업은 받지 않습니다.
  • shutdownNow(): 실행자 서비스를 즉시 종료시키며, 대기 중인 작업은 실행되지 않습니다.
  • submit(Callable<T> task): 값을 반환할 수 있는 작업을 제출하고, 작업이 완료될 때 결과를 받을 수 있는 Future<T>를 반환합니다.
  • invokeAll(...): 작업 컬렉션을 실행하고, 모든 작업이 완료될 때까지 기다린 후, 결과를 반환합니다.

이미지 출처 :&nbsp; :&nbsp; https://mangkyu.tistory.com/259

 

ExecutorService 인터페이스에서 제공하는 주요 메소드들과 각각의 사용 예제를 아래에 설명하겠습니다. 이 인터페이스는 다양한 방법으로 작업을 실행하고, 관리하는 기능을 제공합니다

 

1. execute(Runnable command)

단순한 Runnable 작업을 실행합니다. 작업의 결과를 반환받을 수는 없습니다.

ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.execute(new Runnable() {
    public void run() {
        System.out.println("Asynchronous task");
    }
});
executorService.shutdown();

 

2. submit(Runnable task)

Runnable 작업을 실행하고, 작업이 완료될 때까지 기다리는 데 사용할 수 있는 Future<?>를 반환합니다.

ExecutorService executorService = Executors.newSingleThreadExecutor();
Future<?> future = executorService.submit(new Runnable() {
    public void run() {
        System.out.println("Asynchronous task");
    }
});
executorService.shutdown();

 

3. submit(Callable<T> task)

Callable 작업을 실행하고, 작업의 결과를 받을 수 있는 Future<T>를 반환합니다.

ExecutorService executorService = Executors.newSingleThreadExecutor();
Future<String> future = executorService.submit(new Callable<String>() {
    public String call() {
        return "Result of the asynchronous computation";
    }
});
executorService.shutdown();

 

4. invokeAll(Collection<? extends Callable<T>> tasks)

주어진 작업들의 컬렉션을 실행하고, 모든 작업이 완료될 때까지 기다린 다음, 각 작업의 결과를 담은 List<Future<T>>를 반환합니다.

ExecutorService executorService = Executors.newSingleThreadExecutor();
List<Callable<String>> callables = Arrays.asList(
    () -> "Task 1",
    () -> "Task 2",
    () -> "Task 3"
);

try {
    List<Future<String>> futures = executorService.invokeAll(callables);
    for(Future<String> future : futures){
        System.out.println(future.get());
    }
} catch (InterruptedException | ExecutionException e) {
    e.printStackTrace();
}
executorService.shutdown();

 

5. invokeAny(Collection<? extends Callable<T>> tasks)

주어진 작업들의 컬렉션 중 하나를 실행하고, 가장 먼저 완료되는 작업의 결과를 반환합니다. 나머지 작업은 취소됩니다.

ExecutorService executorService = Executors.newSingleThreadExecutor();
List<Callable<String>> callables = Arrays.asList(
    () -> {
        TimeUnit.SECONDS.sleep(2);
        return "Task 1";
    },
    () -> {
        TimeUnit.SECONDS.sleep(1);
        return "Task 2";
    },
    () -> {
        TimeUnit.SECONDS.sleep(3);
        return "Task 3";
    }
);

String result = executorService.invokeAny(callables);
System.out.println(result); // "Task 2" 의 결과가 가장 빨리 나올 것입니다.
executorService.shutdown();

 

ExecutorExecutorService는 자바에서 동시성을 다룰 때 중요한 구성 요소입니다. 이들을 사용함으로써 스레드를 직접 관리하는 복잡성을 줄이고, 효율적이고 안정적인 동시 실행을 구현할 수 있습니다.

 

6. shutdown()

실행자 서비스를 순차적으로 종료합니다. 이미 제출된 작업은 완료되지만, 새 작업은 받지 않습니다.

ExecutorService executorService = Executors.newSingleThreadExecutor();
// 작업 제출 등
executorService.shutdown();

 

7. shutdownNow()

실행자 서비스를 즉시 종료하고, 현재 대기 중이거나 실행 중인 작업 목록을 반환합니다.

ExecutorService executorService = Executors.newSingleThreadExecutor();
// 작업 제출 등
List<Runnable> notExecutedTasks = executorService.shutdownNow();

 

 

참고 : https://mangkyu.tistory.com/259

 

[Java] Callable, Future 및 Executors, Executor, ExecutorService, ScheduledExecutorService에 대한 이해 및 사용법

이번에는 자바5 부터 멀티 쓰레드 기반의 동시성 프로그래밍을 위해 추가된 Executor, ExecutorService, ScheduledExecutorService와 Callable, Future를 살펴보도록 하겠습니다. 1. Callable과 Future 인터페이스에 대한

mangkyu.tistory.com

 

https://www.acmicpc.net/problem/20056

 

20056번: 마법사 상어와 파이어볼

첫째 줄에 N, M, K가 주어진다. 둘째 줄부터 M개의 줄에 파이어볼의 정보가 한 줄에 하나씩 주어진다. 파이어볼의 정보는 다섯 정수 ri, ci, mi, si, di로 이루어져 있다. 서로 다른 두 파이어볼의 위치

www.acmicpc.net

이번주 연휴여서  가족끼리 간단히 여행다녀와서 주말에 공부를 많이 못했습니다.

 

여기서 핵심 포인트는 파이어볼이 나눠질때 나눠지는 순간에는 움직이지 않는다는 점을 주의 해야합니다.

그걸 모르면 음 나눠질때도 움직이게 계산을 하는 실수를 범할수 있습니다. 

문제는 조금 많이 생각해야하는 문제네요.

package test01;
import java.util.*;
import java.util.*;
import java.io.*;

public class Main {
    static int N, M, K;
    static ArrayList<Fireball>[][] map;
    static int[] dr = {-1, -1, 0, 1, 1, 1, 0, -1};
    static int[] dc = {0, 1, 1, 1, 0, -1, -1, -1};

    public static class Fireball {
        int r, c, m, s, d;

        public Fireball(int r, int c, int m, int s, int d) {
            this.r = r;
            this.c = c;
            this.m = m;
            this.s = s;
            this.d = d;
        }
    }

    public static void main(String[] args) throws IOException {
       Scanner scan=new Scanner(System.in);
        N = scan.nextInt();
        M =  scan.nextInt();
        K =  scan.nextInt();

        map = new ArrayList[N][N];
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                map[i][j] = new ArrayList<Fireball>();
            }
        }

        for (int i = 0; i < M; i++) {
           
            int r =  scan.nextInt()- 1;
            int c =  scan.nextInt() - 1;
            int m =  scan.nextInt();
            int s =  scan.nextInt();
            int d = scan.nextInt();
            map[r][c].add(new Fireball(r, c, m, s, d));
        }

        for (int k = 0; k < K; k++) {
            moveFireballs();
            DivideFireballs();
        }

        int result = 0;
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                for (Fireball f : map[i][j]) {
                    result += f.m;
                }
            }
        }

        System.out.println(result);
    }

    public static void moveFireballs() {
        ArrayList<Fireball>[][] newMap = new ArrayList[N][N];
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                newMap[i][j] = new ArrayList<Fireball>();
            }
        }

        for (int r = 0; r < N; r++) {
            for (int c = 0; c < N; c++) {
            	for(int z=0;z<map[r][c].size();z++) {
            		Fireball f=map[r][c].get(z);
            		int nr = (f.r + dr[f.d] * f.s % N + N) % N;
                     int nc = (f.c + dc[f.d] * f.s % N + N) % N;
            		
            			newMap[nr][nc].add(new Fireball(nr, nc, f.m, f.s, f.d));
            		
            	
            	}
                
            }
        }

        map = newMap;
    }

    public static void DivideFireballs() {
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                if (map[i][j].size() > 1) {
                    int sumM = 0;
                    int sumS = 0;
                    boolean even = true; 
                    boolean odd = true;
                    for (Fireball f : map[i][j]) {
                        sumM += f.m;
                        sumS += f.s;
                        if (f.d % 2 == 0) odd = false;
                        else even = false;
                    }

                    int nm = sumM / 5;
                    int ns = sumS / map[i][j].size();
                    map[i][j].clear();
                    if (nm > 0) {
                        for (int d = 0; d < 8; d += 2) {
                            if (even || odd) {
                            	map[i][j].add(new Fireball(i, j, nm, ns, d));
                            } 
                            else {
                            	map[i][j].add(new Fireball(i, j, nm, ns, d + 1));
                            }
                        }
                    }
                }
            }
        }
    }
}

'알고리즘 공부' 카테고리의 다른 글

백준 배열돌리기4  (0) 2024.03.30
백준-배열돌리기3  (1) 2024.03.25
백준 - 마법사 상어와 비바라기  (1) 2024.02.24
백준 컨베이어 밸트 위의 로봇  (1) 2024.02.17
백준 빗물  (0) 2024.02.11

2024.02.18 - [웹/Spring] - Spring jpa - repository 인터페이스의 정의

 

Spring jpa - repository 인터페이스의 정의

2024.02.03 - [웹/Spring] - Spring Data JPA - 핵심 개념 Spring Data JPA - 핵심 개념 2024.02.03 - [끄적이기] - JPA에 대해서 JPA에 대해서 JPA? 자바 퍼시스턴스(Java Persistence, 이전 이름: 자바 퍼시스턴스 API/Java Persist

kwaksh2319.tistory.com

Spring Data JPA 리포지토리 지원은 다음 예시와 같이 JavaConfig와 사용자 지정 XML 네임스페이스를 통해 활성화될 수 있습니다.

@Configuration
@EnableJpaRepositories
@EnableTransactionManagement
class ApplicationConfig {

  @Bean
  public DataSource dataSource() {

    EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
    return builder.setType(EmbeddedDatabaseType.HSQL).build();
  }

  @Bean
  public LocalContainerEntityManagerFactoryBean entityManagerFactory() {

    HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
    vendorAdapter.setGenerateDdl(true);

    LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
    factory.setJpaVendorAdapter(vendorAdapter);
    factory.setPackagesToScan("com.acme.domain");
    factory.setDataSource(dataSource());
    return factory;
  }

  @Bean
  public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {

    JpaTransactionManager txManager = new JpaTransactionManager();
    txManager.setEntityManagerFactory(entityManagerFactory);
    return txManager;
  }
}

 

앞서 언급된 구성 클래스는 spring-jdbc의 EmbeddedDatabaseBuilder API를 사용하여 내장 HSQL 데이터베이스를 설정합니다. 그런 다음 Spring Data는 EntityManagerFactory를 설정하고 샘플 영속성 제공자로 Hibernate를 사용합니다. 여기에 선언된 마지막 인프라 구성 요소는 JpaTransactionManager입니다. 마지막으로, 예제는 @EnableJpaRepositories 주석을 사용하여 Spring Data JPA 리포지토리를 활성화하는데, 이는 본질적으로 XML 네임스페이스와 같은 속성을 가집니다. 기본 패키지가 구성되지 않은 경우, 구성 클래스가 위치한 패키지를 사용합니다.

 

*  EmbeddedDatabaseBuilder API?

EmbeddedDatabaseBuilder API는 Spring Framework의 일부로, 개발자가 손쉽게 내장형 데이터베이스를 구성하고 사용할 수 있게 해주는 도구입니다. 이 API는 spring-jdbc 모듈에 포함되어 있으며, 주로 테스트나 프로토타이핑 목적으로 사용됩니다. EmbeddedDatabaseBuilder를 사용하면 HSQL, H2, Derby와 같은 인메모리 데이터베이스를 코드 몇 줄로 설정할 수 있습니다. 이 API를 통해 데이터베이스 인스턴스를 생성하고, SQL 스크립트를 실행하여 스키마를 초기화하거나 테스트 데이터를 로드할 수 있습니다.

EmbeddedDatabaseBuilder는 매우 유연하며, 데이터베이스 타입, 초기화 스크립트, 종료 옵션 등을 설정할 수 있는 다양한 메서드를 제공합니다. 이를 통해 애플리케이션이나 테스트 실행 시 필요한 데이터베이스 환경을 쉽게 준비하고 관리할 수 있습니다.

 

* 내장 HSQL 데이터베이스?

HSQLDB(HyperSQL DataBase)는 자바로 작성된 관계형 데이터베이스 관리 시스템(RDBMS)입니다. 이 데이터베이스는 주로 내장 데이터베이스로 사용되며, 애플리케이션에 직접 포함될 수 있습니다. HSQLDB는 작고 빠르며, SQL-92 표준의 상당 부분을 지원합니다. 인메모리 운영 모드를 지원하기 때문에, 애플리케이션 테스트나 개발 과정에서 빠르게 데이터베이스 환경을 구축하고 사용할 수 있습니다.

내장 HSQL 데이터베이스의 주요 장점은 별도의 서버 설치나 관리 없이 애플리케이션 내부에서 직접 데이터베이스를 실행할 수 있다는 것입니다. 이는 개발 및 테스트 과정을 간소화하고, 애플리케이션의 배포와 이식성을 향상시킵니다. HSQLDB는 자바 기반 애플리케이션과의 통합이 용이하며, JUnit 테스트 등에서 데이터베이스 환경을 요구하는 경우 유용하게 사용될 수 있습니다.

 

*Spring 네임스페이스

Spring Data의 JPA 모듈에는 리포지토리 빈을 정의할 수 있는 사용자 지정 네임스페이스가 포함되어 있습니다. 또한 JPA에 특화된 특정 기능과 요소 속성을 포함하고 있습니다. 일반적으로, JPA 리포지토리는 다음 예시와 같이 repositories 요소를 사용하여 설정할 수 있습니다.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:jpa="http://www.springframework.org/schema/data/jpa"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
    https://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/data/jpa
    https://www.springframework.org/schema/data/jpa/spring-jpa.xsd">

  <jpa:repositories base-package="com.acme.repositories" />

</beans>

 

repositories 요소를 사용하면 @Repository로 주석이 달린 모든 빈에 대해 영속성 예외 변환을 활성화하여, JPA 영속성 제공자에 의해 발생된 예외들이 Spring의 DataAccessException 계층 구조로 변환되게 합니다.

 

*  JPA 영속성이란?

자바 애플리케이션에서 객체와 데이터베이스 테이블 사이의 매핑을 관리하는 방법입니다. 이는 자바 표준으로, 개발자가 데이터베이스 작업을 보다 쉽게 할 수 있도록 도와주며, 객체 지향 프로그래밍과 관계형 데이터베이스 사이의 간극을 줄여줍니다.

JPA를 사용하면 개발자는 복잡한 SQL 쿼리를 작성하는 대신, 객체의 상태 변화를 데이터베이스에 자동으로 반영할 수 있습니다. 이를 통해 객체를 생성, 조회, 업데이트 및 삭제하는 작업을 객체 지향적인 방식으로 처리할 수 있습니다. JPA는 이러한 작업을 위한 API와 런타임 환경을 제공합니다.

영속성 컨텍스트라고 불리는 JPA의 핵심 개념은 엔티티의 생명 주기를 관리합니다. 영속성 컨텍스트는 엔티티를 관리하며, 엔티티의 상태 변화를 추적하여 데이터베이스에 반영합니다. 엔티티가 영속성 컨텍스트에 의해 관리될 때, 그 엔티티는 '영속 상태'에 있으며, 이 상태에서는 JPA가 자동으로 데이터베이스와의 동기화를 처리합니다.

이러한 방식으로 JPA 영속성은 개발자가 데이터베이스와의 상호작용을 추상화하고, 데이터베이스 작업을 보다 직관적이고 객체 지향적인 방식으로 수행할 수 있도록 도와줍니다.

 

*사용자 지정 네임스페이스 속성

repositories 요소의 기본 속성을 넘어서, JPA 네임스페이스는 리포지토리 설정에 대한 보다 상세한 제어를 할 수 있도록 추가 속성을 제공합니다.

    표1.  repositories 요소의 사용자 지정 JPA 특정 속성

entity-manager-factory-ref repositories 요소에 의해 감지된 리포지토리와 함께 사용될 EntityManagerFactory를 명시적으로 연결합니다. 보통 애플리케이션 내에서 여러 EntityManagerFactory 빈들이 사용될 경우에 사용됩니다. 구성되지 않은 경우, Spring Data는 ApplicationContext 내에서 entityManagerFactory라는 이름의 EntityManagerFactory 빈을 자동으로 찾습니다.
transaction-manager-ref repositories 요소에 의해 감지된 리포지토리와 함께 사용될 PlatformTransactionManager를 명시적으로 연결합니다. 보통 여러 트랜잭션 매니저 또는 EntityManagerFactory 빈들이 구성된 경우에만 필요합니다. 현재 ApplicationContext 내에서 단일로 정의된 PlatformTransactionManager를 기본값으로 합니다.

주의)

  명시적인 transaction-manager-ref가 정의되어 있지 않은 경우, Spring Data JPA는 transactionManager라는 이름의 PlatformTransactionManager 빈이 존재해야 합니다.

 

*bootstrap mode

기본적으로, Spring Data JPA 리포지토리는 기본적으로 Spring 빈입니다. 이들은 싱글톤 범위를 가지며 즉시 초기화됩니다. 시작하는 동안, 그들은 검증 및 메타데이터 분석 목적으로 JPA EntityManager와 이미 상호작용합니다. Spring Framework는 JPA EntityManagerFactory의 초기화를 백그라운드 스레드에서 지원합니다. 왜냐하면 그 과정은 보통 Spring 애플리케이션의 시작 시간에서 상당한 양을 차지하기 때문입니다. 그 백그라운드 초기화를 효과적으로 사용하기 위해, JPA 리포지토리가 가능한 한 늦게 초기화되도록 해야 합니다.

 

Spring Data JPA 2.1부터, 이제 @EnableJpaRepositories 주석 또는 XML 네임스페이스를 통해 다음 값을 가지는 BootstrapMode를 구성할 수 있습니다:

DEFAULT (기본값) — 리포지토리는 명시적으로 @Lazy로 주석이 달리지 않는 한 즉시 인스턴스화됩니다. 
                    이 지연화는 리포지토리의 인스턴스가 필요하지 않는 클라이언트 빈이 없을 때만
                    효과가 있습니다. 왜냐하면 그것은 리포지토리 빈의 초기화를 요구하기 때문입니다.

LAZY — 모든 리포지토리 빈을 암시적으로 지연된 것으로 선언하고 클라이언트 빈에 주입될 지연 초기화
       프록시를 생성합니다. 
       즉, 클라이언트 빈이 단순히 인스턴스를 필드에 저장하고 초기화하는 동안 리포지토리를 
       사용하지 않는 경우 리포지토리가 인스턴스화되지 않습니다. 리포지토리 인스턴스는 
       리포지토리와의 첫 번째 상호작용 시 초기화되고 검증됩니다.

DEFERRED — 기본적으로 LAZY와 동일한 운영 모드이지만, 
            애플리케이션이 완전히 시작되기 전에 리포지토리가 검증되도록 하여
            ContextRefreshedEvent에 대한 반응으로 리포지토리 초기화를 트리거합니다.

 

*추천 사항

비동기적인 JPA 부트스트랩을 사용하지 않는 경우, 기본 bootstrap mode 를 사용하세요.

JPA를 비동기적으로 bootStrap 하는 경우, DEFERRED는 합리적인 기본값입니다. 이는 EntityManagerFactory 설정이 애플리케이션의 다른 모든 구성 요소를 초기화하는 것보다 더 오래 걸릴 경우에만 Spring Data JPA 부트스트랩이 대기하도록 합니다. 그럼에도 불구하고, 애플리케이션이 준비되었다고 신호하기 전에 리포지토리가 제대로 초기화되고 검증되도록 합니다.

LAZY는 테스트 시나리오와 로컬 개발에 적합한 선택입니다. 리포지토리가 제대로 부트스트랩될 수 있다는 것을 확신하거나, 애플리케이션의 다른 부분을 테스트하는 경우에, 모든 리포지토리에 대한 검증을 실행하는 것은 시작 시간을 불필요하게 증가시킬 수 있습니다. 로컬 개발에서도, 단일 리포지토리만 초기화해야 하는 애플리케이션의 일부분에만 접근할 경우 같은 원칙이 적용됩니다.

 

참조: 

https://docs.spring.io/spring-data/jpa/reference/repositories/create-instances.html

 

Configuration :: Spring Data JPA

By default, Spring Data JPA repositories are default Spring beans. They are singleton scoped and eagerly initialized. During startup, they already interact with the JPA EntityManager for verification and metadata analysis purposes. Spring Framework support

docs.spring.io

 

' > Spring' 카테고리의 다른 글

Reflection api GetMethod  (0) 2024.04.20
Spring Data JPA- repository 인터페이스의 정의  (0) 2024.02.18
Spring Data JPA - 핵심 개념  (0) 2024.02.03
Spring Data JPA에 대해서  (0) 2024.02.03
톰캣의 war 실행되는 원리?  (0) 2024.01.14

https://www.acmicpc.net/problem/21610

 

21610번: 마법사 상어와 비바라기

마법사 상어는 파이어볼, 토네이도, 파이어스톰, 물복사버그 마법을 할 수 있다. 오늘 새로 배운 마법은 비바라기이다. 비바라기를 시전하면 하늘에 비구름을 만들 수 있다. 오늘은 비바라기

www.acmicpc.net

음 요즘 계속 평일에 알고리즘을 못푸네요 ㅠㅠ 

어쩌다보니 주말에 좀 풀게 되었는데 상황이 그렇게되어서 평일에 피곤하기도 하공 ㅠㅠ 나름 문제 읽고 풀려고하면 12시가 넘어서 ㅠ 일단 그래도 주말에라도 알고리즘 틈틈히 풀면서 포트폴리오도 쌓도록 하겠습니다. 

이번 문제는 상당히 쉬웠습니다. 다만 조금 조건이 많은거 뺴곤 구현문제로써는 상당히 좋은문제라고 생각했습니다. ㅎㅎ 


import java.util.*;

public class Main {
	public static int maps[][];
	public static boolean bCheck[][];
	public static int n;
	public static ArrayList<Cloud>clouds=new ArrayList<>();
	public static class Cloud{
		private int x;
		private int y;
		public Cloud(int x,int y) {
			this.x=x;
			this.y=y;
		}
		
		public void update(int x,int y) {
			this.x=x;
			this.y=y;
		}
		
		public int x() {
			return this.x;
		}
		
		public int y() {
			return this.y;
		}
	}
	public static void Prints() {
		for(int i=0;i<n;i++) {
			for(int j=0;j<n;j++) {
				System.out.print(maps[i][j]+",");
			}
			System.out.println();
		}
	}
	public static void moving(int movX,int movY, int S ) {
		
		for(int i=0;i<S;i++) {
			for(int j=0;j<clouds.size();j++) {
				int tmpX=clouds.get(j).x();
				int tmpY=clouds.get(j).y();
				
				//이동
				tmpX=tmpX+movX;
				tmpY=tmpY+movY;
				
				if(tmpX < 0 ) {
					tmpX=n-1;
				}
				
				if(tmpX>n-1) {
					tmpX=0;
				}
				
				if(tmpY < 0 ) {
					tmpY=n-1;
				}
				
				if(tmpY>n-1) {
					tmpY=0;
				}
				
				clouds.get(j).update(tmpX,tmpY);
			}
		
		}
		//rain
		for(int i=0;i<clouds.size();i++) {
			int tmpX=clouds.get(i).x();
			int tmpY=clouds.get(i).y();
			
			maps[tmpX][tmpY]=maps[tmpX][tmpY]+1;
			
		}
	
		//대각선 4개 방향에 따라 물잇을시
		int dirx[]= {-1,1,-1,1};
		int diry[]= {-1,-1,1,1};
		for(int i=0;i<clouds.size();i++) {
			int tmpX=clouds.get(i).x();
			int tmpY=clouds.get(i).y();
			bCheck[tmpX][tmpY]=true;
			
	
			//대각선 4개
			int tmpcnt=0;
			for(int j=0;j<4;j++) {
				int tmpDirX=tmpX+dirx[j];
				int tmpDirY=tmpY+diry[j];
				if(tmpDirX  == -1 ||tmpDirY == -1 || tmpDirX>n-1 ||tmpDirY>n-1) {
					continue;
				}
				if(maps[tmpDirX][tmpDirY]<=0) {
					continue;
				}
				tmpcnt++;
			}
			
			maps[tmpX][tmpY]=maps[tmpX][tmpY]+tmpcnt;
			
		}
		
		
		
		ArrayList<Cloud>tmpClouds=new ArrayList<>();
		for(int i=0;i<n;i++) {
			for(int j=0;j<n;j++) {
				if(maps[i][j]>=2 && bCheck[i][j] == false) {
					
					tmpClouds.add(new Cloud(i,j));
					//bCheck[i][j]=true;
					maps[i][j]=maps[i][j]-2;
					
				}
			}
		}
		
		
	   //clouds.clear();
		for(int i=0;i<clouds.size();i++) {
			int tmpX=clouds.get(i).x();
			int tmpY=clouds.get(i).y();
			bCheck[tmpX][tmpY]=false;
		}
		
		clouds.clear();
		
		for(int i=0;i<tmpClouds.size();i++) {
			clouds.add(tmpClouds.get(i));
		}
	}
	
	
    public static void main(String[] args) throws Exception {
    	
    	Scanner scan=new Scanner(System.in);
    	n=scan.nextInt();
    	int m=scan.nextInt();
    	
    	//1부터 순서대로 ←, ↖, ↑, ↗, →, ↘, ↓, ↙
    	
    	maps=new int[n][n];
    	bCheck=new boolean[n][n];
    	
    	for(int i=0;i<n;i++) {
    		for(int j=0;j<n;j++) {
    			int tmp = scan.nextInt();
    			maps[i][j]=tmp;
    		}
    	}
    	//비바라기를 시전하면 (N, 1), (N, 2), (N-1, 1), (N-1, 2)에 비구름

    	clouds.add(new Cloud(n-1,0));// (N, 1)
    	clouds.add(new Cloud(n-1,1));//(N, 2)
    	clouds.add(new Cloud(n-2,0));//(N-1, 1)
    	clouds.add(new Cloud(n-2,1));// (N-1, 2)
    	
    	
    	for(int z=0;z<m;z++) {
    		int d=scan.nextInt();
    		int s=scan.nextInt();
    		
    		switch(d) {
    		case 1:  // ←
    			moving( 0, -1, s );
    			break;
    		case 2:   // ↖
    			moving( -1, -1, s );
    			break;
    		case 3:     //↑
    			moving( -1, 0, s );
    			break;
    		case 4:     //↗
    			moving( -1, 1, s );
    			break;
    		case 5:    // →
    			moving( 0, 1, s );
    			break;
    		case 6:    // ↘
    			moving( 1, 1, s );
    			break;
    		case 7:  //↓
    			moving( 1, 0, s );
    			break;
    		case 8:   //↙
    			moving( 1, -1, s );
    			break;
    			
    		default:
    			break;
    		}
    		
    	}
    	
    	int sum=0;
    	for(int i=0;i<n;i++) {
    		for(int j=0;j<n;j++) {
    			sum=sum+maps[i][j];
    		}
    	}
    	System.out.println(sum);
        
    }
    
}

'알고리즘 공부' 카테고리의 다른 글

백준-배열돌리기3  (1) 2024.03.25
백준 - 마법사 상어와 파이어볼  (0) 2024.03.03
백준 컨베이어 밸트 위의 로봇  (1) 2024.02.17
백준 빗물  (0) 2024.02.11
백준 미로 만들기  (1) 2024.02.02

2024.02.03 - [웹/Spring] - Spring Data JPA - 핵심 개념

 

Spring Data JPA - 핵심 개념

2024.02.03 - [끄적이기] - JPA에 대해서 JPA에 대해서 JPA? 자바 퍼시스턴스(Java Persistence, 이전 이름: 자바 퍼시스턴스 API/Java Persistence API) 또는 자바 지속성 API(Java Persistence API, JPA)는 자바 플랫폼 SE와

kwaksh2319.tistory.com

 

저장소 인터페이스를 정의하려면 먼저 도메인 클래스별 저장소 인터페이스를 정의해야 합니다. 인터페이스는 Repository를 확장하고 도메인 클래스 및 ID 유형에 타입이 지정되어야 합니다. 해당 도메인 유형에 대한 CRUD 메소드를 노출하려면 Repository 대신 CrudRepository 또는 그 변형 중 하나를 확장할 수 있습니다.

 

저장소 인터페이스 정의를 세밀하게 조정하는 방법에는 몇 가지 변형이 있습니다.

전형적인 접근 방식은 CrudRepository를 확장하는 것이며, 이는 CRUD 기능을 위한 메소드를 제공합니다. CRUD는 생성(Create), 읽기(Read), 업데이트(Update), 삭제(Delete)를 의미합니다. 버전 3.0에서는 ListCrudRepository도 도입했는데, 이는 CrudRepository와 매우 유사하지만 다수의 엔티티를 반환하는 메소드의 경우 Iterable 대신 List를 반환하여 사용하기 더 쉬울 수 있습니다.

반응형 저장소를 사용하는 경우 사용하는 반응형 프레임워크에 따라 ReactiveCrudRepository 또는 RxJava3CrudRepository를 선택할 수 있습니다.

 

Kotlin을 사용하는 경우 코틀린의 코루틴을 활용하는 CoroutineCrudRepository를 선택할 수 있습니다.

추가로, Sort 추상화를 지정할 수 있는 메소드가 필요한 경우 PagingAndSortingRepository, ReactiveSortingRepository, RxJava3SortingRepository 또는 CoroutineSortingRepository를 확장할 수 있습니다. 첫 번째 경우 Pageable 추상화를 지정할 수 있습니다. 다양한 정렬 저장소는 Spring Data 버전 3.0 이전처럼 각각의 CRUD 저장소를 확장하지 않습니다. 따라서 두 기능 모두를 원하는 경우 두 인터페이스를 모두 확장해야 합니다.

 

Spring Data 인터페이스를 확장하고 싶지 않은 경우, @RepositoryDefinition으로 저장소 인터페이스를 주석 처리할 수도 있습니다. CRUD 저장소 인터페이스 중 하나를 확장하면 엔티티를 조작하는 메소드의 완전한 세트가 노출됩니다. 노출되는 메소드를 선택적으로 결정하고 싶다면, 원하는 메소드를 CRUD 저장소에서 도메인 저장소로 복사하세요. 이렇게 할 때 메소드의 반환 유형을 변경할 수 있습니다. 가능한 경우 Spring Data는 반환 유형을 존중합니다. 예를 들어, 다수의 엔티티를 반환하는 메소드의 경우 Iterable<T>, List<T>, Collection<T> 또는 VAVR 리스트를 선택할 수 있습니다.

 

애플리케이션의 많은 저장소가 같은 메소드 세트를 가져야 한다면, 상속받을 자체 기본 인터페이스를 정의할 수 있습니다. 이러한 인터페이스는 @NoRepositoryBean으로 주석 처리되어야 합니다. 이는 Spring Data가 직접 인스턴스를 생성하려고 시도하고 실패하는 것을 방지하기 위함입니다. 왜냐하면 여전히 일반 유형 변수를 포함하고 있어 해당 저장소의 엔티티를 결정할 수 없기 때문입니다.

 

다음 예시는 CRUD 메소드(이 경우 findById와 save)를 선택적으로 보여줍니다.

 

@NoRepositoryBean
interface MyBaseRepository<T, ID> extends Repository<T, ID> {

  Optional<T> findById(ID id);

  <S extends T> S save(S entity);
}

interface UserRepository extends MyBaseRepository<User, Long> {
  User findByEmailAddress(EmailAddress emailAddress);
}

 

이전 예시에서, 모든 도메인 저장소에 대한 공통 기본 인터페이스를 정의하고 findById(...)와 save(...) 메소드를 노출시켰습니다. 이 메소드들은 CrudRepository에 있는 메소드 시그니처와 일치하기 때문에, 선택한 저장소의 Spring Data 제공 기본 저장소 구현체(예를 들어, JPA를 사용하는 경우 SimpleJpaRepository 구현체)로 라우팅됩니다. 따라서 UserRepository는 이제 사용자를 저장하고, ID로 개별 사용자를 찾고, 이메일 주소로 사용자를 찾기 위한 쿼리를 트리거할 수 있습니다.

 

애플리케이션에서 단일 Spring Data 모듈을 사용하는 것은 모든 저장소 인터페이스가 정의된 범위 내에서 해당 Spring Data 모듈에 바인딩되기 때문에 일이 간단해집니다. 그러나 때로는 둘 이상의 Spring Data 모듈을 사용해야 하는 상황이 발생합니다. 이런 경우에는 저장소 정의가 영속성 기술 사이를 구별해야 합니다. 클래스 경로상에 여러 저장소 팩토리가 감지되면, Spring Data는 엄격한 저장소 구성 모드로 전환됩니다. 엄격한 구성은 저장소 또는 도메인 클래스에 대한 세부 정보를 사용하여 저장소 정의에 대한 Spring Data 모듈 바인딩을 결정합니다:

  • 저장소 정의가 모듈 특정 저장소를 확장하는 경우, 해당 Spring Data 모듈에 대한 유효한 후보가 됩니다.
  • 도메인 클래스가 모듈 특정 유형 주석으로 주석이 달린 경우, 해당 Spring Data 모듈에 대한 유효한 후보가 됩니다. Spring Data 모듈은 JPA의 @Entity와 같은 타사 주석이나 Spring Data MongoDB 및 Spring Data Elasticsearch의 @Document와 같은 자체 주석을 허용합니다.

다음 예시는 모듈 특정 인터페이스(JPA인 경우)를 사용하는 저장소를 보여줍니다:

interface MyRepository extends JpaRepository<User, Long> { }

@NoRepositoryBean
interface MyBaseRepository<T, ID> extends JpaRepository<T, ID> { … }

interface UserRepository extends MyBaseRepository<User, Long> { … }
interface AmbiguousRepository extends Repository<User, Long> { … }

@NoRepositoryBean
interface MyBaseRepository<T, ID> extends CrudRepository<T, ID> { … }

interface AmbiguousUserRepository extends MyBaseRepository<User, Long> { … }
interface PersonRepository extends Repository<Person, Long> { … }

@Entity
class Person { … }

interface UserRepository extends Repository<User, Long> { … }

@Document
class User { … }
interface JpaPersonRepository extends Repository<Person, Long> { … }

interface MongoDBPersonRepository extends Repository<Person, Long> { … }

@Entity
@Document
class Person { … }

엄격한 저장소 구성을 위해 저장소 유형 세부 정보와 도메인 클래스 주석을 구별하는 것은 특정 Spring Data 모듈에 대한 저장소 후보를 식별하는 데 사용됩니다. 동일한 도메인 유형에 여러 영속성 기술 특정 주석을 사용하는 것이 가능하며, 이는 여러 영속성 기술에 걸쳐 도메인 유형의 재사용을 가능하게 합니다. 그러나 이 경우 Spring Data는 더 이상 저장소와 바인딩할 유일한 모듈을 결정할 수 없습니다.

저장소를 구별하는 마지막 방법은 저장소 기본 패키지의 범위를 지정하는 것입니다. 기본 패키지는 저장소 인터페이스 정의를 스캔하기 위한 시작점을 정의하며, 이는 적절한 패키지에 저장소 정의가 위치해야 함을 의미합니다. 기본적으로, 주석 기반 구성은 구성 클래스의 패키지를 사용합니다. XML 기반 구성에서는 기본 패키지가 필수입니다.

 

@EnableJpaRepositories(basePackages = "com.acme.repositories.jpa")
@EnableMongoRepositories(basePackages = "com.acme.repositories.mongo")
class Configuration { … }

https://docs.spring.io/spring-data/jpa/reference/repositories/definition.html

 

Defining Repository Interfaces :: Spring Data JPA

To define a repository interface, you first need to define a domain class-specific repository interface. The interface must extend Repository and be typed to the domain class and an ID type. If you want to expose CRUD methods for that domain type, you may

docs.spring.io

 

' > Spring' 카테고리의 다른 글

Reflection api GetMethod  (0) 2024.04.20
Spring Data JPA - 구성  (0) 2024.02.25
Spring Data JPA - 핵심 개념  (0) 2024.02.03
Spring Data JPA에 대해서  (0) 2024.02.03
톰캣의 war 실행되는 원리?  (0) 2024.01.14

https://www.acmicpc.net/problem/20055

 

20055번: 컨베이어 벨트 위의 로봇

길이가 N인 컨베이어 벨트가 있고, 길이가 2N인 벨트가 이 컨베이어 벨트를 위아래로 감싸며 돌고 있다. 벨트는 길이 1 간격으로 2N개의 칸으로 나뉘어져 있으며, 각 칸에는 아래 그림과 같이 1부

www.acmicpc.net

문제는 쉬운편이였습니다. 다만 문제를 이해하는게 조금 난이도가 있었고요 로봇을 내리는 상황을 정확하게 이해해야합니다. n번째의 로봇이 내린다. 라는걸 이해를 잘 해야합니다.

import java.util.*;

public class Main {
    private int durability;
    private boolean robot;

    public Main(int durability, boolean robot) {
        this.durability = durability;
        this.robot = robot;
    }

    public void setDurability(int durability) {
        this.durability = durability;
    }

    public void setRobot(boolean robot) {
        this.robot = robot;
    }

    public int getDurability() {
        return this.durability;
    }

    public boolean hasRobot() {
        return this.robot;
    }

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
        int k = scan.nextInt();

        Main belt[] = new Main[n * 2];

        for (int i = 0; i < n * 2; i++) {
            int tmp = scan.nextInt();
            belt[i] = new Main(tmp, false);
        }

        int gcnt = 0;
        while (true) {
            // Step 1: Move the belt
            Main tmp = belt[n * 2 - 1];
            for (int i = n * 2 - 1; i > 0; i--) {
                belt[i] = belt[i - 1];
            }
            belt[0] = tmp;

            // Step 1.5: Remove robot at position n-1 (if any)
            belt[n - 1].setRobot(false);

            // Step 2: Move the robots
            for (int i = n - 2; i >= 0; i--) { // 로봇 이동 가능성 검사 범위 수정
                if (belt[i].hasRobot() && !belt[i + 1].hasRobot() && belt[i + 1].getDurability() > 0) {
                    belt[i].setRobot(false);
                    belt[i + 1].setRobot(true);
                    belt[i + 1].setDurability(belt[i + 1].getDurability() - 1);
                    if (i + 1 == n - 1) { // n-1 위치에 도달한 로봇 즉시 내리기
                        belt[i + 1].setRobot(false);
                    }
                }
            }


            // Step 3: Add a new robot
            if (belt[0].getDurability() > 0 && !belt[0].hasRobot()) {
                belt[0].setRobot(true);
                belt[0].setDurability(belt[0].getDurability() - 1);
            }

            // Step 4: Check for broken belts
            int brokenCount = 0;
            for (Main m : belt) {
                if (m.getDurability() == 0) {
                    brokenCount++;
                }
            }

            gcnt++;
            if (brokenCount >= k) {
                System.out.println(gcnt);
                break;
            }
        }
        
    }
}

'알고리즘 공부' 카테고리의 다른 글

백준 - 마법사 상어와 파이어볼  (0) 2024.03.03
백준 - 마법사 상어와 비바라기  (1) 2024.02.24
백준 빗물  (0) 2024.02.11
백준 미로 만들기  (1) 2024.02.02
백준 괄호의 값  (1) 2024.01.24

https://www.acmicpc.net/problem/14719

 

14719번: 빗물

첫 번째 줄에는 2차원 세계의 세로 길이 H과 2차원 세계의 가로 길이 W가 주어진다. (1 ≤ H, W ≤ 500) 두 번째 줄에는 블록이 쌓인 높이를 의미하는 0이상 H이하의 정수가 2차원 세계의 맨 왼쪽 위치

www.acmicpc.net

설이라 좀 많이 쉬었네요 ㅎㅎ 

그 뭔가 이 문젠 구현 문제보단 그리드문제에 좀더 가까운것같네요... 어렵더군요 ㅠ 

키 포인트는 가장 왼쪽벽, 가장 오른쪽 큰벽을 구한다음에 현재 블록에서 두개의 왼,오른쪽의 높은값중 가장 낮은 높이차를 구한후 합하는게 포인트입니다.

package test01;
import java.util.*;

public class Main {
    public static void main(String[] args) throws Exception {
    	
    	Scanner scan=new Scanner(System.in);
        	int h=scan.nextInt();//4
        	int w=scan.nextInt();//8
        	int block[]=new int[w];
        	int start=0;
        	int end=0;
        	int min=0;
        	for(int i=0;i<w;i++) {
        		block[i]=scan.nextInt();
        	}
        	 int answer = 0;
        	
        	 for (int i = 1; i < w - 1; i++) {
                 int leftMax = 0;
                 int rightMax = 0;
                 
                 for (int j = 0; j < i; j++) {
                     leftMax = Math.max(leftMax, block[j]);
                 }

                 for (int j = i + 1; j < w; j++) {
                     rightMax = Math.max(rightMax, block[j]);
                 }

                 int water = Math.min(leftMax, rightMax) - block[i];
                 if (water > 0) {
                     answer += water;
                 }
             }
             System.out.println(answer);
        
    }
    
}

'알고리즘 공부' 카테고리의 다른 글

백준 - 마법사 상어와 비바라기  (1) 2024.02.24
백준 컨베이어 밸트 위의 로봇  (1) 2024.02.17
백준 미로 만들기  (1) 2024.02.02
백준 괄호의 값  (1) 2024.01.24
백준 톱니바퀴  (0) 2024.01.17

2024.02.03 - [끄적이기] - JPA에 대해서

 

JPA에 대해서

JPA? 자바 퍼시스턴스(Java Persistence, 이전 이름: 자바 퍼시스턴스 API/Java Persistence API) 또는 자바 지속성 API(Java Persistence API, JPA)는 자바 플랫폼 SE와 자바 플랫폼 EE를 사용하는 응용프로그램에서 관

kwaksh2319.tistory.com

Spring Data 저장소 추상화의 중앙 인터페이스는 Repository입니다. 관리할 도메인 클래스와 도메인 클래스의 식별자 유형을 유형 인수로 사용합니다. 이 인터페이스는 주로 작업할 유형을 캡처하고 이 인터페이스를 확장하는 인터페이스를 검색하는 데 도움이 되는 마커 인터페이스 역할을 합니다. CrudRepository 및 ListCrudRepository 인터페이스는 관리되는 엔터티 클래스에 대한 정교한 CRUD 기능을 제공합니다.

 

public interface CrudRepository<T, ID> extends Repository<T, ID> {

  <S extends T> S save(S entity);   //1

  Optional<T> findById(ID primaryKey); ///2

  Iterable<T> findAll(); //3

  long count(); //4

  void delete(T entity); //5

  boolean existsById(ID primaryKey); //6

  // … more functionality omitted.
}

 

  1. entity를 저장합니다.
  2. entity에서 id 식별자를 통해서 return 합니다.
  3. 모든 entity를 return 합니다.
  4. entities들의 숫자를 return합니다.
  5. entity를 삭제합니다.
  6. id 식별자를 entity에서  존재 여부를 확인합니다. 

이 메서드들은 CRUD 메서드들를 참조하여 일반적으로 인터페이스에 명시된 메서들입니다.

ListCrudRepository는  동등한 메서들을 제공합니다. 그러나 CrudRepository는 Iterable리턴하지만 

ListCrudRepository는 list를 return 합니다.

 

CrudRepository 외에도 엔터티에 대한 페이지 매김 액세스를 쉽게 하기 위해 추가 메서드를 추가하는 PagingAndSortingRepository 및 ListPagingAndSortingRepository가 있습니다.

public interface PagingAndSortingRepository<T, ID>  {

  Iterable<T> findAll(Sort sort);

  Page<T> findAll(Pageable pageable);
}

 

페이지 크기 20으로 User의 두 번째 페이지에 액세스하려면 다음과 같이 할 수 있습니다.

PagingAndSortingRepository<User, Long> repository = // … get access to a bean
Page<User> users = repository.findAll(PageRequest.of(1, 20));

 

ListPagingAndSortingRepository는 동등한 메서드를 제공하지만 PagingAndSortingRepository 메서드가 Iterable을 반환하는 List를 반환합니다

 

쿼리 방식 외에도 개수 쿼리와 삭제 쿼리 모두에 대한 쿼리 파생이 가능합니다. 다음 목록은 파생된 카운트 쿼리에 대한 인터페이스 정의를 보여줍니다.

interface UserRepository extends CrudRepository<User, Long> {

  long countByLastname(String lastname);
}

다음 목록은 파생된 삭제 쿼리에 대한 인터페이스 정의를 보여줍니다.

interface UserRepository extends CrudRepository<User, Long> {

  long deleteByLastname(String lastname);

  List<User> removeByLastname(String lastname);
}

https://docs.spring.io/spring-data/jpa/reference/repositories/core-concepts.html

 

Core concepts :: Spring Data JPA

The methods declared in this interface are commonly referred to as CRUD methods. ListCrudRepository offers equivalent methods, but they return List where the CrudRepository methods return an Iterable.

docs.spring.io

 

+ Recent posts