why is android.os.Message not immutable -


in android.os.message, there lot of fields thread identify after receiving message.

public int what; public int arg1;  public int arg2; 

however, if change value in fields after putting message message queue, it'd affect way receiver thread handles message.

why doesn't android team make android.os.message immutable? think it'll prevent android developers make mistakes.

isn't better design make immutable?

i have no exact answer first question (only android team has one). looks like, it's related memory/performance considerations. generally, creation of objects quite expensive, so, android suggests :

the best way 1 of these call message.obtain() or 1 of handler.obtainmessage() methods, pull them pool of recycled objects.

if follow android reference , use message.obtain(), won't spent time , memory on creation new message objects, re-use existing ones 'message query'. believe message made mutable, because android mobile systems restricted resources (not sure if it's valid point today, years ago).

the same time immutable objects have many advantages. check out effective java item 15: minimize mutability more details. main reasons using immutable classes are:

  • immutable objects simple;
  • immutable objects inherently thread-safe; require no synchronization;
  • immutable objects can shared freely, can share internals (whose finals usually);
  • it's easier build other objects immutable ones;

effective java mentions single disadvantage of immutable classes: require separate object each distinct value.


Comments

Popular posts from this blog

c# - SVN Error : "svnadmin: E205000: Too many arguments" -

c# - Copy ObservableCollection to another ObservableCollection -

All overlapping substrings matching a java regex -