아래는 1년전 쯤 개발했던 httpUrlConnection 모듈이다

https://developyo.tistory.com/10?category=688588

 

시간이 지날 수록 소스는 누더기가 되어가고..

디자인패턴을 공부하고, 객체지향스러운 개발을 위해 이책 저책(클린코드 도서 등) 읽고나니

위 코드가 리펙토링이 필요하다는 것을 느껴 리펙토링을 해보았다.

 

상황]

1. 연동되는 서버가 계속해서 늘어났다.

2. 각각의 연동 서버에 맞춰야 되는 예외상황들이 늘어났다. (ex: timeout, charset, retry, responsecode..)

3. 예외상황들을 처리 하기 위한 파라미터들을 받기 위해 메소드의 인자값이 늘어났다.

4. 오버로딩되는 메소드가 늘어났다.

 

방향]

1. 객체를 받도록 처리하자. 

: 파라미터는 적을 수록 좋고,  파라미터가 너무 많이지면 객체를 파라미터로 받도록 소스를 리펙토링 해야한다.

2. boolean 값을 받는 메소드 1개는 두개의 메소드 따로 만들자. (도서 클린코드 참고)

: requestApi(boolean isJsonFormat, ...) 와 같이 boolean 값을 파라미터로 받은 후 분기처리 처리하지 말고

requestApiJsonFormat(...), requestApi(...) 와 같이 두개의 메소드로 분리해야 한다. (도서 클린코드 참고)

3. 필수값과 optional 값을 구분하기 위해 builder 패턴을 적용하여 객체를 설계해보자.

4. 전처리 후처리 로깅을 proxy 패턴을 적용하여 처리해보자. 

5. junit 을 사용하여 테스트해보자. (junit 관련 포스팅1, junit 관련 포스팅2)

 

1. RequestForm

httpUrlConnection 호출에 필요한 파라미터 정보 객체

빌더패턴을 적용하여 필수 파라미터(목적지주소, http method)는 생성자로,

그외 optional 파라미터는 setter 로 받도록 했다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package com.jpp.web.util.HttpUtil;
 
import java.util.Map;
 
public class RequestForm {
   
   private final int tryCount;
   private final int connectionTimeOut;
   private final int readTimeOut;
   private final String httpMethod;
   private final String url;
   private final Map<String, Object> header;
   private final int httpStatus;
   private final String requestCharset;
   private final String responseCharset;
   
   public static class Builder {
      private String httpMethod; //required
      private String url;        //required
      private int tryCount = 1;  //optional
      private int connectionTimeOut = 1000;  //optional
      private int readTimeOut = 1000;     //optional
      private Map<String, Object> header; //optional
      private int httpStatus = 0;    //optional
      private String requestCharset = "UTF-8";
      private String responseCharset = "UTF-8";
      
      public Builder(String httpMethod, String url) {
         this.httpMethod = httpMethod;
         this.url = url;
      }
      
      public Builder setTryCount(int tryCount) {
         this.tryCount = tryCount<1?1:tryCount;
         return this;
      }
      
      public Builder setConnectionTimeOut(int connectionTimeOut) {
         this.connectionTimeOut = connectionTimeOut<100?1000:connectionTimeOut;
         return this;
      }
      
      public Builder setReadTimeOut(int readTimeOut) {
         this.readTimeOut =  readTimeOut<100?1000:readTimeOut;
         return this;
      }
      
      public Builder setHeader(Map<String, Object> header) {
         this.header = header;
         return this;
      }
      
      public Builder setExpectedHttpStatus(int httpStatus) {
         this.httpStatus = httpStatus;
         return this;
      }
      
      public Builder setRequestCharset(String requestCharset) {
         this.requestCharset = requestCharset;
         return this;
      }
      
      public Builder setResponseCharset(String responseCharset) {
         this.responseCharset = responseCharset;
         return this;
      }
      
      public RequestForm build() {
         return new RequestForm(this);
      }
   }
   
   public RequestForm(Builder builder) {
      this.httpMethod = builder.httpMethod;
      this.url = builder.url;
      this.tryCount = builder.tryCount;
      this.connectionTimeOut = builder.connectionTimeOut;
      this.readTimeOut = builder.readTimeOut;
      this.header = builder.header;
      this.httpStatus = builder.httpStatus;
      this.requestCharset = builder.requestCharset;
      this.responseCharset = builder.responseCharset;
   }
   
   public int getTryCount() {
      return tryCount;
   }
 
   public int getConnectionTimeOut() {
      return connectionTimeOut;
   }
 
   public int getReadTimeOut() {
      return readTimeOut;
   }
 
   public String getHttpMethod() {
      return httpMethod;
   }
 
   public String getUrl() {
      return url;
   }
   
   public Map<String, Object> getHeader(){
      return header;
   }
   
   public int getHttpStatus() {
      return httpStatus;
   }
 
   public String getRequestCharset() {
      return requestCharset;
   }
 
   public String getResponseCharset() {
      return responseCharset;
   }
   
}
 
cs

 

 

2. CustomHttpUrlConnection

java.net.HttpUrlConnection 객체를 사용하여 외부 서버 api를 호출하는 역할을 하는 클래스

1) 요청정보를 담고있는 RequestForm객체를 파라미터로 받도록 했다.

2) jsonFormat(body로 호출) 여부인 boolean 값을 파라미터로 받아 내부에서 분기처리하는게 아닌, 별도의 메소드로 각각 분리했다.

메소드를 작은 단위로 쪼개면 코드 중복이 많이 줄어들 것 같은데 나중에..

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
package com.jpp.web.util.HttpUtil;
 
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;
 
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
import com.google.gson.Gson;
import com.jpp.web.comm.CustomException;
import com.jpp.web.constants.Constants;
import com.jpp.web.constants.ConstantsEnum;
 
public class CustomHttpUrlConnection {
   
   private static final Logger logger = LoggerFactory.getLogger(CustomHttpUrlConnection.class);
   private static final String UTF_8 = "UTF-8";
 
   private int responseCode = 0;
   private long startTime = 0;
 
   private RequestForm reqForm;
   private Map<String, Object> reqParams;
   
   public CustomHttpUrlConnection(RequestForm reqForm, Map<String, Object> reqParams){
      this.reqForm = reqForm;
      this.reqParams = reqParams;
   }
   
   public int getResponseCode() {
      return responseCode;
   }
   
   public long getStartTime() {
      return startTime;
   }
   
