1. Общ преглед
Java поддържа многопоточност от кутията. Това означава, че като изпълнява едновременно байт код в отделни работни нишки, JVM е в състояние да подобри производителността на приложението.
Въпреки че многопоточността е мощна функция, тя има своята цена. В многонишкови среди трябва да пишем реализации по безопасен за нишки начин. Това означава, че различните нишки могат да имат достъп до едни и същи ресурси, без да излагат погрешно поведение или да произвеждат непредсказуеми резултати. Тази методология за програмиране е известна като „безопасност на нишките“.
В този урок ще разгледаме различни подходи за постигането му.
2. Реализации без гражданство
В повечето случаи грешките в многонишковите приложения са резултат от неправилно споделяне на състояние между няколко нишки.
Следователно първият подход, който ще разгледаме, е да постигнем безопасност на нишките, като използваме внедрения без състояние .
За да разберем по-добре този подход, нека разгледаме прост клас на полезност със статичен метод, който изчислява факториала на число:
public class MathUtils { public static BigInteger factorial(int number) { BigInteger f = new BigInteger("1"); for (int i = 2; i <= number; i++) { f = f.multiply(BigInteger.valueOf(i)); } return f; } }
Методът факториал () е детерминирана функция без състояние. Като се има предвид конкретен вход, той винаги произвежда един и същ изход.
Методът нито разчита на външно състояние, нито изобщо поддържа състояние . Следователно се счита, че е безопасно за нишки и може безопасно да бъде извикано от няколко нишки едновременно.
Всички нишки могат безопасно да извикат метода факториал () и ще получат очаквания резултат, без да се намесват помежду си и без да променят изхода, който методът генерира за други нишки.
Следователно внедряванията без състояние са най-простият начин за постигане на безопасност на нишките .
3. Неизменяеми изпълнения
Ако трябва да споделяме състояние между различни нишки, можем да създадем класове, безопасни за нишки, като ги направим неизменни .
Неизменяемостта е мощна, езиково-агностична концепция и е доста лесно да се постигне в Java.
Казано по-просто, екземпляр на клас е неизменим, когато неговото вътрешно състояние не може да бъде променено след като е конструирано .
Най-лесният начин за създаване на неизменяем клас в Java е чрез деклариране на всички полета частни и окончателни и не предоставяне на сетери:
public class MessageService { private final String message; public MessageService(String message) { this.message = message; } // standard getter }
А MessageService обект е ефективно неизменни, тъй като състоянието му не може да се промени след неговото изграждане. Следователно, той е безопасен за нишки.
Освен това, ако MessageService действително са променяеми , но множество нишки имат достъп само за четене, той също е безопасен за нишки.
По този начин неизменността е просто още един начин за постигане на безопасност на нишките .
4. Локални нишки
В обектно-ориентираното програмиране (OOP) обектите всъщност трябва да поддържат състояние чрез полета и да реализират поведение чрез един или повече методи.
Ако всъщност трябва да поддържаме състояние, можем да създадем класове, безопасни за нишки, които не споделят състояние между нишки, като направим техните полета нишки локални.
Можем лесно да създадем класове, чиито полета са локални за нишки, като просто дефинираме частни полета в класовете Thread .
Можем да дефинираме например клас Thread, който съхранява масив от цели числа :
public class ThreadA extends Thread { private final List numbers = Arrays.asList(1, 2, 3, 4, 5, 6); @Override public void run() { numbers.forEach(System.out::println); } }
Докато друг може да съдържа масив от низове :
public class ThreadB extends Thread { private final List letters = Arrays.asList("a", "b", "c", "d", "e", "f"); @Override public void run() { letters.forEach(System.out::println); } }
И в двете реализации класовете имат свое собствено състояние, но то не се споделя с други нишки. По този начин класовете са безопасни за нишки.
По същия начин можем да създадем локални нишки, като присвоим ThreadLocal екземпляри на поле.
Нека разгледаме например следния клас StateHolder :
public class StateHolder { private final String state; // standard constructors / getter }
Лесно можем да го направим променлива, локална за нишки, както следва:
public class ThreadState { public static final ThreadLocal statePerThread = new ThreadLocal() { @Override protected StateHolder initialValue() { return new StateHolder("active"); } }; public static StateHolder getState() { return statePerThread.get(); } }
Локалните нишки са почти като нормалните полета на класа, с изключение на това, че всяка нишка, която ги осъществява чрез сетер / гетер, получава независимо инициализирано копие на полето, така че всяка нишка има свое собствено състояние.
5. Синхронизирани колекции
Можем лесно да създаваме колекции, безопасни за нишки, като използваме набора от обвивки за синхронизация, включени в рамките на колекциите.
Можем да използваме например една от тези обвивки за синхронизация, за да създадем колекция, безопасна за нишки:
Collection syncCollection = Collections.synchronizedCollection(new ArrayList()); Thread thread1 = new Thread(() -> syncCollection.addAll(Arrays.asList(1, 2, 3, 4, 5, 6))); Thread thread2 = new Thread(() -> syncCollection.addAll(Arrays.asList(7, 8, 9, 10, 11, 12))); thread1.start(); thread2.start();
Нека имаме предвид, че синхронизираните колекции използват вътрешно заключване във всеки метод (вътрешното заключване ще разгледаме по-късно).
Това означава, че методите могат да бъдат достъпни само по една нишка наведнъж, докато други нишки ще бъдат блокирани, докато методът не бъде отключен от първата нишка.
По този начин синхронизацията има наказание в производителността поради основната логика на синхронизирания достъп.
6. Едновременни колекции
Като алтернатива на синхронизираните колекции, можем да използваме едновременни колекции за създаване на колекции, безопасни за нишки.
Java предоставя пакета java.util.concurrent , който съдържа няколко едновременни колекции, като ConcurrentHashMap :
Map concurrentMap = new ConcurrentHashMap(); concurrentMap.put("1", "one"); concurrentMap.put("2", "two"); concurrentMap.put("3", "three");
За разлика от синхронизираните си колеги , едновременните колекции постигат безопасност на нишките, като разделят данните си на сегменти . Например в ConcurrentHashMap няколко нишки могат да придобият ключалки на различни сегменти на картата, така че множество нишки могат да имат достъп до картата едновременно.
Едновременните колекции са много по-ефективни от синхронизираните колекции , поради присъщите предимства на едновременния достъп до нишки.
Струва си да се спомене, че синхронизираните и едновременни колекции правят само колекцията безопасна за нишки, а не съдържанието .
7. Атомни обекти
It's also possible to achieve thread-safety using the set of atomic classes that Java provides, including AtomicInteger, AtomicLong, AtomicBoolean, and AtomicReference.
Atomic classes allow us to perform atomic operations, which are thread-safe, without using synchronization. An atomic operation is executed in one single machine level operation.
To understand the problem this solves, let's look at the following Counter class:
public class Counter { private int counter = 0; public void incrementCounter() { counter += 1; } public int getCounter() { return counter; } }
Let's suppose that in a race condition, two threads access the incrementCounter() method at the same time.
In theory, the final value of the counter field will be 2. But we just can't be sure about the result, because the threads are executing the same code block at the same time and incrementation is not atomic.
Let's create a thread-safe implementation of the Counter class by using an AtomicInteger object:
public class AtomicCounter { private final AtomicInteger counter = new AtomicInteger(); public void incrementCounter() { counter.incrementAndGet(); } public int getCounter() { return counter.get(); } }
This is thread-safe because, while incrementation, ++, takes more than one operation, incrementAndGet is atomic.
8. Synchronized Methods
While the earlier approaches are very good for collections and primitives, we will at times need greater control than that.
So, another common approach that we can use for achieving thread-safety is implementing synchronized methods.
Simply put, only one thread can access a synchronized method at a time while blocking access to this method from other threads. Other threads will remain blocked until the first thread finishes or the method throws an exception.
We can create a thread-safe version of incrementCounter() in another way by making it a synchronized method:
public synchronized void incrementCounter() { counter += 1; }
We've created a synchronized method by prefixing the method signature with the synchronized keyword.
Since one thread at a time can access a synchronized method, one thread will execute the incrementCounter() method, and in turn, others will do the same. No overlapping execution will occur whatsoever.
Synchronized methods rely on the use of “intrinsic locks” or “monitor locks”. An intrinsic lock is an implicit internal entity associated with a particular class instance.
In a multithreaded context, the term monitor is just a reference to the role that the lock performs on the associated object, as it enforces exclusive access to a set of specified methods or statements.
When a thread calls a synchronized method, it acquires the intrinsic lock. After the thread finishes executing the method, it releases the lock, hence allowing other threads to acquire the lock and get access to the method.
We can implement synchronization in instance methods, static methods, and statements (synchronized statements).
9. Synchronized Statements
Sometimes, synchronizing an entire method might be overkill if we just need to make a segment of the method thread-safe.
To exemplify this use case, let's refactor the incrementCounter() method:
public void incrementCounter() { // additional unsynced operations synchronized(this) { counter += 1; } }
The example is trivial, but it shows how to create a synchronized statement. Assuming that the method now performs a few additional operations, which don't require synchronization, we only synchronized the relevant state-modifying section by wrapping it within a synchronized block.
Unlike synchronized methods, synchronized statements must specify the object that provides the intrinsic lock, usually the this reference.
Synchronization is expensive, so with this option, we are able to only synchronize the relevant parts of a method.
9.1. Other Objects as a Lock
We can slightly improve the thread-safe implementation of the Counter class by exploiting another object as a monitor lock, instead of this.
Not only does this provide coordinated access to a shared resource in a multithreaded environment, but also it uses an external entity to enforce exclusive access to the resource:
public class ObjectLockCounter { private int counter = 0; private final Object lock = new Object(); public void incrementCounter() { synchronized(lock) { counter += 1; } } // standard getter }
We use a plain Object instance to enforce mutual exclusion. This implementation is slightly better, as it promotes security at the lock level.
When using this for intrinsic locking, an attacker could cause a deadlock by acquiring the intrinsic lock and triggering a denial of service (DoS) condition.
On the contrary, when using other objects, that private entity is not accessible from the outside. This makes it harder for an attacker to acquire the lock and cause a deadlock.
9.2. Caveats
Even though we can use any Java object as an intrinsic lock, we should avoid using Strings for locking purposes:
public class Class1 { private static final String LOCK = "Lock"; // uses the LOCK as the intrinsic lock } public class Class2 { private static final String LOCK = "Lock"; // uses the LOCK as the intrinsic lock }
At first glance, it seems that these two classes are using two different objects as their lock. However, because of string interning, these two “Lock” values may actually refer to the same object on the string pool. That is, the Class1 and Class2 are sharing the same lock!
This, in turn, may cause some unexpected behaviors in concurrent contexts.
In addition to Strings, we should avoid using any cacheable or reusable objects as intrinsic locks. For example, the Integer.valueOf() method caches small numbers. Therefore, calling Integer.valueOf(1) returns the same object even in different classes.
10. Volatile Fields
Synchronized methods and blocks are handy for addressing variable visibility problems among threads. Even so, the values of regular class fields might be cached by the CPU. Hence, consequent updates to a particular field, even if they're synchronized, might not be visible to other threads.
To prevent this situation, we can use volatile class fields:
public class Counter { private volatile int counter; // standard constructors / getter }
With the volatile keyword, we instruct the JVM and the compiler to store the counter variable in the main memory. That way, we make sure that every time the JVM reads the value of the counter variable, it will actually read it from the main memory, instead of from the CPU cache. Likewise, every time the JVM writes to the counter variable, the value will be written to the main memory.
Moreover, the use of a volatile variable ensures that all variables that are visible to a given thread will be read from the main memory as well.
Let's consider the following example:
public class User { private String name; private volatile int age; // standard constructors / getters }
In this case, each time the JVM writes the agevolatile variable to the main memory, it will write the non-volatile name variable to the main memory as well. This assures that the latest values of both variables are stored in the main memory, so consequent updates to the variables will automatically be visible to other threads.
Similarly, if a thread reads the value of a volatile variable, all the variables visible to the thread will be read from the main memory too.
This extended guarantee that volatile variables provide is known as the full volatile visibility guarantee.
11. Reentrant Locks
Java provides an improved set of Lock implementations, whose behavior is slightly more sophisticated than the intrinsic locks discussed above.
With intrinsic locks, the lock acquisition model is rather rigid: one thread acquires the lock, then executes a method or code block, and finally releases the lock, so other threads can acquire it and access the method.
There's no underlying mechanism that checks the queued threads and gives priority access to the longest waiting threads.
ReentrantLock instances allow us to do exactly that, hence preventing queued threads from suffering some types of resource starvation:
public class ReentrantLockCounter { private int counter; private final ReentrantLock reLock = new ReentrantLock(true); public void incrementCounter() { reLock.lock(); try { counter += 1; } finally { reLock.unlock(); } } // standard constructors / getter }
The ReentrantLock constructor takes an optional fairnessboolean parameter. When set to true, and multiple threads are trying to acquire a lock, the JVM will give priority to the longest waiting thread and grant access to the lock.
12. Read/Write Locks
Another powerful mechanism that we can use for achieving thread-safety is the use of ReadWriteLock implementations.
A ReadWriteLock lock actually uses a pair of associated locks, one for read-only operations and other for writing operations.
В резултат на това е възможно да има много нишки, които четат ресурс, стига да няма нишка, която да го пише. Освен това записването на нишка в ресурса ще попречи на други нишки да го четат .
Можем да използваме заключване ReadWriteLock, както следва:
public class ReentrantReadWriteLockCounter { private int counter; private final ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock(); private final Lock readLock = rwLock.readLock(); private final Lock writeLock = rwLock.writeLock(); public void incrementCounter() { writeLock.lock(); try { counter += 1; } finally { writeLock.unlock(); } } public int getCounter() { readLock.lock(); try { return counter; } finally { readLock.unlock(); } } // standard constructors }
13. Заключение
В тази статия научихме какво е безопасност на нишките в Java и разгледахме задълбочено различните подходи за постигането му .
Както обикновено, всички примерни кодове, показани в тази статия, са достъпни в GitHub.