Java transient 키워드에 대해 몰랐던 사실

Posted by epicdev Archive : 2012. 8. 26. 19:10

Java에는 transient라는 키워드가 존재합니다. 예를 들어 아래처럼 클래스의 멤버변수를 선언할 때 붙일 수 있는 키워드입니다.



일반적으로 transient 키워드는 단순히 Java에서 serialization을 할 때, 특정 멤버변수가 serialization이 되는 것을 막는 것이라고 알려져 있습니다.

물론 맞는 말이구요. 그런데 곰곰이 생각해 보면 이게 정말 하나의 프로그래밍 언어에서 키워드로 지정해야할 수준의 중요성을 지니고 있는 것인가? 라는 의문이 들었습니다.


그래서 좀 찾아봤더니 실제로 그런 의견들이 있었습니다.


출처: http://stackoverflow.com/questions/910374/why-does-java-have-transient-variables


Serialization systems other than the native java one can also use this modifier. Hibernate, for instance, will not persist fields marked with either @Transient or the transient modifier. Terracotta as well respects this modifier.

I believe the figurative meaning of the modifier is "this field is for in-memory use only. don't persist or move it outside of this particular VM in any way. Its non-portable". i.e. you can't rely on its value in another VM memory space. Much like volatile means you can't rely on certain memory and thread semantics.


그리고 댓글에는


I think that transient wouldn't be a keyword if it were designed at this time. They'd probably use an annotation


요약을 해보면 이 transient라는 것은 옛날에 Java가 만들어 질 때 만들어 진 키워드입니다.

만약 이러한 기능이 지금에 와서 만들어 졌다면, transient같은 키워드가 아닌 Java 5부터 소개된 Annotation(@)을 활용해서 이러한 것들이 정의되도록 설계를 했을 것입니다. 이것은 volatile같은 키워드에도 똑같이 적용될 수 있습니다.


실제로 이러한 transient나 volatile같은 키워드들은 VM마다 다르게 구현이 되어있기 때문에, JVM이 아닌 다른 VM을 쓸 경우 제대로 동작하지 않을 수도 있다고 합니다.

그래서 결론은, transient를 그냥 단순히 serialization을 방지하는 키워드라고 외우는 것보다는, transient라는 키워드의 본질적인 의미인, 이 멤버 변수는 "메모리 안에서만 사용되어야한다"라는 것을 암시하는 키워드라고 알아두어야 할 것입니다. 그래서 이러한 키워드의 의미를 JVM에서는 serialization이 되지 않도록 구현을 한 것입니다. 다른 VM에서는 어떻게 구현을 하던간에 transient의 본질적인 의미만 어기지 않으면 되는 것입니다.