   public String requestApi() {
      
      this.startTime = System.currentTimeMillis();
      
      String httpMethod = reqForm.getHttpMethod();  
      String surl = reqForm.getUrl();               
      int tryCnt = reqForm.getTryCount();   
      int readTimeOut = reqForm.getReadTimeOut(); 
      int connectionTimeOut = reqForm.getConnectionTimeOut();
      Map<String, Object> header = reqForm.getHeader();
      int expectedHttpStatus = reqForm.getHttpStatus();
      String requestCharset = reqForm.getRequestCharset();
      String responseCharset = reqForm.getResponseCharset();
      
      String reqCharset = requestCharset==null||requestCharset.isEmpty()?UTF_8:requestCharset;
      String resCharset = responseCharset==null||responseCharset.isEmpty()?UTF_8:responseCharset;
             
      URL url = null;
      HttpURLConnection conn = null;
      BufferedReader br = null;
      JSONObject jobj = null;
      String postParams = "";
      String errMsg = "";
      String returnText = "";
 
      
      for(int i=0; i < tryCnt; i++){
          
         try {
             
            if(httpMethod.equalsIgnoreCase(Constants.POST) || httpMethod.equalsIgnoreCase(Constants.DELETE)){
               url = new URL(surl);
            } else if(httpMethod.equalsIgnoreCase(Constants.GET)){
               url = new URL(surl + ((reqParams!=null)?"?"+makeUrlEncodedParams(reqParams, reqCharset):""));
            }
            
            conn = (HttpURLConnection) url.openConnection();
            
            if(header != null){
                for(String key : header.keySet()) {
                    conn.setRequestProperty(key, header.get(key)!=null?header.get(key).toString():"");
                }
            }
             
            conn.setRequestMethod(httpMethod);
            conn.setConnectTimeout(connectionTimeOut);
            conn.setReadTimeout(readTimeOut);
            conn.setDoOutput(true);
            
            if(httpMethod.equalsIgnoreCase(Constants.POST) || httpMethod.equalsIgnoreCase(Constants.DELETE)){
               if(reqParams != null){
                  postParams = makeUrlEncodedParams(reqParams, reqCharset);
                  conn.getOutputStream().write(postParams.getBytes(UTF_8));
                  conn.getOutputStream().flush();
               }
            }
            
            this.responseCode = conn.getResponseCode();
            
            if(expectedHttpStatus > 0){
               if(expectedHttpStatus!=conn.getResponseCode()){
                  throw new CustomException("successCode : {" + expectedHttpStatus + "}" + " , responseCode : {" + this.responseCode + "}", ConstantsEnum.API_RESULT.E_NETWORK.getCode());
               }
            }
            
            br = new BufferedReader(new InputStreamReader(conn.getInputStream(),resCharset));
            
            StringBuffer sb = null;
            sb = new StringBuffer();
            
            String jsonData = "";
            while((jsonData = br.readLine()) != null){
               sb.append(jsonData);
            }
            returnText = sb.toString();
            
            try{
               jobj = new JSONObject(returnText);
            } catch (JSONException e){
               throw new CustomException();
            }
            
            break;
            
         } catch (SocketTimeoutException se){
            logger.error("connection fail : " + se);
             errMsg = se.getMessage();
         } catch (CustomException e){
            logger.error("response fail : " + e);
             errMsg = e.getMessage();
         } catch (Exception e){
            throw new CustomException(e.getMessage().toString(), ConstantsEnum.API_RESULT.E_NETWORK.getCode());
         } finally {
            try {
               if (br != null) br.close();
            } catch(Exception e){
               logger.warn("finally..br.close()", e);
            }
            br = null;
            try {
               if(conn!=null) {
                  conn.disconnect();
               }
            } catch(Exception e){
               logger.warn("finally..conn.disconnect()", e);
            }
            conn = null;
         }
      }
      
      if(jobj!=null){
         return jobj.toString();
      } else {
         throw new CustomException(errMsg, ConstantsEnum.API_RESULT.E_NETWORK.getCode());
      }
   }
   
   
   public String requestApiWithJsonForm() {
      
      this.startTime = System.currentTimeMillis();
      
      String httpMethod = reqForm.getHttpMethod();
      int tryCnt = reqForm.getTryCount();
      int readTimeOut = reqForm.getReadTimeOut();
      int connectionTimeOut = reqForm.getConnectionTimeOut();
      String surl = reqForm.getUrl();
      Map<String, Object> header = reqForm.getHeader();
      int expectedHttpStatus = reqForm.getHttpStatus();
      String responseCharset = reqForm.getResponseCharset();
      
      String resCharset = responseCharset==null||responseCharset.isEmpty()?UTF_8:responseCharset;
      
      URL url = null;
      HttpURLConnection conn = null;
      BufferedReader br = null;
      JSONObject jobj = null;
      String postParams = "";
      String errMsg = "";
      String returnText = "";
       
      for(int i=0; i < (tryCnt<1?1:tryCnt); i++){
          
         try {
             
            url = new URL(surl);
            
            conn = (HttpURLConnection) url.openConnection();
            
            if(header != null){
                for(String key : header.keySet()) {
                    conn.setRequestProperty(key, header.get(key)!=null?header.get(key).toString():"");
                }
            }
             
            conn.setRequestProperty("Content-Type""application/json");
            conn.setRequestMethod(httpMethod);
            conn.setConnectTimeout(connectionTimeOut);
            conn.setReadTimeout(readTimeOut);
            conn.setDoOutput(true);
            
            if(reqParams != null){
                postParams = makeJsonParams(reqParams);
                conn.getOutputStream().write(postParams.getBytes(UTF_8));
                conn.getOutputStream().flush();
            }
            
            this.responseCode = conn.getResponseCode();
            
            if(expectedHttpStatus != 0){
               if(expectedHttpStatus!=conn.getResponseCode()){
                  throw new CustomException("successCode : {" + expectedHttpStatus + "}" + " , responseCode : {" + this.responseCode + "}", ConstantsEnum.API_RESULT.E_NETWORK.getCode());
               }
            }
            
            br = new BufferedReader(new InputStreamReader(conn.getInputStream(), resCharset));
            
            StringBuffer sb = null;
            sb = new StringBuffer();
            
            String jsonData = "";
            while((jsonData = br.readLine()) != null){
               sb.append(jsonData);
            }
            returnText = sb.toString();
            
            try{
               jobj = new JSONObject(returnText);
            } catch (JSONException e){
               throw new CustomException();
            }
            
            break;
            
         } catch (SocketTimeoutException se){
            logger.error("connection fail : " + se);
             errMsg = se.getMessage();
         } catch (CustomException e){
            logger.error("response fail : " + e);
             errMsg = e.getMessage();
         } catch (Exception e){
            throw new CustomException(e.getMessage().toString(), ConstantsEnum.API_RESULT.E_NETWORK.getCode());
         } finally {
            try {
               if (br != null) br.close();
            } catch(Exception e){
               logger.warn("finally..br.close()", e);
            }
            br = null;
            try {
               if(conn!=null) {
                  conn.disconnect();
               }
            } catch(Exception e){
               logger.warn("finally..conn.disconnect()", e);
            }
            conn = null;
         }
      }
      
      if(jobj!=null){
         return jobj.toString();
      } else {
         throw new CustomException(errMsg, ConstantsEnum.API_RESULT.E_NETWORK.getCode());
      }
   }
    
   
   private String makeUrlEncodedParams(Map<String, Object> params, String charset) throws Exception{
      String param = "";
      StringBuffer sb = new StringBuffer();
      
      if(params != null){
         for ( String key : params.keySet() ){
             try {
                sb.append(key).append("=").append((params.get(key)==null?"":URLEncoder.encode(params.get(key).toString(), charset)).toString().trim()).append("&");
             } catch (UnsupportedEncodingException e) {
                logger.error("ex while encoding : {}", e.getMessage());
                throw e;
             }
         }
         param = sb.toString().substring(0, sb.toString().length()-1);
      }
      return param;
   }
  
   
   private String makeJsonParams(Map<String, Object> params){
      String json = "";
      if(params != null){
          json = new Gson().toJson(params);
      }
      return json;
   }
   
}
 
 
cs

 

 

3. HttpUtil

클라이언트에서 실제로 사용될 클래스

