Skip to content

Commit

Permalink
🔨 refactor: google translator 호출 시 동기화 매커니즘 적용
Browse files Browse the repository at this point in the history
  • Loading branch information
choihuk committed Mar 31, 2024
1 parent f8e24da commit a9b4914
Showing 1 changed file with 15 additions and 16 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
Expand Down Expand Up @@ -51,35 +52,33 @@ public int addGptGeneratorContent(Long userId) {
validateUserService.validateAdminUserById(userId);
List<GetDiaryNoteAndPromptResponse> responses = adminDiaryService.getDiaryNoteAndPrompt();
ExecutorService executor = Executors.newFixedThreadPool(10);
CountDownLatch latch = new CountDownLatch(responses.size());
for (int i = 0; i < responses.size(); i++) {
GetDiaryNoteAndPromptResponse response = responses.get(i);
int finalI = i;
executor.execute(() -> {
AtomicInteger count = new AtomicInteger(responses.size());

CompletableFuture<?>[] futures = responses.stream()
.map(response -> CompletableFuture.runAsync(() -> {
try {
String translatedNotes = translateTextService.translateAutoToEnglish(
response.getNotes());
response.updateNotes(translatedNotes);
} catch (Exception e) {
log.error("번역 API 예외가 발생했습니다.", e);
responses.remove(finalI);
} finally {
latch.countDown();
count.decrementAndGet();
}
});
}
}, executor))
.toArray(CompletableFuture[]::new);

CompletableFuture<Void> allFutures = CompletableFuture.allOf(futures);

try {
latch.await();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
allFutures.join();
} catch (Exception e) {
log.error("작업이 중단되었습니다.", e);
throw new RuntimeException(e);
} finally {
executor.shutdown();
}

if (responses.isEmpty()) {
if (count.get() == 0) {
throw new RuntimeException("번역할 데이터가 없거나 모두 실패했습니다.");
}

Expand All @@ -101,6 +100,6 @@ public int addGptGeneratorContent(Long userId) {
prompt.updatePromptGeneratorResult(result);
}
});
return responses.size();
return count.get();
}
}

0 comments on commit a9b4914

Please sign in to comment.