Reputation:
I've been reading about synchronization in java and I've got a question. So the examples I've seen are either a class creates a synchronized block on a local object. Or a synchronized method. Neither of those two is ideal for my situation. So I have a static instance of a class that holds all the data from the entire application. Variables on that class are created as "private", I created getters to retrieve those values. Some of those values need to be accessed by only one thread at a time from difference classes across the application. Since they are created as private I'm using the synchronized block as follows...
public class Music{
private ArrayList<Album> albums;
private static Music musicObject = new Music();
public ArrayList<Album> getAlbums()
{
return albums;
}
public Music getInstance()
{
return musicObject;
}
}
public class Album {
private Date releaseDate;
private String singer;
public Date getReleaseDate()
{
return releaseDate;
}
public String getSinger()
{
return releaseDate;
}
}
public class AlbumRetrieval
{
private Music data;
public AlbumRetrieval()
{
data = Music.getInstance();
synchronized(data.getAlbums())
{
//No other thread can access the albums variable in here
}
}
}
Can I lock/synchronized an external variable by accessing it through a method call.?
Upvotes: 0
Views: 111
Reputation: 691765
Yes, you can do that. If you couldn't, the code would not compile.
synchronized()
takes an object as "argument". It makes sure that two threads can't enter a synchronized block on this object at the same time.
So, if data.getAlbums()
returns a list, the posted code synchronizes on this list, and no other thread will be able to enter a block that is synchronized on this exact same list while the first thread has not exited its synchronized block.
Note that it's quite a bad strategy to enforce thread-safety. You'll have, every time you access data, to make sure to synchronize correctly. This is very error-prone, and can easily lead to deadlocks. You'd better encapsulate all the accesses to the albums into a well-defined class, which takes care of proper synchronization, rather than return a non-thread-safe list and rely on each and every caller to apply the appropriate synchronization.
Upvotes: 1