Suppose we have some resource(a file on disk) in which we have to write bytes produced by different threads. These threads are spawned by some process that listens to some events and spawns a thread every time when event occures. As we have only one resource, we have to synchronize methods of the class which performs write operation:
synchronized void write(byte [] bytes) {
//write data to file
}
or create some mutex:
Object mutex = new Object();
void write(byte [] bytes) {
synchronized(mutex) {
//write data to file
}
}
And now suppose that we have very old hard drive, so it performs write operation too slowly. And several times a day we have very large amount of events occured. So the threads will make something like queue to the resource. So I have next questions:
- How long such queue could be?
- If there are several threads waiting for the resource and resource
has freed what thread will be the first to occupy the resource. Will
it be FIFO principle? - How the situation will change if threads have different priorities?
- If the resource is
DataSourceobject which producesConnectionobject participating in connection pooling, will it be the same as with the file above?
Executors.ReentrantLockif you want FIFO. But it’s more time-consuming tha basic synchronization or an unfair lock.