1) 프록시(proxy) 패턴을 적용하여 CustomHttpUrlConnection객체의 requestApi(), requestApiWithJsonForm() 메소드를 호출하기 전과 후에 logging 메소드가 호출되도록 했다

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package com.jpp.web.util.HttpUtil;
 
import java.util.Map;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
public class HttpUtil {
    
   private static final Logger logger = LoggerFactory.getLogger(HttpUtil.class);
   
   private RequestForm reqForm;
   private Map<String, Object> reqParams;
   private CustomHttpUrlConnection httpUrlConnection;
   
   public HttpUtil(RequestForm reqForm, Map<String, Object> reqParams) {
      this.reqForm = reqForm;
      this.reqParams = reqParams;
      httpUrlConnection = new CustomHttpUrlConnection(reqForm, reqParams);
   }
   
   public String requestApi() {
      printBeforeLog();
      String resParams = httpUrlConnection.requestApi();
      printAfterLog(resParams);
      return resParams;
   }
   
   public String requestApiWithJsonForm() {
      printBeforeLog();
      String resParams = httpUrlConnection.requestApiWithJsonForm();
      printAfterLog(resParams);
      return resParams;
   }
   
   private void printBeforeLog() {
      logger.info("HTTPCONNECTION.REQUEST|URL:{}|IN_PARAMS:{}"
            , reqForm.getUrl(), reqParams);
   }
   
   private void printAfterLog(String resParams) {
      logger.info("HTTPCONNECTION.RESPONSE|URL:{}|TIME:{}|STATUS_CODE:{}|IN_PARAMS:{}|OUT_PARAMS:{}"
            , reqForm.getUrl()
            , System.currentTimeMillis() - httpUrlConnection.getStartTime()
            , httpUrlConnection.getResponseCode()<1?"":httpUrlConnection.getResponseCode()
            , reqParams
            , resParams);
   }
   
}
 
cs

 

4. test

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package com.jpp.web.util.HttpUtil;
 
import java.util.HashMap;
import java.util.Map;
 
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
 
@RunWith(SpringRunner.class)
@SpringBootTest
public class HttpUtilTest {
   
   private static final Logger logger = LoggerFactory.getLogger(HttpUtil.class);
   
   @Test
   public void test() {
      RequestForm reqForm = new RequestForm.Builder("GET""127.0.0.1:8082/mobile/device")
            .setConnectionTimeOut(1000)
            .setReadTimeOut(1000)
            .setTryCount(3)
            .build();
      
      Map<String, Object> reqParams = new HashMap<String, Object>();
      reqParams.put("deviceType""1");
      reqParams.put("osVersion""10");
      
      String apiResult = new HttpUtil(reqForm, reqParams).requestApiWithJsonForm();
      logger.info(apiResult);
   }
 
   @Test
   public void test2() {
      RequestForm reqForm = new RequestForm.Builder("GET""127.0.0.1:8082/mobile/version")
            .setConnectionTimeOut(1000)
            .setReadTimeOut(1000)
            .setTryCount(3)
            .build();
      
      Map<String, Object> reqParams = new HashMap<String, Object>();
      
      String rs = new HttpUtil(reqForm, reqParams).requestApi();
      logger.info(rs);
   }
}
 
cs

 

소스리뷰를 받고싶다..

 

