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

2

There are several ways to store data for a given 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. It has some services that allows store data for a Cloud application, the Google Cloud Storage is one of them.
  • Storage in RAM memory. In this case the data would be deleted when the computer restarted.

Given the RAM of the above forms of storage you can use RAM to save 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 vetor in memory so that a linear search can be performed on it.

My doubt.

Since access to the variables is only allowed within the scope where it was defined, I would like to know how I can store the data in RAM and allow that data to be accessible from any module or class of my application?

    
asked by anonymous 12.06.2016 / 15:14

1 answer

5

There are some ways. Each one with its advantages and disadvantages. In all cases if the use allows concurrency you will have to control concurrent access by worrying that you do not have a race condition . , for example. I will consider only monothread access that does not require any major concerns.

The simplest way is to create a static variable. Every static variable has a lifetime equal to that of the application and if it has public visibility it can be accessed by any class.

Understand that you have a scope and lifetime issue.

Instance variables have the same lifetime as the instance itself. Statics live by every application.

Instance variables are instance-scoped, so they are accessed through it (it needs to be live and available in the specific scope), since the (static) class variables are class-scoped and accessed through it, which in turn are always in scope in the application.

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

Specific case

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

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

public static int vetor;

This can be accessed from anywhere like:

PesquisaLinearVetor.vetor

Obviously I left without any initialization in the example above, you might want to have a face value already. Remembering that if you try to access this vector like this, the initial value of it will be null. If the intention is to have something, just boot it right there.

If there is any reason not to allow the data to be changed, just enter final . But there you would have to initialize the variable, otherwise it does not make 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 gobais 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

In this case, always use Global.getVetor() e fazer o que quiser and Global.setVetor(um vetor de int aqui) .     }

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

Singleton

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

Some people prefer, for some reasons, to have a Singleton class than a pure static. It can be done too, you have the limitation that you always need 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 secure 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();
    }
}

Of course this can be improved as needed. In the background the mechanism is always the same - there is a static variable storing the value, here only an extra mechanism has been added to generalize in case the problem requires multiple global data on demand (which does not seem to be the case for the question) / p>

In-memory database

Depending on the need you can use a database yourself. Some work exclusively in memory and do not need installation. That's the case with SQLite .

    
12.06.2016 / 15:52