How to implement global variables in java? ThreadLocal~

  Global variables are variables that can be directly referenced no matter where you are, without worrying about various problems. The first language has its own global variables, I think!

  In general, in a process-oriented language, it may be a variable declared at the front, and the following code directly references it, it becomes a global variable! (The most classic C is like this)

For example: in js:

var a = "hello,a!";

alert(a);

function fn1() {
    var b = "hello, b!"
    alert("global var a: " + a);
}

fn1();

 But some languages ​​do not allow direct reference, such as PHP: (The following code will report an error, because php does not allow direct reference to global variables in functions)

<?php 
    $a = "hello, a!";
    echo $a . "\n";
    
    function fn1() {
        $b = "hello, b!";
        echo "global a is:" . $a . "\n";
    }
    
    fn1();

You need to add the global keyword. The purpose of php is that it does not have a specified entry function and does not use global variables to avoid variable pollution:

<?php

$a = "hello, a!";
echo $a . "\n";

function fn1() {
    global $a;
    $b = "hello, b!";
    echo "global a is:" . $a . "\n";
}

fn1();

 But to implement global variables in java, it is not so simple. It is not because there is a problem with accessing a global variable, but when accessing a global variable variable, thread safety problems are often caused, so global variables cannot be used casually.

public class Constants {
    public static String CONST_6 = "6";
}

Where it needs to be used, just use Constants.CONST_6 = 7; directly. But because java is inherently a multi-threaded environment, if another thread also changes this variable, then there will be a problem. Under the same circumstances, other languages ​​are often multi-process environments, and do not have to consider the thread safety of variables.

Of course, java naturally takes into account the need to access global variables, so with ThreadLocal, this class is thread-safe and can be used as a global variable.

public class GlobalVarManager {
    private static ThreadLocal<GlobalVars> globalVars = new ThreadLocal<>();

    public static globalVars getGlobalVars() {
        return globalVars.get();
    }

    public static void setGlobalVars(GlobalVars conn) {
        globalVars.set(conn);
    }
}

In the above method, using the set and get methods outside, you can share global variables and ensure thread safety.

The operation of ThreadLocal has three sets, get, and remove. The implementation principle is to use a map to store variables and put the map into the current thread:

    public void set(T value) {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
    }
    public T get() {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null) {
            ThreadLocalMap.Entry e = map.getEntry(this);
            if (e != null) {
                @SuppressWarnings("unchecked")
                T result = (T)e.value;
                return result;
            }
        }
        return setInitialValue();
    }
     public void remove() {
         ThreadLocalMap m = getMap(Thread.currentThread());
         if (m != null)
             m.remove(this);
     }

ThreadLocal is not necessarily useful for general development work, but it is more useful for operations such as frameworks.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325337819&siteId=291194637