How to store data in RAM and make it available to any module or class in my application?

Asked

Viewed 2,017 times

2

There are several ways to store the data of a particular application and some of them are:

  • Disk Storage (HD). It can be a text file, XML, or a database file of some DBMS.
  • Cloud Storage (Cloud). It has some services that allows store the data of a Cloud application, the Google Cloud Storage is one of them.
  • RAM Storage. In this case the data would be erased when the computer restarts.

Considering the ram memory between the above storage forms it is possible to use the ram memory to store the data temporarily. Let’s consider the following example for illustration:

package pesquisalinearvetor;

import java.util.Scanner;

/**
 * @author Dener
 */
public class PesquisaLinearVetor {
    public static void main(String[] args) {
        int vetor[] = {1, 33, 21, 2, 4};
        int valor;
        Scanner in = new Scanner(System.in);
        
        System.out.println("Informe o valor para ser pesquisado no vetor: ");
        valor = in.nextInt();
        
        if (pesquisaLinear(valor, vetor))
            System.out.println("Existe o valor " + valor + " no vetor.");
        else
            System.out.println("Não existe o valor " + valor + " no vetor.");                      
    }
    
    private static boolean pesquisaLinear(int valor, int vetorAlvo[]) {
        for (int i = 0; i < vetorAlvo.length; i++) 
            if (vetorAlvo[i] == valor)
                return true;        
        return false;
    }
}

The above example stores the values of the variable in memory vetor so that a linear search can be performed on it.

My doubt.

Since access to variables is only allowed within the scope where it was set I would like to know how I can store the data in the ram memory and allow these data to be accessible from any module or class in my application?

1 answer

5


It has some forms. Each one with its advantages and disadvantages. In all if the use allows competition will have to control simultaneous access worrying that it does not have a running condition, for example. I will consider only access monothread that requires no further concern.

The simplest way is to create a static variable. Every static variable has the same lifespan as the application and if it has public visibility it can be accessed by any class.

Understand that there is a question of life span and time.

Instance variables have the same lifetime as the instance itself. Static variables live throughout the application.

Instance variables have instance scope (object), so they are accessed through it (it needs to be alive and available in the specific scope), whereas class variables (static) have class scope and accessed through it, which in turn are always in scope in the application.

Behold What is the difference between a class and an object?.

I think it’s clear that no variable can be accessed directly. Their scope itself is always encapsulated in a structure (class or instance).

Specific case

I’m not sure what the need is and if that’s just an example. There are cases that it would be good to have a class only for this purpose, perhaps with mechanisms that help access the data in a more organized way, perhaps a generic class allowing to store arbitrary data as the demand of the application.

In this particular case it seems to me that the simplest way is just to declare vetor as a static field of the class (no longer a local variable of the method) and will solve the problem simply:

public static int vetor;

This can be accessed from anywhere like:

PesquisaLinearVetor.vetor

Obviously I left without any initialization in the above example, it may be that I wish to have an already expensive value. Remember that if you try to access this vector then its initial value will be null. If the intention is to have something just initialize it right there.

If there is any reason not to allow the data to be changed just put as final. But then it would require initializing the variable, otherwise it makes no sense.

Global class

public final class Global {
    private Global() {} // só pra garantir que não haja instâncias dela
    private static int[] vetor;
    public static int[] getVetor() { return vetor; }
    public static void setVetor(int[] vetor) { this.vetor = vetor; }
    //aqui pode colocar vários outros dados se eles forem relacionados
    //o ideal é criar classe globais para cada necessidade
    //nem sempre é necessário usar getter e setter, o campo público pode ser suficiente
    //é possível criar outras operações específicas de acordo com a necessidade
    //por exemplo pode pegar e setar um elemento do vetor
}

I put in the Github for future reference.

In that case, just wear it at all times Global.getVetor() e fazer o que quiser and Global.setVetor(um vetor de int aqui).

I would say that the simplest solution that is to leave a static field in the class you are already using is more suitable in most cases. If you already have a good place to put a die, why create another?

Singleton

On the other hand, maintaining global open access in this way may not be the most appropriate.

Some people prefer, for some reasons, to have a Singleton class rather than pure static. It can also be done, it has the limitation that always needs to "instantiate" the class to use the value, but the data will be global in the same way.

Some considerations about Singleton and the global state as a whole:

Hashmap

This is a more generic option that allows you to hold multiple global data in an easy and dynamic way.

public class DataHolder {
    private static Map<String, WeakReference<Object>> data = new HashMap<String, WeakReference<Object>>();
    public static void save(String id, Object object) {
        data.put(id, new WeakReference<Object>(object));
    }
    public static Object retrieve(String id) {
        WeakReference<Object> objectWeakReference = data.get(id);
        return objectWeakReference.get();
    }
}

I put in the Github for future reference.

Of course this can be improved as needed. In the background the mechanism is always the same - there is a static variable guarding the value, here has only been added an extra mechanism to generalize to the case of the problem require several global data on demand (which does not seem to be the case of the question).

Database in-memory

Depending on the need it is possible to use even a database. Some work exclusively in memory and do not need installation, is the case with Sqlite.

  • It is also possible to change the contents of the variable?

  • Yes, it can, as long as it’s not final.

  • Global.gerVetor works even if it is not a static method?

  • Oops. Now it’s okay.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.