Question

Hello guys

I'd like to ask, if is there any type of implementation ,that can be used to set method/part of code as atomic operation in Java, so it can't be stopped/paused (must be executed to the end). I need that for ensure that while I am buffering MP3 file to buffer, represented as front of frames that has size of bit rate of that file, the thread will read the whole frame, or the operation will fail to be done, but to avoid that buffer will read only a part of frame, to avoid tears in playing, and errors in data consistence.

I am asking because there will be multiple threads working with that file (BufferClass, PlayerClass, FileInfoClass, etc..) and the file will be implemented as typical example of Critical Part of data, so there will be synchronization through a monitor. Maybe that can be served by some avoid of call Thread.wait() / Thread.notify() but I am not that advanced in Java.

Was it helpful?

Solution

You can use the synchronized statement:

synchronized(anObject){
    performSomeOperation();
}

Every synchronized statement using the same object is guaranted to wait until another thread in such a statement is finished.

Example for Hot Licks comment:

synchronized returntype someMethod(parameters ...){
    performSomeOperation();
}

In this example the object which is locked is 'this'.

OTHER TIPS

As an addition to the accepted answer, you may find it useful to also take a look at the already available (since Java SE 5) Java Concurrency Utilities.

API Specification:

From the official description (emphasis mine):

The concurrency utilities packages provide a powerful, extensible framework of high-performance threading utilities such as thread pools and blocking queues. This package frees the programmer from the need to craft these utilities by hand, in much the same manner the collections framework did for data structures. Additionally, these packages provide low-level primitives for advanced concurrent programming.


For instance, java.util.concurrent.locks package provides an alternative to the classical synchronized blocks:

While locking is built into the Java language through the synchronized keyword, there are a number of limitations to built-in monitor locks. The java.util.concurrent.locks package provides a high-performance lock implementation with the same memory semantics as synchronization, and it also supports specifying a timeout when attempting to acquire a lock, multiple condition variables per lock, nonnested ("hand-over-hand") holding of multiple locks, and support for interrupting threads that are waiting to acquire a lock.

See the Concurrency Utilities Overview for more.


Useful reading

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top