Thursday, April 12, 2012

Making a scheduled method Thread safe

I have a method that is invoked by a scheduler every minute to get a file from ftp, process and persists its records to a DB. I need to make this thread safe so that if the method has to perform multiple files at once, it acts a in a thread safe way..



public synchronized void processData(String data){
//do processing
}


is this really going to be a thread safe method that will handle high volumes of load gracefully?





1 comment:

  1. It's thread-safe as long as it doesn't use any stateful fields from the enclosing object.

    In other words, if there is a class-level field that is manipulated or accessed in processData(String data) with the intention of keeping track of what's going on, then it's not thread-safe.

    An example might be a class-level field called private Boolean hasConnection; If you need to check whether or not a connection exists with this field, then you don't have a thread-safe method.

    If you meet this requirement, then you don't even have to add the synchronized keyword to your method. It will be, by default, thread-safe, and an unlimited number of threads may access it simultaneously.

    If you do not meet this requirement, then you will need to post the whole class in order to determine whether or not it is thread-safe.

    ReplyDelete