For example, I have the following code:

public static void getUser(int id) { new Thread(new Runnable() { public void run() { User user = API.getUser(id); ApplicationLoader.users.put(id, user); } }).start(); } 

In another thread, for example, I take information from the network. After I received the information, the flow will close itself? Or should it not close at all? How does this whole thing work?

And if for example this script will run twice at once? For example, one of the service, and the other of the activation.

1 answer 1

After executing the last line of code, all data associated with the stream will be unloaded. The local memory occupied by the thread will be equal to 0. And the system will destroy the "garbage" handle. This happens when the code is well written, taking into account all possible errors and exceptions.

There is more than one way to organize multithreading in Java. Android also provides a number of add-on classes related to parallel programming and control of sequential actions (AsyncTask class, for example)

If you have received any data in the stream, definitely, you need to save \ transmit-to-post-process it somewhere. It already depends on your second thread, which code is not provided.

  • The user is simply added to a static variable in the ApplicationLoader class that inherits Application. Here is the private static volatile HashMap<Integer, User> users = new HashMap<>(); , access to it is from any stream, so AsyncTask did not use it, because it is not necessary - antop95