---
title: "static synchronized methods?"
author: "standalone"
date: "2010-11-16T21:41:00Z"
tags: []
categories: ["编程语言"]
slug: "static-synchronized-methods"
draft: false
lastmod: "2012-12-19T16:59:44Z"
id: 813278
url: "https://standalone.iteye.com/blog/813278"
---

Keep in mind that using synchronized on methods is really just shorthand (assume class is SomeClass):

```
synchronized static void foo() {
    ...
}
```

is the same as

```
static void foo() {
    synchronized(SomeClass.class) {
        ...
    }
}
```

and

```
synchronized void foo() {
    ...
}
```

is the same as

```
void foo() {
    synchronized(this) {
        ...
    }
}
```

You can use any object as the lock. If you want to lock subsets of static methods, you can

```
class SomeClass {
    private static final Object LOCK_1 = new Object();
    private static final Object LOCK_2 = new Object();
    static void foo() {
        synchronized(LOCK_1) {...}
    }
    static void fee() {
        synchronized(LOCK_1) {...}
    }
    static void fie() {
        synchronized(LOCK_2) {...}
    }
    static void fo() {
        synchronized(LOCK_2) {...}
    }
}
```

(for non-static methods, you would want to make the locks be non-static fields)