Em Java, o que acontece se duas classes chamam um método em uma terceira classe ao mesmo tempo?

StackOverflow https://stackoverflow.com/questions/4843220

Pergunta

No meu projeto, tenho uma classe de jogo que é chamada por uma classe de cliente.No momento, a classe do jogo grava um caminho para um arquivo e a classe do cliente lê esse arquivo e limpa o conteúdo.Estou tendo muitos conflitos com o acesso aqui, então quero usar outra classe como o método para armazenar os dados do caminho.Eu quero saber, no entanto, se ainda haverá um problema, ou qual será o resultado se a classe do jogo tentar chamar o método na classe de armazenamento para escrever enquanto a classe do cliente no mesmo instante chama o método no armazenamentoaula para ler e limpar.

Foi útil?

Solução

Sounds like you need to think about threading and synchronization. I'd recommend reading "Java Concurrency in Practice".

Outras dicas

In presence of multiple threads, your classes have to be thread safe. One way of achieving this is to make the concurrently accessed methods synchronized.

Here is an example to get you started:

public class Test {

    public static void main(String[] args) throws Exception {
        new Thread() { public void run() { Test.method(); }}.start();
        new Thread() { public void run() { Test.method(); }}.start();
    }

    public synchronized static void method() {
        System.out.println("hello ");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {}
        System.out.println("world");
    }
}

Without the synchronized modifier, this program would have printed

hello 
hello    
world
world

With the synchronized keyword, only one thread at a time can call method, thus the program prints

hello 
world
hello 
world

I'm assuming your two classes are running in separate threads, so they might access the third class at the same time. The access to the resource they are reading and writing needs to be synchronized (mutexed). Java has the keyword "synchronized", which can be used in multiple ways to prevent concurrent modifications and such, see here and here for details

The theoretically correct answer is: "anything can happen".

The two calls can run one after the other or interleaved with each other, the results are unpredictable and potentially disastrous.

That's why Java offers you several ways of dealing with it.

  1. The simplest (sounding) way is to write your methods threadsafe. In practice this usually means that you should only use local variables and must not modify the objects that are passed to you as parameters. (No side-effects.) Many methods automatically fall into this category, in which case you don't have to worry about concurrency.

  2. If your method cannot be made threadsafe, you need to handle concurrent calls somehow. synchronized blocks are the most often used constructs but in some cases, a volatile field or using Atomic* classes will suffice. But this subject is way too heavy to be covered in a single answer, so I suggest you read the concurrency tutorial.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top