모든 코드는 제 github(https://github.com/develo-pyo/boot-mybatis)에 올려놓았습니다.

반응형

 

예제를 위한 클래스

1. ExampleSuperClass : 부모클래스

1
2
3
4
5
package Java.reflection;
 
public class ExampleSuperClass {
}
 
cs

 

2. ExampleClass : 예제 클래스

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package Java.reflection;
 
public class ExampleClass extends ExampleSuperClass {
   
   private static final String CONSTANT_FIELD = "constant_field";
   public int i = 1;
   public String publicField = "publicStrField";
   private String privateField = "privateStrField";
   
   public ExampleClass() { 
   }
   
   public ExampleClass(Object a) throws NullPointerException {
   }
   
   private int privateMethod(Object a, int b) throws NullPointerException {
      if(a == null) {
         throw new NullPointerException();
      }
      return b;
   }
   
   public String addStrInt(String a, int b) {
      return a+b;
   }
}
cs

 

3. ExampleChildClass : 자식 클래스

1
2
3
4
package Java.reflection;
 
public class ExampleChildClass extends ExampleClass {       
}
cs

 

 

Java Reflection 의 사용 예

1. isInstance 사용법 

instanceof 와 같은 역할을 수행

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package Java.reflection;
 
//https://gyrfalcon.tistory.com/entry/Java-Reflection
 
//instance of
public class Reflection1_instanceof {
   public static void main(String[] args) {
      
      //classA.isInstance(B);
      //B가 A의 인스턴스인지를 확인
      Class clazz = ExampleClass.class;
      
      boolean rs1 = clazz.isInstance(new ExampleSuperClass());
      System.out.println(rs1);
      boolean rs2 = clazz.isInstance(new ExampleClass());
      System.out.println(rs2);
      boolean rs3 = clazz.isInstance(new ExampleChildClass());
      System.out.println(rs3);
 
   }
}
 
cs

[결과]

false
true
true

 

2. 클래스에서 메소드 정보 가져오기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package Java.reflection;
 
import java.lang.reflect.Method;
 
//Method 정보 가져오기
public class Reflection2_FindMethod {
 
   public static void main(String[] args) throws Exception {
      
      //1. class 가져오기
      Class clazz = Class.forName("Java.reflection.ExampleClass");
      //1-1. class 가져오기(위와 같다)
      Class clazz1 = ExampleClass.class;
      
      //2. class 에서 method 가져오기
      Method methodArr[] = clazz.getDeclaredMethods();
      
      for(Method method : methodArr) {
         
         //1) 메소드명 가져오기
         System.out.println("name = " + method.getName());
         
         //2) 선언된 클래스명 가져오기
         System.out.println("class = " + method.getDeclaringClass());
         
         //3) Parameter Type 가져오기
         Class paramTypes[] = method.getParameterTypes();
         for(Class p : paramTypes) {
            System.out.println("param type : " + p);
         }
      
         //4) exception Type 가져오기
         Class exceptionTypes[] = method.getExceptionTypes();
         for(Class e : exceptionTypes) {
            System.out.println("exception type : " + e);
         }
         
         //5) return Type 가져오기
         System.out.println("return type : "+method.getReturnType());
         
         System.out.println();
      }
   }
}
 
cs

[결과]

name = privateMethod
class = class Java.reflection.ExampleClass
param type : class java.lang.Object
param type : int
exception type : class java.lang.NullPointerException
return type : int

name = addStrInt
class = class Java.reflection.ExampleClass
param type : class java.lang.String
param type : int
return type : class java.lang.String

 

3. 생성자(Constructor) 정보 찾기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package Java.reflection;
 
import java.lang.reflect.Constructor;
 
//Constructor 정보 가져오기
public class Reflection3_FindConstructor {
     
   public static void main(String[] args) throws Exception {
      
      //1. class 가져오기
      Class clazz = ExampleClass.class;
      
      //2. class 에서 Constructor 가져오기
      Constructor constructors[] = clazz.getDeclaredConstructors();
      
      for(Constructor c : constructors) {
         
         //1) 생성자명 가져오기
         System.out.println("name : " + c.getName());
         
         //2) 선언된 클래스명 가져오기
         System.out.println("class : " + c.getDeclaringClass());
         
         //3) parameter type 가져오기
         Class paramTypes[] = c.getParameterTypes();
         for(Class p : paramTypes) {
            System.out.println("param type : " + p);
         }
      
         //4) exception Type 가져오기
         Class exceptionTypes[] = c.getExceptionTypes();
         for(Class e : exceptionTypes) {
            System.out.println("exception type : " + e);
         }
         
         //5) 생성자에 return type은 존재하지 않으므로 getReturnType() 메소드는 없음 
         System.out.println();
      }
   }
}
 
cs

[결과]

name : Java.reflection.ExampleClass
class : class Java.reflection.ExampleClass

name : Java.reflection.ExampleClass
class : class Java.reflection.ExampleClass
param type : class java.lang.Object
exception type : class java.lang.NullPointerException

 

4. 필드 정보 찾기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package Java.reflection;
 
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
 
//Field 정보 가져오기
public class Reflection4_FindFields {
   
   public static void main(String[] args) throws Exception {
      
      //1. class 가져오기
      Class clazz = ExampleClass.class;
      
      //2. class 에서 Field 가져오기
      //Field fields[] = clazz.getFields();        //public modifier(접근제한자) field 만 가져올 수 있다
      Field fields[] = clazz.getDeclaredFields();  //private modifier field 도 가져올 수 있다
      
      for(Field f : fields) {
         
         //1) 필드명 가져오기
         System.out.println("name : " + f.getName());
         
         //2) 필드가 선언된 클래스명 가져오기
         System.out.println("class : " + f.getDeclaringClass());
         
         //3) 필드 타입 가져오기
         System.out.println("type : " + f.getType());
         
         //4) 필드의 접근제한자 가져오기 (int 형이며 Modifier.toString(mod) 로 string으로 바꿔줄 수 있음)
         int modifiers = f.getModifiers();
         System.out.println("modifiers int : " + modifiers);
         System.out.println("modifiers toString : " + Modifier.toString(modifiers));
         System.out.println("isPublic? : " + (modifiers == Modifier.PUBLIC));
         
         System.out.println();
      }
   }
}
 
cs

[결과]

name : CONSTANT_FIELD
class : class Java.reflection.ExampleClass
type : class java.lang.String
modifiers int : 26
modifiers toString : private static final
isPublic? : false

name : i
class : class Java.reflection.ExampleClass
type : int
modifiers int : 1
modifiers toString : public
isPublic? : true

생략..

 

5. 메소드 실행시키기 (invoke)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package Java.reflection;
 
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
 
//https://kaspyx.tistory.com/80
 
//5. 메소드 실행시키기 invoke
public class Reflection5_invoke_1 {
   
   public Reflection5_invoke_1() {}
   
   public Reflection5_invoke_1(String a) {}
   
   public Reflection5_invoke_1(String a, Object b) {}
   
   public String addStrInt(String a, int b) {
      return a+b;
   }
   
   @SuppressWarnings({ "unchecked""rawtypes" })
   public static void main(String[] args) throws Exception {
      
      //1. class 가져오기
      Class clazz = Reflection5_invoke_1.class;
      
      Class paramTypes[] = new Class[2];
      paramTypes[0= String.class;
      paramTypes[1= Integer.TYPE;
      Method method = clazz.getMethod("addStrInt", paramTypes);   //* private modifier method 는 찾지 못한다
 
      Reflection5_invoke_1 methodObj = new Reflection5_invoke_1();
      Object argumentList[] = new Object[2]; 
      argumentList[0= "Str ";
      argumentList[1= new Integer(10);
      
      //java 문법은 보통 아래와 같이 S V O 
      //String rs = addStrInt("a", 10);
      //하지만, reflection 은 V.invoke(S, O)
      Object rs = method.invoke(methodObj, argumentList);
      
      System.out.println(rs);
      
   }
   
}
 
cs

[결과]

Str 10

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package Java.reflection;
 
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
 
//https://kaspyx.tistory.com/80
 
//5. 메소드 실행시키기 invoke
public class Reflection5_invoke_2 {
   
   public Reflection5_invoke_2() {}
   
   public Reflection5_invoke_2(String a) {}
   
   public Reflection5_invoke_2(String a, Object b) {}
   
   public String addStrInt(String a, int b) {
      return a+b;
   }
   
   @SuppressWarnings({ "unchecked""rawtypes" })
   public static void main(String[] args) throws Exception {
      
      Method m = ExampleChildClass.class.getMethod("addStrInt"new Class[] {String.class, Integer.TYPE});
      String result = (String) m.invoke(new ExampleClass(), new Object[]{"Str "new Integer(10)});
      System.out.println(result);
      
      //위와 같다
      Method m3 = ExampleChildClass.class.getMethod("addStrInt"new Class[] {String.class, Integer.TYPE});
      String result3 = (String) m3.invoke(new ExampleClass(), new Object[]{"Str "new Integer(10)});
      System.out.println(result3);
      
      try {
         Method m2 = ExampleClass.class.getMethod("addStrInt"new Class[] {String.class, Integer.TYPE});
         String result2 = (String) m2.invoke(new ExampleSuperClass(), new Object[]{"Str "new Integer(10)});
         System.out.println(result2);
      } catch (IllegalArgumentException ie) {
         System.out.println(ie.getMessage());
      }
   }
}
 
cs

[결과]

Str 10
Str 10
object is not an instance of declaring class

 

6. 인스턴스 생성하기 (newInstance)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package Java.reflection;
 
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
 
//https://kaspyx.tistory.com/80
 
//5. 메소드 실행시키기 invoke
public class Reflection6_newInstance {
   
   public Reflection6_newInstance() {}
   
   public Reflection6_newInstance(String a) {}
   
   public Reflection6_newInstance(String a, Object b) {}
   
   public String addStrInt(String a, int b) {
      return a+b;
   }
   
   @SuppressWarnings({ "unchecked""rawtypes" })
   public static void main(String[] args) throws Exception {
      
      Class clazz = Reflection6_newInstance.class;
      
      Class arguTypes[] = new Class[2];
      arguTypes[0= String.class;
      arguTypes[1= Integer.TYPE;
 
      Object params[] = new Object[2];
      params[0= "Str ";
      params[1= 10;
      
      Constructor myConstructor1 = clazz.getConstructor();     
      Object myObj = myConstructor1.newInstance();             
      Method m1 = clazz.getMethod("addStrInt", arguTypes); 
      String result1 = (String) m1.invoke(myObj, params);   
      System.out.println(result1);
      
      Constructor myConstructor2 = clazz.getConstructor(String.class);
      Object myObj2 = myConstructor2.newInstance("");
      Method m2 = clazz.getMethod("addStrInt", arguTypes);
      String result2 = (String) m2.invoke(myObj2, params);
      System.out.println(result2);
      
      Constructor myConstructor3 = clazz.getConstructor(String.class, Object.class);
      Object myObj3 = myConstructor3.newInstance(""new Object());
      Method m3 = clazz.getMethod("addStrInt", arguTypes);
      String result3 = (String) m3.invoke(myObj3, params);
      System.out.println(result3);
      
      Constructor myConstructor4 = clazz.getConstructor(new Class[]{String.class, Object.class});
      Object myObj4 = myConstructor4.newInstance(""new Object());
      Method m4 = clazz.getMethod("addStrInt"new Class[] {String.class, Integer.TYPE});
      String result4 = (String) m4.invoke(myObj4, new Object[] {"String " , 11});
      System.out.println(result4);
      
   }
}
 
cs

[결과]

Str 10
Str 10
Str 10
String 11

 

위의 모든 샘플 예제들은 github(https://github.com/develo-pyo)에 올려놓았습니다.

 

참고:

https://www.geeksforgeeks.org/reflection-in-java/

https://gyrfalcon.tistory.com/entry/Java-Reflection

 

반응형

1. git history 를 제거할 project(local repository) 최상위 경로로 이동

 

2. 기존 git 설정 모두 제거

rm -rf .git

3. git 새로 설정 및 commit

git init

4. .git/ 경로로 이동 후 아래와 같이 config 파일에 git 사용자 정보 추가

[core]
  repositoryformatversion = 0
  filemode = false  
  bare = false  
  logallrefupdates = true
  symlinks = false
  ignorecase = true
[remote "origin"]
  url = https://github.com/develo-pyo/boot-jpa.git
  fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
  remote = origin
  merge = refs/heads/master
[user]
  email = jungpyo9@gmail.com
  name = develo-pyo

5. 모든 파일을 새로 add 및 commit

git add .
git commit -m "first commit"

6. git repository 연결 및 강제 push

git remote add origin {git remote url}
git push -u --force origin master

 

반응형

Page Frame의 Allocation(할당)

: 각 Process에 얼마만큼의 Page Frame을 할당할 것인지의 문제

- 메모리 참조 명령어 수행시 명령어, 데이터 등 여러 페이지를 동시에 참조하므로 명령어 수행을 위해 최소한 할당되어야 하는 frame 의 수가 있다. (page fault 를 줄이기 위해)

Allocation Scheme

Equal allocation : 모든 프로세스에 똑같은 갯수 할당

Proportional allocation : 프로세스 크기에 비례하여 할당

Priority allocation : 프로세스의 priority에 따라 다르게 할당

 

 

Global replacement 와 Local replacement 의 차이

Global replacement

Replace시 다른 process에 할당된 page frame을 빼앗아 올 수 있다

FIFO, LRU, LFU 등의 알고리즘을 global replacement로 사용하는 경우

Working set, PFF 알고리즘 사용

 

Local replacement

자신에게 할당된 frame 내에서만 replacement

FIFO, LRU, LFU 등의 알고리즘을 local(process) 별로 운영시

 

Global replacement 에서의 문제

Thrashing

메모리에 올라와 있는 프로그램이 늘어날 수록 CPU 이용량은 올라가지만, 

메모리에 프로그램이 너무 많이 올라갈 경우 page frame 수 (메모리 할당 용량)가 너무 적어질 경우 page fault 가 매우 빈번하게 발생하게 되어 CPU utilization 은 낮아지고, 프로세스는 page의 페이지를 빼고 넣고를 (swap in/swap out) 반복하게 되어 실제 CPU는 놀게 되는 현상

 

Thrashing 현상을 방지하기 위한 방법들

1. Working-set Model

- Locality에 기반하여 프로세스가 일정 시간 동안 원활하게 수행되기 위해 한꺼번에 메모리에 올라와 있어야 하는 page 들의 집합을 Working Set이라고 한다 (프로세스는 특정 시간 동안 일정 장소만을 집중적으로 참조, 이 장소들의 집합을 working set이라 함)

- Working set 모델에서는 process의 working set 전체가 메모리에 올라와 있어야 수행되고 그렇지 않을 경우 모든 frame을 반납한 후 swap out(suspend) : 묶음으로 넣거나 아예 넣지 않거나

- Thrashing을 방지하고 Muliprogramming degree를 결정한다

 

Working-set Algorithm

- Process들의 working set size의 합이 page frame의 수보다 큰 경우 일부 process를 swap out 시켜 남은 process의 working set을 우선적으로 충족시켜준다

- Working set을 다 할당하고도 page frame이 남는 경우 Swap out 되었던 프로세스에게 working set을 할당

Window size 

Working size가 너무 작으면 locality set(필요한 페이지 묶음)을 모두 수용하지 못할 수 있다

Working size 동안 Working set에 속한 page는 메모리에 유지, 속하지 않는 것은 버린다

 

2. PFF(Page-Fault Frequency) Scheme

Page-fault rate의 상한값과 하한값을 두고, 

Page fault rate 상한값을 넘으면 frame을 더 할당

Page fault rate 하한값 이하면 할당 frame 수를 줄인다

빈 frame이 없으면 일부 프로세스를 swap out

 

Page size의 결정

Page size가 작다면 

필요한 정보만 메모리에 올라와 메모리 이용에 효율적(페이지 단위가 작으므로 작은 크기로 올릴 수 있음)인 장점 등이 있지만, 

Disk seek (디스크 헤드 이동) 시간 증가

Page size를 감소시킬 경우

페이지 수 증가,

페이지 주소를 관리하는 페이지 테이블 크기 증가와 같은 단점이 있다.

위와 같은 이유로 Page 크기를 키우는게 최근 트렌드

 

 

※ 이화여대 반효경 교수님의 운영체제 강의 정리

 

반응형

Demand Paging

- 실제로 필요할 때 page를 메모리에 올리는 것

- I/O 양의 감소

- Memory 사용량 감소

- 빠른 응답 시간

- 더 많은 사용자 수용

 

Valid/Invalid bit 의 사용

- 사용되지 않는 주소영역인 경우, 페이지가 물리적 메모리에 없는 경우 : Invalid

- 처음에는 모든 page entry 가 invalid로 초기화

- address translation 시에 invalid bit이 set 되어 있으면(요청한 주소가 메모리에 올라와 있지 않은 경우) page fault 발생

 

page fault

: 요청한 주소가 메모리에 올라와 있지 않은 경우 발생

invalid page를 접근하면 MMU가 trap을 발생시킨다 (page fault trap)

Kernel Mode로 들어가서 page fault handler 가 invoke된다

 

page fault 처리 순서

1. Invalid reference ? ( if bad address, protection violation ) abort process

2. get an empty page frame (없으면 뺏어온다)

3. 해당 페이지를 disk에서 memory 로 읽어옴

  1) disk I/O가 끝나기까지 이 프로세스는 CPU를 preempt 당한다(block)

  2) Disk read가 끝나면 page tables entry 기록, valid/invalid bit = "valid"

  3) ready Queue에 process를 insert -> dispatch later

4. 이 프로세스가 CPU를 잡고 다시 running

5. 중단되었던 instruction 재개

 

Page replacement

- Free Frame(비어있는 frame(physical memory 영역))이 없는 경우 수행됨

- 어떤 frame을 빼앗아올지 결정해야 한다 (곧바로 사용되지 않을 page를 쫓아내는 것이 좋다)

- 동일한 페이지가 여러 번 메모리에서 쫓겨났다가 다시 들어올 수 있음

 

 

Page fault를 줄이기 위한 Replacement Algorithm의  종류

page-fault rate을 최소화 하는 것이 목표

알고리즘의 평가기준은 주어진 page reference string에 대해 page fault를 얼마나 내는지

 

1. Optimal Algorithm (=Min Algorithm)

- 가장 먼 미래에 참조되는 page를 replace (미래를 안다는 가정)

- 다른 알고리즘의 성능을 측정하는 기준점이 됨(실제 사용은 불가한 offline 알고리즘)

- Belady's optimal algoroithm MIN, OPT 등으로 불림

-> 7번째 수행에서 5를 참조 할 때, 미래에서 가장 나중에 참조되는 4(마지막에서 2번째)를 쫓아내고 대신 5를 넣음

 

2. FIFO Algorithm (first in first out)

먼저 들어온 것을 먼저 내쫓는다

FIFO Anomaly (Belady's Anomaly) : 페이지가 늘어남에도 불구하고 page faults는 증가하는 현상이 발생

 

3. LRU Algorithm (Least Recently Used)

가장 오래전에 참조된 것을 지운다

 

4. LFU Algorithm (Least Frequently Used)

참조 횟수(reference count)가 가장 적은 페이지를 지움

* 최저 참조 횟수인 page가 여럿인 경우

- LFU 알고리즘 자체에는 여러 page 중 임의로 선정

- 성능 향상을 위해 가장 오래 전에 참조된 page를 지우게 구현할 수도 있음

* 장단점

- LRU 처럼 직전 참조 시점만 보는게 아니라 장기적인 시간 규모를 보기 때문에 page의 인기도를 좀 더 정확히 반영할 수 있음

- 참조 시점의 최근성을 반영치 못함

- LRU 보다 구현이 복잡함

 

 

※ LRU, LFU 의 비교

 

LRU

위에 있을 수록 오래된 참조

- linked list 형태

- 참조될 때 맨 아래에 link시킴

- 쫓아낼 경우 맨 위의 페이지 쫓아냄

LFU

LRU 처럼 linked list 형태로 관리하기는 비효율적

: 새로 참조될 때마다 어디에 link 시킬지 판별하기 위해 참조횟수를 비교해야함 (시간 복잡도 O(N)))

linked list 형태 대신 heap 으로 구현, 2진트리로 구성

* 쫓아낼 경우 root를 쫓아내고 heap을 재구성

 

 

캐싱 기법

- 한정된 빠른 공간(캐시)에 요청된 데이터를 저장해 두었다가 후속 요청시 캐시로부터 직접 서비스 하는 방식

- paging system 외에도 cache memory, buffer caching, web caching 등 다양한 분야에서 사용

캐시 운영의 시간 제약

- 교체 알고리즘에서 삭제할 항목을 결정하는 일에 지나치게 많은 시간이 걸리는 경우 실제 시스템에서 사용할 수 없음

- Buffer caching이나 Web caching의 경우

  : O(1) 에서 O(long n) 정도까지 허용

- Paging system인 경우

  : Page fault인 경우에만 OS가 관여함

  : 페이지가 이미 메모리에 존재하는 경우 참조시각 등의 정보를 OS가 알 수 없음

  : O(1)인 LRU의 list 조작조차 불가능

 

* Paging System에서 LRU, LFU는 사용이 불가하다

: page fault 발생시(CPU 제어권이 운영체제로 넘어오면)에만 디스크에서 메모리에 올라온 시간을 알 수 있으며

이미 메모리에 페이지가 있으면 알 수 없음

 

Clock Algorithm(=Second chance algorithm = NRU(Not Recently Used))

LRU의 근사 알고리즘, LRU/LFU 대신 실제 사용되는 알고리즘

reference bit : 참조여부를 의미(1:최근에 참조된 경우, 0:최근에참조되지 않은 경우)

modified bit(=dirty bit) : write(변경) 여부를 의미(1:write 된 페이지, 0:write 되지 않은 페이지) 

1) 최근에 참조된 경우 Reference bit은 1

2) 1인 경우 Reference bit 을 0으로 바꾸고 다음 페이지를 확인(최근에 참조된 페이지인 경우이므로 다음 페이지 확인)

3) 0인 경우를 발견하면 페이지를 내쫓는다

 

 

 

※ 이화여대 반효경 교수님의 운영체제 강의 정리

 

반응형

1. Contiguous allocation (연속 할당)

1-1) 고정분할

1-2) 가변분할

2. Noncontiguous allocation (불연속 할당)

1) Paging 기법

- Page table은 main memory 에 상주

- Page-table base register(PTBR)가 page table을 가리킴

- Page-table length register(PTLR)가 테이블 크기를 보관

- 모든 메모리 접근 연산에는 2번의 memory access 필요

- page table 접근 1번, 실제 data/instruction 접근 1번

- 속도 향상을 위해 자주 사용되는 주소값을 가지고 캐시와 같이 가지고 있는 TLB 사용

 TLB

- TLB 조회시 fullscan이 이루어지므로, parellel search 가 가능한 associative registers 사용

- 주소값이 없으면(miss) page table 사용

- TLB는 context switch 시 flush 된다(process 마다 달라져야 하므로)

 

※ Two-Level Page Table : 2단계 페이지 테이블

32 bit address 사용시 2^32 (4G) 의 주소 공간

page size 가 4K 일 경우 1M개의 page(=page table entry) 가 필요 ( 4G / 4K = 1M )

각 page entry가 4B 일 경우 프로세스당 4M의 page table 필요 (프로세스 하나에 page table 1개)

사용되지 않는 주소 공간에 대한 outer page table 의 엔트리 값은 NULL (대응하는 inner page table 이 없음)

 

inner page table의 크기는 page 크기와 동일. inner page table 은 page 내에 존재

page 하나는 4KB(inner page table도 마찬가지),  entry 1개는 4Byte entry 는 총 1K 개

 

page offset : 4KB(페이지크기) = 2^12 

P2 : page entry 갯수 1K = 2^10

P1은 outer pager table 의 index

P2는 outer page table의 page에서의 변위(displacement)

 

※ Multi-Level Paging : 멀티 레벨 페이징

- Address space가 커지면 다단계 페이지 테이블 필요

- 각 단계의 페이지 테이블이 메모리에 존재하므로 logical address의 physical address변환에 더 많은 메모리 접근 필요

- TLB를 통해 메모리 접근 시간을 줄일 수 있음

 

Memory Protection

Page table의 각 entry 마다 아래의 bit를 둔다

1) Protection bit

 : page에 대한 read/write/read-only 권한

 ex) code영역은 read-only, data 및 stack 영역은 read/write

