Clean Code



Download 3,58 Mb.
Pdf ko'rish
bet306/384
Sana05.04.2022
Hajmi3,58 Mb.
#530298
1   ...   302   303   304   305   306   307   308   309   ...   384
Bog'liq
Clean Code

Nonthread-Safe Classes
There are some classes that are inherently not thread safe. Here are a few examples:

SimpleDateFormat

Database Connections

Containers in 
java.util

Servlets
Note that some collection classes have individual methods that are thread-safe. However,
any operation that involves calling more than one method is not. For example, if you do
not want to replace something in a 
HashTable
because it is already there, you might write
the following code:
if(!hashTable.containsKey(someKey)) {
hashTable.put(someKey, new SomeValue());
}


329
Dependencies Between Methods Can Break Concurrent Code
Each individual method is thread-safe. However, another thread might add a value in
between the 
containsKey
and 
put
calls. There are several options to fix this problem.

Lock the 
HashTable
first, and make sure all other users of the 
HashTable
do the same—
client-based locking:
synchronized(map) {
if(!map.conainsKey(key))
map.put(key,value);
}

Wrap the 
HashTable
in its own object and use a different API—server-based locking 
using an A
DAPTER
:
public class WrappedHashtable {
private Map map = new Hashtable();
public synchronized void putIfAbsent(K key, V value) {
if (map.containsKey(key))
map.put(key, value);
}
}

Use the thread-safe collections:
ConcurrentHashMap map = new ConcurrentHashMapString>();
map.putIfAbsent(key, value);
The collections in 
java.util.concurrent
have operations like 
putIfAbsent()
to accommo-
date such operations.

Download 3,58 Mb.

Do'stlaringiz bilan baham:
1   ...   302   303   304   305   306   307   308   309   ...   384




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©hozir.org 2024
ma'muriyatiga murojaat qiling

kiriting | ro'yxatdan o'tish
    Bosh sahifa
юртда тантана
Боғда битган
Бугун юртда
Эшитганлар жилманглар
Эшитмадим деманглар
битган бодомлар
Yangiariq tumani
qitish marakazi
Raqamli texnologiyalar
ilishida muhokamadan
tasdiqqa tavsiya
tavsiya etilgan
iqtisodiyot kafedrasi
steiermarkischen landesregierung
asarlaringizni yuboring
o'zingizning asarlaringizni
Iltimos faqat
faqat o'zingizning
steierm rkischen
landesregierung fachabteilung
rkischen landesregierung
hamshira loyihasi
loyihasi mavsum
faolyatining oqibatlari
asosiy adabiyotlar
fakulteti ahborot
ahborot havfsizligi
havfsizligi kafedrasi
fanidan bo’yicha
fakulteti iqtisodiyot
boshqaruv fakulteti
chiqarishda boshqaruv
ishlab chiqarishda
iqtisodiyot fakultet
multiservis tarmoqlari
fanidan asosiy
Uzbek fanidan
mavzulari potok
asosidagi multiservis
'aliyyil a'ziym
billahil 'aliyyil
illaa billahil
quvvata illaa
falah' deganida
Kompyuter savodxonligi
bo’yicha mustaqil
'alal falah'
Hayya 'alal
'alas soloh
Hayya 'alas
mavsum boyicha


yuklab olish