Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Synchronization question.

Posted on 1998-11-18
2
Medium Priority
?
161 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
2 Comments
 
LVL 5

Accepted Solution

by:
msmolyak earned 40 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

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
In this post we will learn different types of Android Layout and some basics of an Android App.
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
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…

610 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