2) Valid-invalid bit (아래 그림 참고)

 : valid는 해당 주소의 frame에 그 프로세스를 구성하는 유효한 내용이 있음을 뜻함(접근 허용)

 : invalid는 해당 주소의 frame에 유효한 내용이 없음을 뜻함

  (프로세스가 그 주소 부분을 사용하지 않거나 해당 페이지가 메모리에 올라와 있지 않고 swap area에 있는 경우)

 

Inverted Page Table

- Page frame 하나당 page table에 하나의 entry 를 둔 것(system-wide:시스템에 하나만 존재)

- 각 page table entry는 각각의 물리적 메모리의 page frame이 담고 있는 내용 표시(process-id, process의 logical address)

- 물리주소로 논리주소를 역으로 찾아야 하기 때문에(value 기준으로 key를 찾아야) 검색에 overhead가 큼(associative register 사용하여 해당 문제 해소)

- 기존의 테이블 페이지 구조와 정반대의 구조

1) 페이지 테이블 : 프로세스 페이지 번호를 기준으로 page table에서 logical address를 physical address 로 변환(정방향)

2) inverted 페이지 테이블 : page table의 entry에 physical memory 에 들어있는 logical address 주소가 들어 있음(역방향)

- 모든 process 별로 그 logical address에 대응하는 모든 page에 대해 page table entry가 존재(배열과 비슷한 구조), 대응하는 page가 메모리에 있든 아니든 간에 page table에는 entry로 존재와 같은 page table 의 문제점을 inverted page table은 갖지 않음.

 

