Bharath Ganesh said:
I understand that making String immutable, makes it thread safe and
thus imporves performance.
Is there any other reason for making it Immutable?
Roedy hinted at one, but let me explain further. Java has this thing
called a SecurityManager, and it is responsible for checking that
unprivileged code (for example, an applet) is allowed to do stuff. To
pick one example, applets are typically allowed to contact their server
of origin with sockets, but not other servers. So let's say I write
this:
String hostName = "my.origin.server.com";
Socket s = new Socket(hostName, 1234);
Looks fine. In the second line, the SecurityManager will first check to
be sure that "my.origin.server.com" really is the origin server. Then
it will establish a connection to that server. BUT this only works if
the server name can't change between the security check and establishing
the connection. If String were not immutable, I could do this:
String fakeHostName = "my.origin.server.com";
String realHostName = "evil.server.com";
String hostName = new String(fakeHostName);
new Thread() {
public void run()
{
while (true)
{
hostName.mutateTo(realHostName);
hostName.mutateTo(fakeHostName);
}
}
}.start();
boolean success = false;
while (!success)
{
try
{
Socket s = new Socket(hostName, 1234);
// try talking to evil.server.com
success = true;
}
catch (SecurityException e) { }
}
It might take a while, but eventually, a context switch would happen
between the security check and establishing the connection. When that
happens, security is compromised.
See how that works? It's not impossible to code around, but if String
were mutable it would be a lot bigger pain to write methods that make
proper use of java.security.AccessController.doPrivileged.
--
www.designacourse.com
The Easiest Way To Train Anyone... Anywhere.
Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation