java-problems with the multi-threaded String constant Pool cache feature

Source: Internet
Author: User

There is a string constant pool cache feature in the JVM.

Package com.leran.thread.demo1;

public class Test {
public static void Main (string[] args) {
String a = "a";
String B = "a";
System.out.println (A = = B);
}

}

Result: true;

For example:

public class Service {
public static void print (String stringparam) {
try {
Synchronized (Stringparam) {
while (true) {
System.out.println (Thread.CurrentThread (). GetName ());
Thread.Sleep (1000);
}
}

} catch (Exception e) {
E.printstacktrace ();
}

}

}

Package com.leran.thread.demo1;

public class Threada extends Thread {
Private service service;
Public Threada (service service) {
Super ();
This.service=service;
}

@Override
public void Run () {
Service.print ("AA");
}

}

Package com.leran.thread.demo1;

public class Threadb extends Thread {
Private service service;
Public threadb (service service) {
Super ();
This.service=service;
}

@Override
public void Run () {
Service.print ("AA");
}

}

Package com.leran.thread.demo1;

public class Test {
public static void Main (string[] args) {
Service service = new service ();
Threada a = new Threada (service);
A.setname ("A");
A.start ();
THREADB B = new threadb (service);
B.setname ("A");
B.start ();
}

}

The result of the output is: A A a a a ...

The result is that because the two values of string are AA and two threads hold the same lock, the thread B cannot execute. This is the problem caused by the string constant pool. So

In most cases, the synchronous synchronized code block does not use string as the lock object, but instead uses the other, such as new object () to instantiate the object, but it is not placed in the cache pool.

java-problems with the multi-threaded String constant Pool cache feature

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.