반응형

개발 중 코드 중에서 Runnable lambda 문법을 이용해서 Thread 코드를 구현을 하였다. 

그런데 Thread 코드 내부에서 서블릿의 remote ip 코드가 일부 위치로 옮기면 ip정보가 유실하는 현상이 있었다. 

좀더 인터넷을 찾아보니, Servlet은 클래스 안에 멤버 변수를 사용하게 되면 모든 request에서 해당 변수를 공유 하기 때

문에 메서드 안에 지역 변수로 사용하라고 경고 되어 있다.

즉, Servlets은 클래쓰에 전역 변수를 사용하게 되면 session당 해당 변수를 공유하기 때문에 사용하면 안되고, Servelt 변

수를 사용하고 싶으면 메서드 지역변수에 저장해서 쓰라는 말이다.

public class ExampleServlet extends HttpServlet {

    private Object thisIsNOTThreadSafe;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Object thisIsThreadSafe;

        thisIsNOTThreadSafe = request.getParameter("foo"); // BAD!! Shared among all requests!
        thisIsThreadSafe = request.getParameter("foo"); // OK, this is thread safe.
    } 
}

출처 : https://stackoverflow.com/questions/3106452/how-do-servlets-work-instantiation-sessions-shared-variables-and-multithreadi/3106909#3106909

 

How do servlets work? Instantiation, sessions, shared variables and multithreading

Suppose, I have a webserver which holds numerous servlets. For information passing among those servlets I am setting session and instance variables. Now, if 2 or more users send request to this se...

stackoverflow.com

그래서 다음과 같이 Servlet에서 받은 원격지 주소를 메서드 안에 지역 변수로 초기화해서 사용하였다.

String remoteIp = req.getRemoteAddr();//중요!!!
if (returnCode == -22) {

  Runnable runnable = () -> {
    try {
      TCPSocketUtil tcpSocketUtil = new TCPSocketUtil(installDBProperty.getSocketAddress(),installDBProperty.getSocketPort());
      jObj.addProperty("event", SocketEventNames.LOGIN_LOCK.getEventName());
      jObj.addProperty("remote_ip", remoteIp);
      jObj.addProperty("userid", loginAccountVO.getUserId());
      jObj.addProperty("auth", "manager");
      jObj.add("uids", uidsArr);
      tcpSocketUtil.sendMsg(gson.toJson(jObj));
    } catch (Exception e) {
      e.printStackTrace();
    }
  };

  Thread thread = new Thread(runnable);
  thread.start();

}
728x90
반응형
package com.ji.main;

import java.util.Arrays;
import java.util.PriorityQueue;

public class DiscoController {

	public static void main(String[] args) {
		int result = solution(new int[][] { { 0, 3 }, { 1, 9 }, { 2, 6 } });
		System.out.println(result);
	}

	public static int solution(int[][] jobs) {
		int answer = 0;
		int count = 0;// 처리된 디스크
		int now = 0;// 작업이 끝난시간

		//요청시간 순으로 오름 차순 정렬
		Arrays.sort(jobs, ((o1, o2) -> o1[0] - o2[0]));

		// 처리 시간 오름 차순 정렬되는 우선 순위 큐
		PriorityQueue<int[]> queue = new PriorityQueue<>(((o1, o2) -> o1[1] - o2[1]));
		
		int i = 0;
		while (count < jobs.length) {
			
			// 하나의 작업이 완료될때까지 모든 요청을 큐에 넣음
			while (i < jobs.length && jobs[i][0] <= now) {
				queue.add(jobs[i++]);
			}

			// queue가 비어있을 경우는 작업 완료 이후
			if (queue.isEmpty()) {
				now = jobs[i][0];//다음 작업의 요청 시작 시작으로 맞춰줌
			} else { 
				//우선순위 큐에 의해서 수행 시간이 가장 짧은 처리 디스크 반환
				int[] tmp = queue.poll();
				answer += tmp[1] + now - tmp[0];
				now += tmp[1];
				count++;
			}
		}

		return answer / jobs.length;
	}

}
728x90

'[개발관련] > 코테준비' 카테고리의 다른 글

[프로그래머스] 여행경로  (0) 2021.09.22
[프로그래머스] 네트워크  (0) 2021.08.07
[프로그래머스] 체육북  (0) 2021.08.07
[백준] 최소 신장 트리  (0) 2021.08.07
[백준] 소문난 칠공주  (0) 2021.08.07
반응형
package com.ji.dfs;

public class MakeBigNumber {

	public static void main(String[] args) {
		System.out.println(solution("1924", 2));
		System.out.println(solution("1231234", 3));
		System.out.println(solution("4177252841", 4));
	}

	public static String solution(String number, int k) {
		 StringBuilder answer = new StringBuilder();

		 // String[] numberArr = number.split(""); 시간 초과 발생!!!
			char[] numberArr = number.toCharArray();

			int startIndex = 0;
			for (int i = 0; i < numberArr.length - k; i++) {
				char maxNum ='0';

				for (int j = startIndex; j <= k + i; j++) {
					if (numberArr[j]> maxNum) {
						maxNum = numberArr[j];
						//이미 선택한 최대값을 지나치기 위해서 초기화
						startIndex = j + 1;
					}
				}
				answer.append(String.valueOf(maxNum));
			}

			return answer.toString();
	}

}
728x90

+ Recent posts