Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple threads hold the same lock?

  "dashboardRefreshContainer-8" - Thread t@1384
   java.lang.Thread.State: RUNNABLE
    at sun.util.calendar.ZoneInfo.getLastRule(ZoneInfo.java:638)
    - locked <4d70153e> (a sun.util.calendar.ZoneInfo)
    at sun.util.calendar.ZoneInfo.getOffsets(ZoneInfo.java:275)
    at sun.util.calendar.ZoneInfo.getOffsets(ZoneInfo.java:225)
    at java.util.GregorianCalendar.computeFields(GregorianCalendar.java:2024)
    at java.util.GregorianCalendar.computeFields(GregorianCalendar.java:1996)
    at java.util.Calendar.setTimeInMillis(Calendar.java:1109)
    at java.util.Calendar.setTime(Calendar.java:1075)

"TP-Processor38" - Thread t@158
   java.lang.Thread.State: RUNNABLE
    at sun.util.calendar.ZoneInfo.getLastRule(ZoneInfo.java:638)
    - locked <4d70153e> (a sun.util.calendar.ZoneInfo)
    at sun.util.calendar.ZoneInfo.getOffsets(ZoneInfo.java:275)
    at sun.util.calendar.ZoneInfo.getOffsets(ZoneInfo.java:225)
    at java.util.GregorianCalendar.computeFields(GregorianCalendar.java:2024)
    at java.util.GregorianCalendar.computeFields(GregorianCalendar.java:1996)
    at java.util.Calendar.setTimeInMillis(Calendar.java:1109)
    at java.util.Calendar.setTime(Calendar.java:1075)

The threads are both Runnable, and they hold the same lock. Can both threads lock the same address while they are both RUNNABLE? Is that a JRE bug?

like image 716
Maybe Avatar asked Dec 21 '22 06:12

Maybe


1 Answers

The problem exists only in the thread dump. In fact, at any point in time, the lock is held by only one thread. However, the thread dump shows two different threads with the same lock, because it is not atomic.

The behavior can easily reproduced with the following program:

public class Test {
    public static void main(String[] args) {
        Runnable runnable = new Runnable() {
            public void run() {
                for (;;) {
                    synchronized (this) { }
                }
            }
        };
        new Thread(runnable).start();
        new Thread(runnable).start();
    }
}
like image 192
nosid Avatar answered Jan 02 '23 21:01

nosid