Java multi-thread synchronization of ThreadLocal and Synchromized

Introduction:
different ideas and angles ThreadLocal and Synchronized are made to address access conflicts same variable multiple threads, but both deal with the problem.

  • ThreadLocal is a Java class, is to make up time by a separate thread for each storage space, sacrificing space to solve the multi-thread access violation, ThreadLocal thread has the effect of isolation, only to get the corresponding value in the thread, the thread can not be outside access to the desired value.
  • Synchronized Java is a reserved keyword, by a thread waiting, sacrificing time to solve the access violation. Rely on the JVM lock mechanism to achieve atomic access functions or variables in the critical region. In the synchronization mechanism by locking mechanism to ensure that the object of the same time only one thread access the variable, then the variable is used as a lock mechanism is shared by multiple threads.

Code

  • Synchronized
public class SqlConnectionUtil {
    private static SqlPool instance=null;
    public static synchronized SqlConnection getInstance(){
        if(instance==null)
            instance=new SqlPool();
        return instance.getSqlConnection();
    }          

  • ThreadLocal
public class SqlConnectionUtil {
    private static ThreadLocal<SqlConnection> tl = new ThreadLocal<SqlConnection>();
    private static SqlConnection initSqlConnection = null;
    static {
        try {
            initSqlConnection = DriverManager.getSqlConnection("url, name and password");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    
    public SqlConnection getSqlConnection() {
        SqlConnection c = tl.get();
        if(null == c) tl.set(initSqlConnection);
        return tl.get();
    }
}

Published 12 original articles · won praise 19 · views 80000 +

Guess you like

Origin blog.csdn.net/u012675150/article/details/104109509