public static ThreadLocalthreadLocal = new ThreadLocal () { @Override protected Integer initialValue() { return 0; } }; public void run() { int val = threadLocal.get(); System.out.println("Initial value: " + val); threadLocal.set(val + 1); val = threadLocal.get(); System.out.println("Final value: " + val); }
public class ExampleThreadLocal { private static final ThreadLocalIn this example, a ThreadLocal variable is declared to create a database connection for each thread. The initialValue() method is overridden to establish a database connection using the appropriate credentials. A getConnection() method is then defined to get the database connection for the current thread. Package/Library: java.lang.ThreadLocal.connectionThreadLocal = new ThreadLocal () { @Override public Connection initialValue() { try { return DriverManager.getConnection(DB_URL, DB_USERNAME, DB_PASSWORD); } catch (SQLException e) { e.printStackTrace(); } return null; } }; public static Connection getConnection() { return connectionThreadLocal.get(); } }