PDA

Archiv verlassen und diese Seite im Standarddesign anzeigen : [Java] statische und nichtstatische Methoden synchronisieren?


Arokh
2007-03-30, 00:58:23
Ich habe eine Klasse, die sowohl statische als auch nichtstatische Methoden haben soll, wobei alle thread-sicher sein sollen. D.h. es soll kein Thread eine nichtstatische Methode ausführen können, während ein anderer eine statische Methode ausführt. Kann das funktionieren? Soweit ich weiß, kann man mit dem Schlüsselwort synchronized erreichen, daß nicht gleichzeitig zwei nichtstatische Methoden derselben Instanz ausgeführt werden können, oder daß nicht gleichzeitig zwei statische Methoden ausgeführt werden. In dem einen Fall ist die jeweilige Instanz das Synchronisierungsobjekt, im anderen Fall ein spezielles Class-Objekt. Das deutet ja eher darauf hin, daß es nicht möglich ist, statische und nichtstatische Methodenaufrufe zu synchronisieren, wegen den unterschiedlichen Synchronisationsobjekten...

AlSvartr
2007-03-30, 01:07:56
Du könntest natürlich auch eine statische oder eine threadglobale Variable zur Synchronisation nutzen. Synchronized ist ja nicht nur als Modifikator für Methoden vorhanden, sondern auch in der Form, dass du einzelne Codeblöcke mittels entsprechender Objekte synchronisieren kannst.

mithrandir
2007-03-30, 12:36:57
Das ist schon problematisch:
Unfortunately, the Class-level monitor is in no way connected to the monitors of the various instances of the object, and a synchronized, but nonstatic, method can also access the static fields. Entering the synchronized nonstatic method does not lock the Class object.
-> http://www.javaworld.com/javaworld/jw-04-1999/jw-04-toolbox.html

Es läuft also wohl darauf hinaus, wie AlSvarts schon angesprochen hatte, dass du die synchronized Methoden streichst und stattdessen die synchronized-Blöcke mit einer statischen Variable selbst anlegst, z.B. so:

private static final Object syncObj = new Object();

static someStaticMethod()
{
synchronized( syncObj )
{
// something
}
}

public someOtherMethod()
{
synchronized( syncObj )
{
// something
}
}

HellHorse
2007-03-30, 17:20:25
Das ist schon problematisch:

-> http://www.javaworld.com/javaworld/jw-04-1999/jw-04-toolbox.html

Es läuft also wohl darauf hinaus, wie AlSvarts schon angesprochen hatte, dass du die synchronized Methoden streichst und stattdessen die synchronized-Blöcke mit einer statischen Variable selbst anlegst, z.B. so:

private static final Object syncObj = new Object();

static someStaticMethod()
{
synchronized( syncObj )
{
// something
}
}

public someOtherMethod()
{
synchronized( syncObj )
{
// something
}
}

Alternative:

public class SomeClass {

static someStaticMethod()
{
synchronized( SomeClass.class )
{
// something
}
}

public someOtherMethod()
{
synchronized( SomeClass.class )
{
// something
}
}