Java - Synchronized methods cause a program to slow down massively

I am trying to learn about threads and synchronization. I made this test program:

public class Test {
    static List<Thread> al = new ArrayList<>();

    public static void main(String[] args) throws IOException, InterruptedException {
        long startTime = System.currentTimeMillis();

        al.add(new Thread(() -> fib1(47)));
        al.add(new Thread(() -> fib2(47)));

        for (Thread t : al)
            t.start();
        for (Thread t: al)
            t.join();

        long totalTime = System.currentTimeMillis() - startTime;
        System.out.println(totalTime);
    }

    public static synchronized int fib1(int x) {
        return x <= 2 ? 1 : fib1(x-2) + fib1(x-1);
    }

    public static synchronized int fib2(int x) {
        return x <= 2 ? 1 : fib2(x-2) + fib2(x-1);
    }
}

This program takes about 273 seconds, but if I remove both of it synchronized, it will work in 7 seconds. What makes this huge difference?

EDIT: I know that I'm using a terribly slow Fibonacci number calculation algorithm. And I also know that threads do not share resources, and therefore methods do not need to be synchronized. However, this is just a test program in which I try to understand how it works synchronized, and I chose a slow algorithm so that I can measure the time spent in milliseconds.

+4
6

static synchronized , , , , ( Test). . , fib , . .

, , . fib, , , , .

, , , fib, . , , , , , .

- , . , , fib1 fib2 .

, , , . , , , , , , .

+2

- . :

1.

, , , . . .

2.

:

, synchronized , . , static, . , , .

synchronized , , , , . , , . - - - , .

, , - synchronized. - , JVM. , JVM synchronized, . - , synchronized - " " . , , JVM , synchronized, , .

Btw: fib1 fib2 ,

+1

@MartinS , , . , .

. , , 100%, , . , - , 100%. , . , .

, ( , ). , .

0

, - . "" - .

N >= 4, . , , N- , 2 ^ N . 2 ^ 47 - (, ). , , , .

. Java, , , . , , . :)

0

fib1 ( fib2) , . , ( , ). , synchronized Java .

.

:

  • ( private, );
  • public , .

, 14 , Test.class.

0

, , , . , Test.class.

.

static final Object LOCK1 = new Object();
static final Object LOCK2 = new Object();

fib1() fib2() . .

public static int fib1(int x) {
   synchronized(LOCK1) {
        return x <= 2 ? 1 : fib1(x-2) + fib1(x-1);
    }
}

public static int fib2(int x) {
   synchronized(LOCK2) {
        return x <= 2 ? 1 : fib2(x-2) + fib2(x-1);
    }
}

LOCK1, , LOCK2, , . ( ). , .

0
source

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


All Articles