Shared Page

- Re-entrant Code(=Pure code) : 재진입가능한 코드

- read-only로 하여 프로세스 간 하나의 code만 메모리에 올린다 

- Shared code는 모든 프로세스의 logical address space에서 동일한 위치에 있어야 한다

Private code and data

- 각 프로세스들은 독자적으로 메모리에 올림

- private data는 logical address space의 아무곳에 와도 무방

 

 

2) Segmentation Architecture

- Logical address 는 segment-number(s), offset(d) 으로 구성

- 각각의 segment table 은 limit(segment의 길이), base(segment 의 시작 물리 주소) 를 가짐

- Segment-table base register(STBR) : 물리적 메모리에서의 segment table 위치

- Segment-table length register(STLR) : 프로그램이 사용하는 segment의 수

if (s > STLR) trap

if (limit < d)  trap

 

장점 : segment 는 의미 단위이기 때문에 Sharing과 protection에 있어 paging 보다 훨씬 효과적

단점 : segment의 길이가 동일하지 않으므로 가변분할 방식에서와 동일한 문제점들이 발생

 

 

※ 이화여대 반효경 교수님의 운영체제 강의 정리

반응형

Allocation of Physical Memory : 메모리 할당

메모리는 일반적으로 두 영역으로 나뉘어 사용

1) OS 상주 영역 : interrupt vector 와 함께 낮은 주소 영역 사용

2) 사용자 프로세스 영역 : 높은 주소 영역 사용

 

사용자 프로세스 영역의 할당 방법

1. Contiguous allocation (연속 할당)

: 각각의 프로세스가 메모리의 연속적인 공간에 적재

1) 고정 분할 방식

- 물리적 메모리를 몇 개의 영구적 분할로 나눈다

- 분할당 하나의 프로그램을 적재

- 내부/외부 조각이 발생

  * 외부조각 : 프로그램의 크기보다 분할의 크기가 작은 경우,

                 아무 프로그램에도 배정되지 않은 빈 공간이지만 프로그램이 올라갈 수 없는 작은 분할

  * 내부조각 : 프로그램 크기보다 분할의 크기가 큰 경우,

                 특정 프로그램에 배정되었지만 사용되지 않는 공간

2) 가변 분할 방식

- 프로그램 크기를 고려해서 할당

- 분할의 크기, 개수가 동적으로 변함

- 기술적 관리 기법 필요

  * 외부조각 발생 : B가 끝나서 비어있는 공간이 발생했지만 프로그램 D가 해당 빈 공간 보다 커서 사용할 수 없음

Hole

- 가용 메모리 공간

- 다양한 크기의 Hole 들이 메모리 여러 곳에 존재

- 프로세스가 도착하면 수용가능한 hole 을 할당

- 운영체제는 다음의 정보를 유지 

  할당 공간, 가용 공간(hole)

Hole 을 어떻게 관리 할 것인가?

: Dynamic Storage-Allocation Problem

: 가변 분할 방식에서 size n인 요청을 만족하는 가장 적절한 hole을 찾는 문제

1) First-fit

- Size 가 n 이상인 것 중 최초로 찾아지는 hole 에 할당

2) Best-fit

- Size 가 n 이상인 가장 작은 hole을 찾아서 할당

- 많은 수의 아주 작은 hole들이 생성됨

3) Worst-fit (First-fit, Best-fit 보다 속도/공간 이용률이 비효율적)

- 가장 큰 hole에 할당

- 상대적으로 아주 큰 hole들이 생성됨

 

※ Compaction

- 외부 조각 문제를 해결하는 방법

- 사용 중인 메모리 영역을 한군데로 몰고 hole들을 다른 한 곳으로 몰아 큰 block을 만드는 것

- 비용이 매우 많이 드는 방법

- 최소한의 메모리 이동으로 compaction 하는 방법

- 프로세스 주소가 실행 시간에 동적으로 재배치 가능한 경우에만 수행 가능

 

2. Noncontiguous allocation (불연속 할당)

: 하나의 프로세스가 메모리의 여러 영역에 분산되어 올라감

1) Paging 기법

2) Segmentation 기법

 

 

※ 이화여대 반효경 교수님의 운영체제 강의 정리

반응형

현상, Exception Message (Console) : 

org.quartz.JobPersistenceException: Couldn't acquire next trigger: 
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version 
for the right syntax to use near 'OPTION SQL_SELECT_LIMIT=1' at line 1

 

원인 :
Mysql Connector jar 버전 문제

 

해결방법 :

위와 같은 Exception 발생시

mysql-connector-java 버전을 올려준다.

5.1.22 버전 이상으로 올려주면 된다.

 

※ tomcat / jboss(wildfly) 를 사용중이라면 서버 module 버전도 올려주어야 한다.

jboss 경우의 예]

jboss설치디렉토리/modules/com/mysql/main/ 에 5.1.22 이상의 mysql-connector-java-5.1.22.jar 를 넣어주고

module.xml 의 resource root path 를 아래와 같이 수정

<?xml version="1.0" encoding="UTF-8"?>
<module xmlns="urn:jboss:module:1.0" name="com.mysql">
  <resources>
     <resource-root path="mysql-connector-java-5.1.22.jar"/>
  </resources>
  <dependencies>
     <module name="javax.api"/>
  </dependencies>
</module>

 

참고

반응형

메모리의 주소를 크게 두가지로 나눌 수 있다

Logical address(=virtual address)

- 프로세스마다 독립적으로 가지는 주소 공간

- 각 프로세스마다 0번지부터 시작

- CPU가 보는 주소는 logical address

Physical address

- 메모리에 실제 올라가는 위치

주소 바인딩 : 프로그램이 실제로 메모리에 올라 갈 때 주소를 결정하는 것

Symbolic Address > Logical Address > Physical address

 

주소 바인딩(Address Binding) 방식의 종류

1) Compile time binding

- 물리적 메모리 주소가 컴파일시 알려짐

- 시작 위치 변경시 재컴파일

- 컴파일러는 절대 코드 생성

2) Load time binding

- loader의 책임하에 물리적 메모리 주소 부여

- 컴파일러가 재배치가능코드를 생성한 경우 가능

3) Runtime binding

- 수행이 시작된 이후에도 프로세스의 메모리상 위치를 옮길 수 있음

- CPU가 주소를 참조할 때마다 binding을 점검

- 하드웨어적인 지원이 필요(base and limit registers MMU)

 

Memory Management Unit (MMU)

logical address를 physical address로 매핑해 주는 Hardware device

※ MMU scheme

사용자 프로세스가 CPU에서 수행되며 생성해내는 모든 주소값에 대해 base register(=relocation register)의 값을 더한다

user program

logical address만을 다룬다

실제 physical address를 볼 수 없으며 알 필요가 없다

 

1) CPU가 현재 실행중인 process p1의 논리주소 346 요청

2) process p1 은 물리주소 14000번부터 올라가 있음

