I am using spring jdbctemplate in my application and in my query I am using row mapped as new BeanPropertyRowMapper(dto.class)
But I am getting comment from my client to make row mapped thread safe. How it can be done?
The query method looks like:
jdbcTemplate.query(qry, new Object[]("abc"),
new BeanPropertyRowMapper<dto>(dto.class))
Your code is already thread-safe. But you can improve its performance by creating a constant.
The BeanPropertyRowMapper class has mutable data. But once initialized, those data don't change so the class is thread-safe.
Exemple:
private static final BeanPropertyRowMapper<dto> DTO_ROW_MAPPER = new dto<dto>(DtoDetailEvenement.class);
...
jdbcTemplate.query(qry, new Object[]("abc"), DTO_ROW_MAPPER)
Given this code called from a DAO instance method:
jdbcTemplate.query(qry, new Object[]("abc"), new BeanPropertyRowMapper<dto>(dto.class))
(where jdbcTemplate is an instance member of the DAO injected by Spring, and the DAO is a Spring-managed bean with singleton scope) then this seems ok. BeanPropertyRowMapper is stateful and would not be threadsafe if used concurrently by multiple threads, but you're not exposing it to multiple threads, you're using it in a thread-confined manner which is safe.
Java Concurrency in Practice, section 3.3, discusses thread-confinement in general:
Accessing shared, mutable data requires using synchronization; one way to avoid this requirement is to not share. If data is only accessed from a single thread, no synchronization is needed. This technique, thread confinement, is one of the simplest ways to achieve thread safety. When an object is confined to a thread, such usage is automatically thread-safe even if the confined object itself is not [CPJ 2.3.2].
It also discusses (in 3.3.2) the particular kind of thread-confinement that you're doing:
Stack confinement is a special case of thread confinement in which an object can only be reached through local variables. Just as encapsulation can make it easier to preserve invariants, local variables can make it easier to confine objects to a thread. Local variables are intrinsically confined to the executing thread; they exist on the executing thread's stack, which is not accessible to other threads. Stack confinement (also called within-thread or thread-local usage, but not to be confused with the ThreadLocal library class) is simpler to maintain and less fragile than ad-hoc thread confinement.
The only reference to the RowMapper is on the stackframe created for that method call. No other thread (including threads calling the same method on the same DAO) can access it. Tell your client this object is already safe due to being reachable only by local variables, and refer him to the quoted passage from the JCIP book, which is an authoritative reference.
Related
J. Bloch in his Effective Java suggests we use an enum-based singleton implementation. For instance:
public enum Application {
INSTANCE;
//methods, fields
}
This implementation is nice in the case of serialization because enums provide us with the capability of serialization by default (and we don't have to be afraid of getting two different instances while deserializing the object).
My question is how this implementation respects multhreading. How to make it thread-safe? What would we probably get if we try to access it from different threads?
The actual enum behavior of instatiating the instance doesn't have an issue with thread safety. However, you will need to make sure that the instance state itself is thread-safe.
The interactions with the fields and methods of Application are the risk--using either careful synchronization and locking, or purely concurrent data and careful verification that other inconsistencies can't happen, will be your best bet here.
Singleton ensures you only have one instance of a class per class loader.
You only have to take care about concurrency if your singleton has a mutable state. I mean if singleton persist some kind of mutable data.
In this case you should use some kind of synchronization-locking mechanishm to prevent concurrent modification of the state and/or use thread-safe data structures.
I have read many stackoverflow questions on this but phrased differently and not answered what I was looking for. I don't expect any code solutions but a behavioral explanation of singleton object in multi-threaded environment. Answers with some links with explanation would be great.
Question 1:
If there are multiple thread that needs to access singleton object(say configured as singleton bean in spring config), then is it that only one thread is able to get access and others are blocked till current holding thread releases it.
For me blocking here makes sense, because there is only one object and all threads cannot get same object at the same time.
So if I configure my DAO as singleton bean then if multiple users(threads) try to do reads and write through that DAO then it doesn't actually happen concurrently but sequentially ---> a performance issue in database intensive application.
On the other hand most of the DAOs are stateless(atleast in my case), so instead of configuring it as Singleton, I can instantiate it wherever I need and do the operations concurrently, but each object instantiation may take some time and memory. So it is a design decision.
In my case, since DAO has no state variable so memory would be negligible, so if my above theory is correct then I would go with 2nd option i.e. choosing concurrency over memory.
Question 2: For the question asked here
I think the best answer is below by S.Lott(I don't know how to point link
directly to the answer so copying the answer):
Singletons solve one (and only one) problem.
Resource Contention.
If you have some resource that
(1) can only have a single instance, and
(2) you need to manage that single instance,
you need a singleton.
Here my question is if above answer is true--> That would be the reason for loggers implemented as singletons because you have one log file(single resource).
You don't want that due to time slicing if one thread has written part of some log into the file and then suspended and then thread-2 writes its part and then thread-1 again, thereby making log file gibberish.
I stroke above text because I think if one thread is logging then second thread cannot log at all(blocked) because of singleton config, there by avoiding making log file a gibberish.
Is my understanding right?
"Singleton" has no meaning in the Java programming language. It's just a design pattern. The behavior of a singleton object that is shared by many threads is no different from the behavior of any other object that is shared by many threads.
It's safe if, and only if, you make it safe.
The quote you have is correct but incomplete. Singleton have more purposes, which hopefully becomes clear later on.
The answer to your first question is, it depends on the bean and how it is implemented. Instances instantiated by Spring do not guarantee thread-safety. For the purpose of answering this question, suppose that there are two possible categories of implementations: stateful and stateless. An implementation can be considered stateful if there are any methods that require external resources (e.g. field variables, database access, file access) that are mutable. On the other hand, an implementation is stateless if all the methods are able to execute their tasks using only their parameters and immutable external resources.
class Stateful {
private String s; // shared resource
void setS(String s) {
this.s = s;
}
}
class Stateless {
int print(String s) {
return s.size();
}
}
Now, if the implementation is stateless, it generally makes sense for it to be a singleton. Because a stateless class is inherently thread-safe. Multiple threads can use the methods concurrently (without blocking). Just because a class is stateless does not mean that it consumes negligible memory. In Java, instantiating a class is considered an expensive operation.
More work is required for stateful implementations to be a singleton. Again for the purpose of answering this question, suppose that there are two categories of implementation: blocking and non-blocking. Blocking is as described (although there are various types of blocking). Non-blocking means that multiple threads can call the methods concurrently. Typically, there is a thread specially for the non-blocking implementation for processing.
Loggers are good examples of non-blocking implementations. Below is a highly simplified code.
class Logger {
private List<String> msgs = new CopyOnWriteArrayList<>();
void log(String msg) {
msgs.add(msg);
}
private void process() {...} // used internally by a thread specially for Logger
}
As for question 2, the basic answer is no; singletons are not all bad. Design patterns are double-edge swords. Use them wisely and they improve your code; use them badly and they create more problems than they solve.
Whatever #james said is correct. Coming to your questions:
Question 1: Multiple threads can get access to singleton object without blocking unless you make the get method which returns the object synchronized. Please see below(Multiple threads can get a reference to singleton object without getting blocked).
public class Singleton {
private Singleton() {
}
private static class SingletonHelper {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonHelper.INSTANCE;
}
}
Question 2: No your understanding is incorrect. If one thread is writing, another thread must wait, this is not because of singleton config, but because there might be a possibility that the object(file) may end up in inconsistent state; same is applicable for any object not synchronized properly.
you are linking then singleton pattern and a multithread application assuming that the access to the singleton object must be serialized; this is not true.
The requirement is that the singleton must be thread safe.
Consider the DAO example in your question; assuming the each invocation is stateless (i.e. you don't share variables within the class but only witihin the methos) you don't need multiple instance of the same DAO, in a Spring application usually there is one or more manager classes (usually you manage then DB transactions of these manager classes using AOP); each of them has a reference to a single DAO. Each time a DAO object is invoked it gets a DB connection form the data source and it executes the desired operation, then it releases the connection to the data source.
When multiple threads call your manager class you need to acquire/release the DB connection in a thread safe way. Usually Spring hides this complexity and you don't need to worry about that.
A pseudo code for the dao is something like
public void doSomeDBOperation(YourObject param) {
Connection connection=acquireDBConnection();//the connection must be acquired in a thread safe way
SQLStatement statement=connection.createStatement(yourSQL);
//do the operation with your param;
releaseDBConnection(connection);
}
Spring does sometinh similar under the hood it acquires a Db connection in the AOP aspect, it save in thread local variable so it ca be used by multiple DAOs and you can manage the transaction over the connection.
So one manager, one dao and multiple DB connections is a way to manage multithread operations in parallel (you serialize only the DBconnection lease/release assuming you are using a connection pool) and doing DB operation without blocking (at a java level on the db level things operations may lock in order to guarantee integrity constraints).
Regarding the logger question I assume you are refering to the way most logging library are used i.e you declare a static logger in each of you classes:
public class MyClass {
private static final Logger logger=LoggerFactory.get(MyClass.class.getName());
.....
}
The logger class and the file where you log are not directly linked, with Log4J, LogBack, etc you can log to multiple files with one log call, you can even log to something that is not file (a socket for example). The real writing operations are done by the appenders, the appenders must be thread safe and serialize the access to the underlying resource if needed. In you application you declare multiple loggers (one for each class) so there is one singleton per class not only one logger class in you application.
Different threads can invoke the same logger in paralled but it's the underlyng appender guarantees that the access to the underlyng file (o to something else) is serialized if needed (if you have an appender that sends a mail instead of writing a file you can do it concurrently).
If you want to combine multithreading and a single logfile that's not achieved by singletons, singletons only have influence in one thread to avoid another one from popping up.
Now if you break this by using multiple threads, singletons won't help you. If they did, the second thread would just be incapable of logging.
Ive seen object monitors used in java several times, but it seems to me that any object monitor logic can easily be replaced by use of synchronized code blocks and/or methods.
What is the purpose for using an explicit object monitor rather than just carefully coordinating synchronized code blocks along with Atomic primitives ?
There is always a monitor object. When you have synchronized block, your class instance is the monitor object.
So reasons to use explicit objects:
1) you can share them between class instances to synch access to a shared resource
2) more explicit
3) you can give your monitor object a helpful name
4) more flexible
You're making a distinction where none exists (or are using uncommon terminology). In Java terms, a monitor is the object used as parameter to a synchronized block (or, in the case of synchronized instance methods, implicitly the this instance, and with synchronized static method the class instance).
The main thing is that a normal synchronized block uses the enclosing object as its monitor, in other words, it's equivalent to using synchronized(this) { }. The problem is one of scoping/visibility: any class external to your class can choose to synchronize on the same instance and interfere with your synchronization logic. By using a private final reference as the monitor, this is no longer possible (assuming no reflection shenanigans).
This is formulated in Java Concurrency In Practice as follows (p61, section 4.2.1):
There are advantages to using a private lock object instead of an object's intrinsic lock (or any other publicly accessible lock). Making the lock object private encapsulates the lock so that client code cannot acquire it, whereas a publicly accessible lock allows client code to participate in its synchronization policy -- correctly or incorrectly. Clients that improperly acquire another object's lock could cause liveness problems, and verifying that a publicly accessible lock is properly used requires examining the entire program rather than a single class.
but it seems to me that any object monitor logic can easily be replaced by use of synchronized code blocks and/or methods.
Yes, this is true for the same reason that a glass of water can easily be replaced by a glass of water - they're the same thing. Java's synchronized code blocks and methods expose the monitor pattern at the language level.
I am working on my first mutlithreaded program and got stuck about a couple of aspects of synchronization. I have gone over the multi-threading tutorial on oracle/sun homepage, as well as a number of questions here on SO, so I believe I have an idea of what synchronization is. However, as I mentioned there are a couple of aspects I am not quite sure how to figure out. I formulated them below in form of clear-cut question:
Question 1: I have a singleton class that holds methods for checking valid identifiers. It turns out this class needs to hold to collections to keep track of associations between 2 different identifier types. (If the word identifier sounds complicated; these are just strings). I chose to implement two MultiValueMap instances to implement this many-to-many relationship. I am not sure if these collections have to be thread-safe as the collection will be updated only at the creation of the instance of the singleton class but nevertheless I noticed that in the documentation it says:
Note that MultiValueMap is not synchronized and is not thread-safe. If you wish to use this map from multiple threads concurrently, you must use appropriate synchronization. This class may throw exceptions when accessed by concurrent threads without synchronization.
Could anyone elaborate on this "appropriate synchronization"? What exactly does it mean? I can't really use MultiValueMap.decorate() on a synchronized HashMap, or have I misunderstood something?
Question 2: I have another class that extends a HashMap to hold my experimental values, that are parsed in when the software starts. This class is meant to provide appropriate methods for my analysis, such as permutation(), randomization(), filtering(criteria) etc. Since I want to protect my data as much as possible, the class is created and updated once, and all the above mentioned methods return new collections. Again, I am not sure if this class needs to be thread-safe, as it's not supposed to be updated from multiple threads, but the methods will most certainly be called from a number of threads, and to be "safe" I have added synchronized modifier to all my methods. Can you foresee any problems with that? What kind of potential problems should I be aware of?
Thanks,
Answer 1: Your singleton class should not expose the collections it uses internally to other objects. Instead it should provide appropriate methods to expose the behaviours you want. For example, if your object has a Map in it, don't have a public or protected method to return that Map. Instead have a method that takes a key and returns the corresponding value in the Map (and optionally one that sets the value for the key). These methods can then be made thread safe if required.
NB even for collections that you do not intend to write to, I don't think you should assume that reads are necessarily thread safe unless they are documented to be so. The collection object might maintain some internal state that you don't see, but might get modified on reads.
Answer 2: Firstly, I don't think that inheritance is necessarily the correct thing to use here. I would have a class that provides your methods and has a HashMap as a private member. As long as your methods don't change the internal state of the object or the HashMap, they won't have to be synchronised.
It's hard to give general rules about synchronization, but your general understanding is right. A data-structure which is used in a read-only way, does not have to be synchronized. But, (1) you have to ensure that nobody (i.e. no other thread) can use this structure before it is properly initialized and (2) that the structure is indeed read-only. Remember, even iterators have a remove method.
To your second question: In order to ensure the immutability, i.e. that it is read-only, I would not inherit the HashMap but use it inside your class.
Synchronization commonly is needed when you either could have concurrent modifications of the underlying data or one thread modifies the data while another reads and needs to see that modification.
In your case, if I understand it correctly, the MultiValueMap is filled once upon creation and the just read. So unless reading the map would modify some internals it should be safe to read it from multiple threads without synchronization. The creation process should be synchronized or you should at least prevent read access during initialization (a simple flag might be sufficient).
The class you descibe in question 2 might not need to be synchronized if you always return new collections and no internals of the base collection are modified during creation of those "copies".
One additional note: be aware of the fact that the values in the collections might need to be synchronized as well, since if you safely get an object from the collection in multiple thread but then concurrently modify that object you'll still get problems.
So as a general rule of thumb: read-only access does not necessarily need synchronization (if the objects are not modified during those reads or if that doesn't matter), write access should generally be synchronized.
If your maps are populated once, at the time the class is loaded (i.e. in a static initializer block), and are never modified afterwards (i.e. no elements or associations are added / removed), you are fine. Static initialization is guaranteed to be performed in a thread safe manner by the JVM, and its results are visible to all threads. So in this case you most probably don't need any further synchronization.
If the maps are instance members (this is not clear to me from your description), but not modified after creation, I would say again you are most probably safe if you declare your members final (unless you publish the this object reference prematurely, i.e. pass it to the outside world from the cunstructor somehow before the constructor is finished).
I know that the Properties class is a sub-class of Hashtable. So all the inherited methods are synchronized, but what about the other methods of Properties such as store, load, etc? (Dealing specifically with Java 1.6)
the java1.6 javadoc says:
This class is thread-safe: multiple
threads can share a single Properties
object without the need for external
synchronization.
I always found the doc disclaimer misleading, specially for beginners (pardon if it is not your case).
This class is thread-safe: multiple threads can share a single Properties object without the need for external synchronization.
Even Thread-safe classes need synchronization more than you think. What is synchronized on that classes are their methods, but often a user uses this classes in a more complex context.
If you only put/get it is ok, but with some more code things get tighter:
p.putProperty("k1","abc");
p.putProperty("k2","123");
String.out.println(p.get("k1")+p.get("k2"));
This example code only prints for shure "abc123" in a multi threaded environment, if the section is a synchronized block (and even then things could get wrong).
For that reason (and of courrse performance) i prefer non thread safe classes and i get forced to think: is my program thread safe ...