Solved

Synchronization question.

Posted on 1998-11-18
2
152 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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
PDFBox - convert image to PDF, PDF resolution 3 117
eclipse compiler vs Installed JREs option 3 76
Java Jpanels and Jframe 8 28
what is a "java.lang.System Property"   ? 20 57
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.

920 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

13 Experts available now in Live!

Get 1:1 Help Now