Recommendations for using objects between threads in Java

I tried to search, but could not find the exact answer I was looking for, so I asked a new question.

If you want to share any mutable objects (objects) between multiple threads, are there any recommendations / principles / recommendations for this?

Or will it just change in each case?

+4
source share
5 answers

Sharing mutable objects between threads is risky.

The safest way is to make objects immutable, you can freely share them.

, , . (synchronized, AtomixX ..).

, , .

+5

java , / , .

:

  • (ConcurrentHashMap),
  • volatile, ( )

/, , , .

+4

, . , .

, .

  • .

. , . , /api, , . Scala , Java .

  1. synchronize.

, . , . , , . , .

  1. .

, . . . , Akka, .

  1. . (Java.util.concurrent.atomic)

, incrementAndGet. .

  1. .

Java api , .

  1. .

. , dsl. , , . , synchronize .

+2

. StringBuilder , synchronized (builder) . .

(, StringBuffer), .

    public static void main(String[] args) throws InterruptedException {
        StringBuilder builder = new StringBuilder("");

        Thread one = new Thread() {
            public void run() {

                for (int i = 0; i < 1000; i++) {
                    //synchronized (builder) {
                        builder.append("thread one\n");
                    //}
                }
            }
        };
        Thread two = new Thread() {
            public void run() {

                for (int i = 0; i < 1000; i++) {
                    //synchronized (builder) {
                        builder.append("thread two\n");
                    //}
                }
            }
        };
        one.start();
        two.start();
        one.join();
        two.join();

        System.out.println(builder);
    }
+1

, , Java Concurrency 3 - .

.

:

  • ;
  • ( ) ;
  • , .

, :

, . :

  • ;
  • volatile AtomicReference;
  • ;
  • , .

, / synchronize.

+1
source

Source: https://habr.com/ru/post/1671033/


All Articles