PDA

View Full Version : سوال: ریسمان ها و دسترسی همزمان!



محمد فدوی
پنج شنبه 28 شهریور 1392, 11:48 صبح
سلام.
برای مثال در کلاس ساده زیر:


public class Counter {
private static int count = 0;

public static void increase() {
count++;
}

public static int getCount() {
return count;
}
}


با فرض اینکه چندین ریسمان از کلاس فوق استفاده کنند، آیا ممکنه موقع فراخوانی همزمان متدها توسط 2یا چند ریسمان، مشکلی پیش بیاد؟ راه حل چیه؟ :متفکر:
ممنون.

rezaricky
پنج شنبه 28 شهریور 1392, 12:21 عصر
سلام
اره ممکنه
میتونی از synchronized استفاده کنی
public class Counter {
private static int count = 0;

public synchronized static void increase() {
count++;
}

public static int getCount() {
return count;
}
}
البته طبق این متن
"Avoid lock on static methods

The worst solution is to put the "synchronized" keywords on the static methods, which means it will lock on all instances of this class."
دراین لینک http://www.theserverside.com/news/1363681/Scaling-Your-Java-EE-Applications
بهتره در صورت امکان از توابع synchronized static استفاده نکنی چون کل کلاس رو lock می کنند.

cups_of_java
پنج شنبه 28 شهریور 1392, 14:16 عصر
یه راه دیگه برای اینکه خودتو درگیر synchronized نکنی استفاده از AtomicInteger هست که راحت تره:
private static AtomicInteger a;

a.incrementAndGet();

a.intValue();