Synchronization question.

Posted on 1998-11-18
Last Modified: 2010-08-05
I wrote a simple package in Java where a class simply write
tracing information to a file.
This the code:
public class PulseTrace
      public void PulseTrace()
      public static int ptrace (String component_name,
                        String file_name,
                        String log_message)
            String log_string = "";
            //validate input parameters
            if (file_name.equals(""))
                  //invalid file name;
                  return -1;
            //format date & time
            Date current_time = new Date();
            SimpleDateFormat formatter = new SimpleDateFormat("dd'/'MM'/'yyyy HH':'mm':'ss'.'SSS");

            //populate log_string with formatted trace message
            log_string = formatter.format(current_time) + "|" +
                        component_name +       "|" + log_message + "\n";

                  //open file
                  RandomAccessFile raf = new RandomAccessFile(file_name,"rw");
                  //go to end of file & write
            catch (Exception e)
                  System.err.println("Exception: " + e);
                  return -1;
            return 0;

Now, I would like this package to be used by multiple
processes or multiple threads within a process. There
are two scenarios:
1) Each process or thread within a process writes to a
   different file; I am assuming there are no problems
   for this scenario.
2) Suppose all processes /threads are writing to the
   same file.
   Do I have to be worried about simultaneous access to the
   file by multiple processes/threads or is this taken care
   of by java ?

Appreciate any help/explanations.

Question by:kkandasa

Accepted Solution

msmolyak earned 20 total points
ID: 1227719
I don't think the RandomAccessFile operations are synchronized. Thus to make your code thread-safe make the block(s) or metjod(s) where you write to the file using your RandomAccessFile object synchronized. That will assure that only one thread can be in that block (method) at a time. Note that synchronization adversely affects performance, so use it judiciously.
LVL 16

Expert Comment

ID: 1227720
Synchronization is necessary if you use some Java object in different threads. The only real shared object in your example is the Class obejct of the class PulseTrace. This objects (this is a class object) has only one method - that is the
public static int ptrace (String component_name, String file_name, String log_message) so the only the only possible problem may happen when two different threads try to access at the same time this method.
Let's look inside the method. All the objects used in the method are local (created inside and thrown away inside) so two different calling threads won't access common Java object, but ... you may have a common physical object !!! - and this is the real physical file on the system. So in the worst case if two threads ask  for exactly the same file it may happen that the first thread opens and writes in the file, than second threads takes the 'focus' and now it writes too ... and everything becomes messed.
So the only possible conflict region is the file stuff.

you can
- just add 'synchronized' in the ptrace  definition -
public static synchronized int ptrace (String component_name, String file_name, String log_message)
in this case only one thread will be able to 'live' inside this method. All other threads are block until the first one exits the method
- you can create a lock object and use create a lock round the critical area (all the file related actions)
// the critical area
// ...
// all the file stuff ...

and for 1.)
1) Each process or thread within a process writes to a
       different file; I am assuming there are no problems
       for this scenario.

yes, you don't have to bother if your threads use different files - there isn't any single common object between Thread so they can't conflict at all.

I have to things to add:
1. I don't see how 'different proccesses' are supposed to use common Java object (all java object live in JavaVm which runs into single proccess)
2. I don't like
    public void PulseTrace()
constructors does not return a value - real constructor will look like
    public PulseTrace()

so any other problems ?


Featured Post

What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

For customizing the look of your lightweight component and making it look lucid like it was made of glass. Or: how to make your component more Apple-ish ;) This tip assumes your component to be of rectangular shape and completely opaque. (COD…
For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…

777 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question