3) 프로그램(process p1)이 혹여 자신의 메모리 범위(3000)가 아닌 주소를 요청할 경우를 막기위해

    limit register 의 값과 비교를 해본다.

    limit register 보다 요청 주소가 크다면 trap interrupt 발생 후 운영체제로 제어권을 넘긴다

3) 그렇지 않다면, 시작위치 물리주소인 base register(relocation register)에 논리주소를 더해 돌려줌 (14000+346)

 

Dynamic Loading (동적 로딩)

- 프로세스 전체를 메모리에 미리 다 올리는게 아니라 해당 루틴이 불려질 때 메모리에 load 하는 것

- memory utilization 의 향상

- 가끔씩 사용되는 많은 양의 코드의 경우 유용 ex)오류 처리 루틴

- 운영체제의 특별한 지원 없이 프로그램 자체에서 구현 가능(OS는 라이브러리를 통해 지원 가능)

 

Overlays

- 메모리에 프로세스의 부분 중 실제 필요한 정보만을 올린다

- 프로세스의 크기가 메모리보다 클 때 유용

- 운영체제의 지원없이 사용자에 의해 구현

- 작은 공간의 메모리를 사용하던 초창기 시스템에서 수작업으로 프로그래머가 구현(프로그래밍 매우 복잡)

 

Swapping

- 프로세스를 일시적으로 메모리에서 backing store로 쫓아내는 것

  * backing store(=swap area) : 디스크 (많은 사용자의 프로세스 이미지를 담을 만큼 충분히 빠르고 큰 저장 공간

Swap in / Swap out

- 일반적으로 중기 스케쥴러(swapper)에 의해 swap out 시킬 프로세스 선정

- priority-based CPU scheduling algorithm

  priority가 낮은 프로세스를 swapped out 시킨다, priority가 높은 프로세스를 메모리에 올려놓는다

- Compile time binding 혹은 load time binding 을 사용하는 경우 swapping 후 원래 주소로 복귀(Swap in)해야 하므로 효율적이지 못하다

- Runtime binding 에서 효율적이다

- swap time 은 대부분 transfer time(swap되는 양에 비례하는 시간)

※ 페이징 시스템에서 일부 페이지가 메모리에서 쫓겨날 때도 swap out 이라고 표현하지만 원칙적으로 swap out은 프로그램을 구성하는 메모리 전부가 쫓겨남을 의미

 

Dynamic Linking

Linking을 실행 시간(execution time)까지 미루는 기법

1) Static linking

- 라이브러리가 프로그램의 실행 파일 코드에 포함됨

- 실행 파일의 크기가 커짐

- 동일한 라이브러리를 각각의 프로세스가 메모리에 올리므로 메모리 낭비

2) Dynamic linking (=Shared library =DLL(dynamic linking library))

- 라이브러리가 실행시 연결(link)됨

- 라이브러리 호출 부분에 라이브러리 루틴의 위치를 찾기 위한 stub이라는 작은 코드를 둠

- 라이브러리가 이미 메모리에 있으면 그 루틴의 주소로 가고 없으면 디스크에서 읽어옴

- 운영체제의 도움이 필요

 

 

※ 이화여대 반효경 교수님의 운영체제 강의 정리

반응형

교착상태 Deadlock

일련의 프로세스들이 서로가 가진 자원을 기다리며 block 된 상태

Resource (자원)

- 하드웨어, 소프트웨어 등을 포함하는 개념

  ex) I/O device, CPU cycle, memory space, semaphore 등

- 프로세스가 자원을 사용하는 절차

  : Request, Allocate, Use, Release

 

Deadlock example 1]

시스템에 2개의 tape drive가 있고

프로세스 P1과 P2 각각이 하나의 tape drive를 보유한 채 다른 하나를 기다리고 있다

Deadlock example 2]

Binary semaphores A and B

 

Deadlock 발생의 4가지 조건

1. Mutual exclusion (상호 배제)

  : 매 순간 하나의 프로세스만이 자원을 사용할 수 있음

2. No preemption (비선점)

  : 프로세스는 자원을 스스로 내어놓을 뿐 강제로 빼앗기지 않음

3. Hold and wait (보유대기)

  : 자원을 가진 프로세스가 다른 자원을 기다릴 때 보유 자원을 놓지 않고 계속 가지고 있음

4. Circular wait (순환대기)

  : 자원을 기다리는 프로세스간에 사이클이 형성되어야 함

 

 

Resource-Allocation Graph

좌측은 deadlock 우측은 deadlock 아님

좌측 : P1에게 R2 자원 1개 가있고, P2에게 R2 자원 1개가 가있는 상황, P3가 R2자원 하나 더 요구

        P2 은 R3 자원 요청, R3은 P3 가 가지고 있고 P1 은 R1을 요청하나 이는 P2 가 가지고 있으므로

        모든 프로세스가 자원을 반납할 수 없는 상황 즉, deadlock 상태

우측 : P1에게 R2 자원 1개 가있고, P4에게 R2 자원 1개 가있는 상황, P3가 R2 자원 요구 

        P4가 자원 반납시 문제가 없음 

 

그래프에 cycle이 없으면 deadlock이 아니다

그래프에 cycle이 있으면

if only one instance per resource type, then deadlock

if several instances per resource type, possibility of deadlock

 

Deadlock 처리 방법

1. Deadlock prevention

: 자원 할당 시 deadlock의 4가지 필요 조건 중 어느 하나가 만족되지 않도록 하는 것

ex)

비선점방식을 선점방식으로,

가지고 있으면서 대기하지 못하도록(자원 요청시 보유한 자원 반납),

자원 유형에 할당 순서를 정하여 정해진 순서대로만 할당 

 

2. Deadlock Avoidance

: 자원 요청에 대한 부가적인 정보(최대 요청 자원양)를 이용해서 자원 할당이 deadlock으로부터 안전한지를 동적으로 조사하여 안전한 경우에만 할당

: 가장 단순하고 일반적인 모델은 프로세스들이 필요로 하는 각 자원별 최대 사용량을 미리 선언하도록 하는 방법

ex)

※ Banker's algorithm

현재 요청(Need)을 충족시킬 수 있는 자원상황(Available)이라 할 지라도 최대 요청(Max) 가능성을 염두하여 현재 자원상황을 초과할 가능성이 있다면 자원 할당하지 않음. 

 

3. Deadlock detection and recovery

: deadlock 발생은 허용하되 그에 대한 detection 루틴을 두어 deadlock 발견시 recover

1) Process termination

- 데드락과 관련된 모든 프로세스를 죽인다

- 데드락이 풀릴 때 까지 데드락과 관련된 프로세스를 한 개 씩 죽인다

2) Resource Preemption

- 비용을 최소화할 victim 선정

- safe state 로 rollback 하여 process를 restart

- 동일한 프로세스가 계속해서 victim으로 선정되는 경우 starvation 문제 (cost factor에 rollback 횟수도 같이 고려)

 

4. Deadlock ignorance

: deadlock 을 시스템이 책임지지 않음, 현대 대부분의 OS는 해당 처리방법을 채택

- Deadlock이 매우 드물게 발생하므로 데드락 조치 자체가 더 큰 overhead 일 수 있음

- deadlock 발생하여 시스템이 비정상적일 경우 유저가 직접 process를 죽이는 방법으로 대처

 

 

※ 이화여대 반효경 교수님의 운영체제 강의 정리

반응형

+ Recent posts