๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

๋นˆ ๊ตฌ๋ฉ ์ฑ„์šฐ๊ธฐ

[Android][Java] SharedPreference object ์•ˆ Context๋กœ memory leak ๊ฒฝ๊ณ 

SharedPreferences๋ฅผ ํŽธํ•˜๊ฒŒ ์จ๋ณด๊ฒ ๋‹ค๊ณ  Object๋กœ ๋žฉํ•‘ํ–ˆ์—ˆ๋‹ค. 

Application ํด๋ž˜์Šค์˜ onCreate()์—์„œ ์ดˆ๊ธฐํ™” ์‹œ application context๋ฅผ ๋ฐ›์•„ SharedPreferences ๊ธฐ๋Šฅ์„ ์‚ฌ์šฉํ•  ๋•Œ๋งˆ๋‹ค context๋ฅผ ํŒŒ๋ผ๋ฏธํ„ฐ๋กœ ๋ฐ›์•„์˜ค์ง€ ์•Š๋„๋ก ํ•ด์„œ ์ •๋ง ํŽธํ•˜๊ฒŒ ์“ฐ๊ณ  ์žˆ์—ˆ๋Š”๋ฐ, ์•ˆ๋“œ๋กœ์ด๋“œ ์ŠคํŠœ๋””์˜ค์—์„œ memory leak ๊ฒฝ๊ณ ๋ฅผ ๋„์›Œ์คฌ๋‹ค.

 

Do not place Android context classes in static fields (static reference to 'Pref' which has field 'context' pointing to 'Context'); this is a memory leak

 

์ดˆ๊ธฐํ™” ์‹œ์— ๋ฐ›์•„์˜ค๋Š” context๋ฅผ WeakReference๋กœ ๋ž˜ํ•‘ํ• ์ง€, SoftReference๋กœ ๋ž˜ํ•‘ํ• ์ง€ ๊ณ ๋ฏผํ–ˆ๋‹ค. ์•ฑ์„ ์‚ฌ์šฉํ•  ๋•Œ ์–ด๋Š ๋•Œ๋“  ํŽธํ•˜๊ฒŒ ์‚ฌ์šฉํ•˜๊ธฐ ์œ„ํ•ด์„œ ๋งŒ๋“  SharedPreferences object์ด๊ธฐ ๋•Œ๋ฌธ์—, ์™ ๋งŒํ•˜๋ฉด ์˜ค๋ž˜์˜ค๋ž˜ GC์—๊ฒŒ์„œ ๋ฉ€์–ด์ง€๋Š” ๊ฒƒ์ด ์ข‹์ง€ ์•Š๋‚˜ ์‹ถ์–ด์„œ SoftReference ๊ฐ€ WeakReference๋ณด๋‹ค ๋‚˜์„๊นŒ ๊ณ ๋ฏผํ–ˆ๋‹ค.

 

https://aroundck.tistory.com/477

 

[Java] WeakReference ์™€ SoftReference ์˜ ์ฐจ์ด์ .

์•ˆ๋…•ํ•˜์„ธ์š” ๋ผ์ง€์™• ์™•๋ผ์ง€์ž…๋‹ˆ๋‹ค ์˜ค๋Š˜์€ Weak Reference ์™€ Soft Reference ์— ๋Œ€ํ•ด ์•Œ์•„๋ณด์•˜์Šต๋‹ˆ๋‹ค. WeakReference. Object ๋ฅผ ์ฐธ์กฐํ•˜๋Š” ํ˜•ํƒœ ์„ธ ๊ฐ€์ง€ ์ค‘์˜ ํ•˜๋‚˜์ž…๋‹ˆ๋‹ค. GC ๊ฐ€ ๋ฐœ์ƒํ•  ๋•Œ ์–ด๋–ค object ๊ฐ€ weakly-r..

aroundck.tistory.com

https://itmining.tistory.com/10

 

[์•ˆ๋“œ๋กœ์ด๋“œ] ์•ˆ๋“œ๋กœ์ด๋“œ ๋ฉ”๋ชจ๋ฆฌ ๊ด€๋ฆฌ (Weak Reference์™€ Soft Reference)

์ด ๊ธ€์€ PC ๋ฒ„์ „ TISTORY์— ์ตœ์ ํ™” ๋˜์–ด์žˆ์Šต๋‹ˆ๋‹ค. ์„œ๋ก   ์˜ค๋Š˜์€ ์ž๋ฐ”์™€ ์•ˆ๋“œ๋กœ์ด๋“œ์—์„œ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋Š” Reference Object ์— ๋Œ€ํ•ด์„œ ์„ค๋ช…ํ•ด๋ณด๋„๋ก ํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค. Reachability  GC(Garbage collector)๋Š” reference..

itmining.tistory.com

 

WeakReference๋Š” strong reference๊ฐ€ ๋ชจ๋‘ ๋Š๊ธฐ๊ณ  ๋‚˜์„œ GC ํƒ€์ด๋ฐ์ด ๋˜์–ด์•ผ์ง€ GC routine์„ ํƒ„๋‹ค๋Š” ๊ฒƒ์„ ๋ณด๊ณ , WeakReference๋ฅผ ์‚ฌ์šฉํ•ด๋„ ๋˜๊ฒ ๋‹ค๋Š” ๊ฒฐ์ •์„ ๋‚ด๋ ธ๋‹ค. ์ด SharedPreferences ๋ž˜ํ•‘ object์—์„œ ์ฐธ์กฐํ•˜๋Š” context๋Š” ์•ฑ์˜ application context์ด๋‹ค. ์ด ์นœ๊ตฌ๋Š” Strong ์†์„ฑ์„ ๊ฐ€์งˆ ๊ฒƒ์ด๊ธฐ์— ์™ ๋งŒํ•˜๋ฉด GC์—๊ฒŒ ๋ฉ”๋ชจ๋ฆฌ๊ฐ€ ํšŒ์ˆ˜๋˜์ง€ ์•Š์„ ๊ฒƒ์ž„์„ ์ถ”์ธกํ•  ์ˆ˜ ์žˆ์—ˆ๋‹ค.