Solved

Synchronization question.

Posted on 1998-11-18
2
151 Views
Last Modified: 2010-08-05
Hello,
I wrote a simple package in Java where a class simply write
tracing information to a file.
This the code:
public class PulseTrace
{
      //constructor
      public void PulseTrace()
      {
            //void
      }
      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";

            try
            {
                  //open file
                  RandomAccessFile raf = new RandomAccessFile(file_name,"rw");
                  //go to end of file & write
                  raf.seek(raf.length());
                  raf.writeBytes(log_string);      
                  raf.close();
            }
            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.

Thanks
0
Comment
Question by:kkandasa
2 Comments
 
LVL 5

Accepted Solution

by:
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.
0
 
LVL 16

Expert Comment

by:heyhey_
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
or
- you can create a lock object and use create a lock round the critical area (all the file related actions)
synchronized(lockObject)
{
// 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
//constructor
    public void PulseTrace()
    {
    //void
    }
constructors does not return a value - real constructor will look like
    public PulseTrace()
    {
    //void
    }

so any other problems ?
  heyhey

0

Featured Post

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.

760 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

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now