Terminating enqueued threads at synchronized block

Hi!
I would really appreciate your opinions: :)
The application desing:
- I'm developing a web applicaction running on a Tomcat server.
- The app is being developed using Struts and Spring.
- Pages (presentation layer) are made of JSPs.
- There are Spring beans (Services) that execute the business logic.
- These Services are used by the Struts Actions.
My problem case:
1. When you submit myPage.jsp, MyAction.java's execute method is called.
2. MyAction.java uses MyService.java's "process()" method to do some file processing that takes 2 to 3 hours to finish.
3. This MyService.java is a singleton Spring bean.
4. The call to process() method is synchronized on MyAction.java like this:
public ActionForward execute(...) throws Exception {
     // Some code ...
     synchronized (this) {
          myService.process(...); // This method takes up to 3 hours to return
          // Some code ...
     return mapping.findForward("success");
}As you can imagine, many requests (threads) will be enqueued at the synchronized keyword line. Because of this, I need to provide a cancelation functionality. This would be fired by a cancel button on myPage.jsp.
So, if you tried to launch the so-long-process by the "Process" button on myPage.jsp and you received a "Waiting..." message at your screen (because the 3 hours process was launched by another client), you should be able to cancel your processing request (because you don't want to wait so much time to begin your file processing).
I would really appreciate your opinions on which would be the best approach to achive this cancelation functionality.
I'm sure there's a better way than the one I came up with: I could populate a class variable Map with "sessionId - Thread" (key - value) everytime a request arrives at the line before the synchronized block. Thus, when you clicked the Cancel button, MyAction.java would get the request's session id and then get the Thread it must terminate from the Map. Having the Thread instance, I could maybe call it's interrupt method.
I don't think that's the best approach, but it's the only one I could thought about.
Thank you very much for your time and opinions!

Well, first thing I'd say is that if you use Spring, you'd be better off using it's own Controller architecture which is, to my mind, a lot more developed than Struts, especially now you can do pretty much the whole thing with @RequestMapping rather than XML.
Having a web transaction wait for a long running server action is basically a bad idea. Rather you should have the web front end launch the file processing job and return immediately, probably showing a list of jobs to the user which may be queued, running or finished (for good or ill). One technique is to display a "background action in progress" page which submits a new transaction every few minutes to check if the job has finished yet (using a Javascript timer). If the job is still queued or running then this request displays the "in progress" page again, if finished it displays the result.
Such a page could have a "Stop" button to abort the running job if feasible.
I would suggest that you have a queue of background jobs, probably serviced by a ThreadPoolExecuter. The initial request simply builds a request object and queues it.
Use a ContextListener object to create the queue and start the executer when the application starts, and close it down when the application is stopped,

Similar Messages

  • Java thread synchronized block

    i am still a noob comes to thread and synchronized.
    i heard people said that i shouldn't synchronized on "mySet" because "mySet" is getting modified in the synchronized block.
    is this true?
    or should i use a different object to synchronized the block. what's the advantage or disadvantage to use a different object to synchronized the block.
    thanks
    public class Test {
      final Set mySet = new HashSet(); 
      final Map myMap = new HashMap();
      public void add(Object o) {
        synchronize(mySet) {
          mySet.add(o);
          myMap.add(o);
      public void clear(){
        synchronize(mySet) {
          mySet.clear();
          myMap.clear();
    }

    yaliu07 wrote:
    i am still a noob comes to thread and synchronized.
    i heard people said that i shouldn't synchronized on "mySet" because "mySet" is getting modified in the synchronized block.
    is this true? No, that's not a reason not to sync on that object. In fact, in some cases it's a reason why you should sync on that object.
    Most of the time it doesn't matter which object you sync on, as long as all the relevant blocks are synced on the same object. There are a couple of considerations to keep in mind though that might affect the choice of object.
    In some cases, you want to sync on an object that's not exposed to the outside world, for instance a private Object member variable that exists only to be a lock. The reason for this is that if you sync on something that's exposed to the outside (such as "this", which is what gets synced on when you declare a non-static method as synchronized), then other code might also sync on that object, causing deadlock or thread starvation.
    In other cases, you DO want to expose the object, so that you can use it to ensure that other code and your synced code only enter the critical sections one thread at a time. For instance, in Collections.synchronizedXxx() methods, the return object's methods are all synced on "this", and any code that iterates over that collection must also sync on that object, so that the iteration code and the collection object's own code don't step on each other's toes.
    Much of the time, however, the choice of an object to sync on is just one that's convenient and logical for the humans writing and reading the code.

  • Nested synchronized blocks on multiple objects without deadlock

    Is it possible? Here is an example problem that exhibits deadlock:
    public class SomeObject {
         public static class Foo {
              private int n = 0;
              public synchronized void p() {
                   n++;
                   if (n % 100 == 0)
                        System.out.print("f");
         public static class Bar {
              private int n = 0;
              public void p() {
                   n++;
                   if (n % 100 == 0)
                        System.out.print("b");
         public void doSomething1(Foo f, Bar b) {
              synchronized(f) {
                   synchronized(b) {
                        f.p();
                        b.p();
         public void doSomething2(Foo f, Bar b) {
              synchronized(b) {
                   synchronized(f) {
                        b.p();
                        f.p();
         public static void main(String[] args) {
              SomeObject so = new SomeObject();
              Foo f = new Foo();
              Bar b = new Bar();
              for (int i = 0; i < 100; i++)
                   (new MyThread(so, f, b)).start();
         public static class MyThread extends Thread {
              SomeObject so = null;
              Foo f = null;
              Bar b = null;
              public MyThread(SomeObject so, Foo f, Bar b) {
                   this.so = so;
                   this.f = f;
                   this.b = b;
              public void run() {
                   while (true) {
                        if (Math.random() > 0.5)
                             so.doSomething1(f, b);
                        else
                             so.doSomething2(f, b);
    }

    Well, playing with sinchronized code as to be done carefully.
    This is very important because de JVM does not break the deadlocks (like by throwing an exception in a deadlocked thread). so in the above example, once 2 of the threads do deadlock, the rest of the threads that are created in the main method loop will deadlock too.
    For that it is better to:
    a) use minimal sinchronized code, like in Foo.p, the method is sinchronized to have access to an internal variable.
    b) use layered sinchronization. If several components in a system have synchronized code (methods) or are used as monitors in synchronized blocks, then it is better to layer the monitor usage nesting and to eliminate circular dependencies (also it is good to minimize dependencies). This is similar to code dependency in which package circular dependency should be avoided. Though in this case it is critical.
    In the example given, the doSomething* methods generate circular dependency of monitors.
    If the desing is to have a 'transaction' in calling Foo.p() and Bar.p() from the doSomething* methods, then the usage of a 'grand-daddy' central lock would be a simple solution, like changing the doSomething* methods to:
    static public synchornized void doSomething*(Foo f, Bar b) {
    f.p();
    b.p();
    or
    public void doSomething*(Foo f, Bar b) {
    synchornized (SomeObject.class) {
    f.p();
    b.p();
    If there is no need of a 'transaction' in the calling of Foo.p() and Bar.p(), then the doSomething* methods should not have any type of synchronization, and the methods Foo.p() and Bar.p() should both be synchronized.
    Also a more complex scheme could be deviced in order to lower the contention on the SomeObject class monitor. Though for the example given, as it exists only one instance of both Foo and Bar, it is not needed.
    llongeri

  • ConcurrentModificationException in synchronized block?

    Edit: Narrowed it down to this:
    Caused by: java.util.ConcurrentModificationException: null
         at java.util.LinkedList$ListItr.checkForComodification(Unknown Source)
         at java.util.LinkedList$ListItr.next(Unknown Source)
         at server.ConversationServiceImpl.clientExit(ConversationServiceImpl.java:28)
    public void clientExit() {
         String currentUserId = getCurrentUserId();
         synchronized(users) {
              Iterator<User> it = users.iterator();
              while(it.hasNext()) {
                   User aUser;
                   synchronized(aUser = it.next()) { // Line 28
                        if(aUser.getId() == currentUserId) {
                             users.remove(aUser);
         UserList userList = new UserList(getUserListStrings());
         addEventToAllUsers(userList);
    }Surely since there is a synchronized block, there shouldn't be any ConcurrentModificationException?
    Edited by: ta2 on 29-Mar-2009 02:22

    Maxideon wrote:
    Not really. The problem was this line
    users.remove(aUser);When you are iterating through a collection you're suppose to remove elements with the iterator.
    it.remove();You also seem to be using synchronize blocks of code kind of haphazardly.
    For example in your original post you had a synchronized block around an object in local scope.
    synchronized(aUser = it.next()) {
    Yeah you're right... I don't really know what I'm doing with the synchronized blocks. Though another thread could get that particular user by going users.get(int thatOne), but I've already blocked that with the synchronized(users) bit. Is that what you mean?
    Cheers

  • Synchronized blocks: the best approach?

    I have a question concerning synchronization within a servlet. As I
              understand it, by default only one instance of a servlet will be
              instantiated by WebLogic. The impact of this is that if an instance
              variable is set in 'doGet', there is no guarantee that the value will be
              unchanged upon execution of 'doPost' (i.e. it is not "thread-safe").
              There are a few approaches to this problem, none of which are very
              appealing to me. If I utilize the "SingleThreadModel" interface, then I am
              guaranteed that the value will not change. However, this will occur at the
              expense of performance (isn't there a maximum of 5 instances?), especially
              if hundreds of users are concurrently attempting to access this same
              servlet. Even if I store a variable in the session, if the user can open
              multiple browser windows, then I could still run into a synchronization
              problem (since each window will share the same session).
              With this in mind (assuming that a user can open multiple browser windows
              and that I do not want to implement "SingleThreadModel"), is my only option
              to place synchronized blocks around the sections of code that I want
              protected?
              I appreciate any input. Thanks.
              

              It is possible to make this really messy - avoid that.
              Don't use intance variables, use only variables declared in the doGet method -
              each execution will have it's own variables and you won't have these problems.
              If you need data to persist from one call to the next, use the httpSession.
              If you need to manage separate browser windows - then put a hidden field or a
              parameter in the URL that identifies that window. Then store the data in the httpsession
              along with the window id -
              session.putValue("USERNAME_"+winId, username);
              Putting synchronized blocks doesn't really protect you from the multiple window
              problem - suppose a user does a search in one window - and the search results
              are stored in the http session. Then they do a second search in a second window
              - even if you protect the variables in a synchronize block - the second results
              will overwrite the first results. Then they start to page through what should
              be the first results in the first window - but they would see the second results.
              Mike Reiche
              Resume at http://home.earthlink.net/~mikereiche/resume.htm
              "Edward Mench" <[email protected]> wrote:
              > I have a question concerning synchronization within a servlet. As
              >I
              >understand it, by default only one instance of a servlet will be
              >instantiated by WebLogic. The impact of this is that if an instance
              >variable is set in 'doGet', there is no guarantee that the value will
              >be
              >unchanged upon execution of 'doPost' (i.e. it is not "thread-safe").
              >
              > There are a few approaches to this problem, none of which are very
              >appealing to me. If I utilize the "SingleThreadModel" interface, then
              >I am
              >guaranteed that the value will not change. However, this will occur
              >at the
              >expense of performance (isn't there a maximum of 5 instances?), especially
              >if hundreds of users are concurrently attempting to access this same
              >servlet. Even if I store a variable in the session, if the user can
              >open
              >multiple browser windows, then I could still run into a synchronization
              >problem (since each window will share the same session).
              >
              > With this in mind (assuming that a user can open multiple browser windows
              >and that I do not want to implement "SingleThreadModel"), is my only
              >option
              >to place synchronized blocks around the sections of code that I want
              >protected?
              >
              > I appreciate any input. Thanks.
              >
              >
              >
              >
              

  • Thread confusion - synchronized keyword

    Hi All,
    I am trying to understand when and how to use synchronized. From my tinkering I have come to a situation that is confusing me:
    I have an object with two (unsynchronized) methods (called inc and dec). These methods increment and decrement an Integer field called counter. The methods then sleep for a random amount of time.
    The contents of the methods are enclosed with a synchronized block, synchronized to the field 'counter'.
    I now create two threads, one calling inc the other dec continuously.
    From the output the methods are not synchronizing at all.
    If I change the synchronized block to sync to a different variable, eg. 'this' or an arbitrary unused object, the code synchronizes properly.
    My question/problem is why does the code not synchronize properly on an object that I am altering in the synchronized block.
    A second and (hopfully) related question - is:
    synchronized public void foo() {...}syntactic sugar for:
    public void foo() {
       synchronized (this) {...}
    }Thank you for your time in reading this, any help would be very appreciated.
    Alex.

    Peter-Lawrey - Thankyou!!!
    It's obvious now - by creating a new Integer object I am synchronizing on different objects in the two methods, hence still failing to lock the other thread out... DOH!
    Here's one of the methods for completeness
         public void inc() {
              synchronized (this) {
                   System.out.print("Inc = ");
                   try {
                        sleep(1001);
                   } catch (InterruptedException e) {
                        e.printStackTrace();
                   counter = new Integer(counter.intValue() + 1);
                   System.out.println(counter.toString());
         } As Integers are readonly I have to intValue, then increment then create a new Integer Object.
    Out of curiosity - does the synchronized block fail at this point or does is now apply to the new object until the end of the block is reached?
    Thankyou again for your help and returning a small part of my sanity!
    Alex.

  • IllegalMonitorStateException Thrown From Synchronized Block

    Greetings,
    We recently had a case where a java.lang.IllegalMonitorStateException was thrown from section of code (in activemq) that I'm 99.9% sure was properly synchronized. Has anyone ever seen this exception thrown when the object whose wait method is being called is currently owened (via. a synchronized block)?
    The code that this exception occurred was in the backport-util-concurrent library. A get method (which is synchronized) call was made to a FutureTask instance which (eventually) calls Object.wait(). This call threw the exception. Below is the FutureTask code.
    public synchronized Object get() throws InterruptedException, ExecutionException
      waitFor();
      return getResult();
    private void waitFor() throws InterruptedException
      while (!isDone())
        wait();
    }And the stack trace on the exception was:
    ERROR - 21/2 08:56:41 - Failed to checkpoint a message store: java.lang.IllegalMonitorStateException - org.apache.activemq.store.journal.JournalPersistenceAdapter 395
    java.lang.IllegalMonitorStateException
    at java.lang.Object.wait(Native Method)
    at java.lang.Object.wait(Object.java:485)
    at edu.emory.mathcs.backport.java.util.concurrent.FutureTask.waitFor(FutureTask.java:267)
    at edu.emory.mathcs.backport.java.util.concurrent.FutureTask.get(FutureTask.java:117)
    at org.apache.activemq.store.journal.JournalPersistenceAdapter.doCheckpoint(JournalPersistenceAdapter.java:386)
    at org.apache.activemq.store.journal.JournalPersistenceAdapter$2.iterate(JournalPersistenceAdapter.java:129)
    at org.apache.activemq.thread.PooledTaskRunner.runTask(PooledTaskRunner.java:117)
    at org.apache.activemq.thread.PooledTaskRunner.access$100(PooledTaskRunner.java:26)
    at org.apache.activemq.thread.PooledTaskRunner$1.run(PooledTaskRunner.java:44)
    at edu.emory.mathcs.backport.java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:650)
    at edu.emory.mathcs.backport.java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:675)
    at java.lang.Thread.run(Thread.java:619)We are running Java 1.6 on solaris (64-bit). If anybody has any feedback on what might have caused this problem it would be appreciated.
    Thanks,
    Corey

    There seem to be some difficult to reproduce bugs in JDK 6 relating to hotspot compilation (and maybe synchronization). A few threads worth checking out:
    http://forum.java.sun.com/thread.jspa?threadID=5251785&tstart=0
    http://forum.java.sun.com/thread.jspa?threadID=5262404&tstart=0
    My own bug report (this one is reproducible): http://www.blinkenbyte.org/jvm/hotspot_bug_reviewid_1085121.html
    Which reminds me, I need to get around to submitting an update to the report.. disabling HotSpot compilation on the problematic method made the problem go away in my case...
    If at all possible to turn this into a test case, please do so and submit a bug report to Sun. Somehow Sun needs to pay attention to this problem, but I haven't even got a bug id on my problem despite it being 100% reproducible.

  • Performance of synchronized blocks on Linux much worse than on Windows

    Our application is a J2EE application currently deployed in WebLogic 6.1 which utilizes Oracle iFS as a content store. We access the iFS CMS through the api's provided in the cmdsk.jar. Our reference implementation has been Solaris and that's where most of our testing has been done so far. However, we recently began doing performance tests on Linux and ran into a strange problem. We found that we were not getting sufficient throughput and that this was coupled with underutilization of CPU resources on the Application Server (AS) node. With sufficient DB resources, which we had in this case, we expect to see full CPU utilization on the AS tier, so we knew something was wrong.
    A great deal of investigation revealed that all active threads were stuck at the same spot accessing an iFS cache. We found that this cache is implemented as a hashtable and accesses to hashtables are synchronized. However, we were not seeing the same problem on other platforms (Solaris and Windows) with dual CPU machines.
    In order to simplify things, we developed a test program to look at what we felt to be the root cause. This test program, which I will attach, essentially creates a hashtable then a number of threads (as specified by the user). These threads then use the hashtable.get method to access the hashtable concurrently and time how long it takes. The info is then returned at the end of the run.
    We ran a set of tests where we increased the number of threads from 1 to 100. This test was run once with Windows 2000 and once with Red Hat Linux 2.1 (kernel 2.4.9-e.12). The exact same hardware (dual 1.2 GHz PIII) was used in both cases. The results show that we were clearly able to reproduce the behaviour with this simple program. What these results show is that with one thread, access times are exactly the same for Windows and Linux. However, as we increase the number of threads, access times for Linux increase at a much greater rate than Windows. We also see underutilization of CPU resources on Linux while Windows uses all available.
    The first round of tests was run with Sun's JDK 1.3.1. We repeated the testing with 1.4.1 and found that there was no significant difference. I just tried it quickly with 1.4.2 and found the behaviour to be much the same. We also altered the program to use an unsynchronized hashmap instead of a hashtable and, as expected, performance on Linux was much better. CPU was fully utilized during the test.
    In order to determine if this was a problem "in the VM" or "in the kerenel", I tried repeating it with the JRocket VM provided by WebLogic. When running the same test with the JRocket VM, we saw performance roughly equivalent to what we saw with a hashmap and the Sun VM. That is, JRocket did not have the same problem as the Sun VM.
    So, it appears that there is something with the implementation of synchronized blocks in the Sun VM that is problematic, especially when compared to other platforms. It is likely that the problem lies in a combination of how the synchronization is implemention is based on the underlying operating system infrastructure. At this point, we don't really have a way to deal with the problem, aside from deploying multiple WebLogic nodes on the same 2 CPU physical AS node. Changes to the iFS infrastructure would help, but that's beyond our control. I've searched the bug database and have not seen mention of this problem. With the test program, it can be easily reproduced, but I wanted to run it by the folks on this list before submitting a bug.
    Thanks,
    Justin

    # File #1: Driver.java
    import java.io.*;
    import java.util.HashMap;
    import java.util.Hashtable;
    * Created on May 13, 2003
    * @author llai
    * Driver to test the access of hash table on various platforms.
    public class Driver
         public static void main(String[] args)
              * Obtain the following input values:
              * 1. Number of Elements
              *      - The number of elements in the hash table
              * 2. Size of Element
              * - The size of each element in the hash table
              * 3. Number of threads
              * - The number of concurrent threads in the test
              * 4. Focused Access
              * - Determines whether each thread access the same element or a random element
              * 5. Number of Accesses
              * - The number of accesses which each thread will complete before exiting
              * 6. Start offset
              * - The number of accesses at the beginning which will not be timed
              * 7. End offset
              * - The number of accesses at the end which will not be timed.
              * Initialize all input variables.
              * SET DEFAULT VALUES HERE...
              int numberOfElements = 10000;
              int sizeOfElement = 100;
              int numberOfThreads = 25;
              boolean focusedAccess = true;
              int numberOfAccesses = 1000000;
              int startOffset = 100000;
              int endOffset = 100000;
              boolean mapOrTable = false;
              * Input number of elements.
              try
                   BufferedReader in =
                        new BufferedReader(new InputStreamReader(System.in));
                   String tempInput;
                   boolean inputInvalid = true;
                   while (inputInvalid)
                        System.out.print(
                             "Enter a non-negative value for the number of elements to be in the hashtable: ");
                        tempInput = in.readLine();
                        if (tempInput.equals(""))
                             System.out.println("default value used.\n");
                             inputInvalid = false;
                        else
                             try
                                  numberOfElements = Integer.parseInt(tempInput);
                                  if (numberOfElements >= 0)
                                       inputInvalid = false;
                                  else
                                       System.out.println(
                                            "You entered a negative value for the number of elements. Try again.");
                             catch (NumberFormatException nfe)
                                  System.out.println(
                                       "You entered an invalid value for the number of elements. Try again.");
                   * Input size of elements.
                   inputInvalid = true;
                   while (inputInvalid)
                        System.out.print(
                             "Enter the size of each element in the hash table (ie. length of a string): ");
                        tempInput = in.readLine();
                        if (tempInput.equals(""))
                             System.out.println("default value used.\n");
                             inputInvalid = false;
                        else
                             try
                                  sizeOfElement = Integer.parseInt(tempInput);
                                  if (sizeOfElement >= 0)
                                       inputInvalid = false;
                                  else
                                       System.out.println(
                                            "You entered a negative value for the size of elements. Try again.");
                             catch (NumberFormatException nfe)
                                  System.out.println(
                                       "You entered an invalid value for the size of elements. Try again.");
                   * Input number of threads.
                   inputInvalid = true;
                   while (inputInvalid)
                        System.out.print(
                             "Enter the number of concurrent threads in the test: ");
                        tempInput = in.readLine();
                        if (tempInput.equals(""))
                             System.out.println("default value used.\n");
                             inputInvalid = false;
                        else
                             try
                                  numberOfThreads = Integer.parseInt(tempInput);
                                  if (numberOfThreads >= 0)
                                       inputInvalid = false;
                                  else
                                       System.out.println(
                                            "You entered a negative value for the number of threads. Try again.");
                             catch (NumberFormatException nfe)
                                  System.out.println(
                                       "You entered an invalid value for the number of threads. Try again.");
                   * Input focused access option.
                   inputInvalid = true;
                   while (inputInvalid)
                        System.out.print(
                             "Focused access? Determines whether each thread access the same element or a random element (y/n or blank for default): ");
                        String tempFocusedAccess = in.readLine();
                        if (tempFocusedAccess.equals("y"))
                             focusedAccess = true;
                             inputInvalid = false;
                        else if (tempFocusedAccess.equals("n"))
                             focusedAccess = false;
                             inputInvalid = false;
                        else if (tempFocusedAccess.equals(""))
                             System.out.println("default value used.\n");
                             inputInvalid = false;
                        else
                             System.out.println(
                                  "You entered an invalid input for focused access. Try again.");
                   * Input number of accesses.
                   inputInvalid = true;
                   while (inputInvalid)
                        System.out.print(
                             "Enter a non-negative value for the number of accesses each thread will complete: ");
                        tempInput = in.readLine();
                        if (tempInput.equals(""))
                             System.out.println("default value used.\n");
                             inputInvalid = false;
                        else
                             try
                                  numberOfAccesses = Integer.parseInt(tempInput);
                                  if (numberOfAccesses >= 0)
                                       inputInvalid = false;
                                  else
                                       System.out.println(
                                            "You entered a negative value for the number of accesses per thread. Try again.");
                             catch (NumberFormatException nfe)
                                  System.out.println(
                                       "You entered an invalid value for the number of accesses per thread. Try again.");
                   * Input start offset.
                   inputInvalid = true;
                   while (inputInvalid)
                        System.out.print("Enter the start offset: ");
                        tempInput = in.readLine();
                        if (tempInput.equals(""))
                             System.out.println("default value used.\n");
                             inputInvalid = false;
                        else
                             try
                                  startOffset = Integer.parseInt(tempInput);
                                  if (startOffset <= numberOfAccesses
                                       && startOffset >= 0)
                                       inputInvalid = false;
                                  else
                                       System.out.println(
                                            "You entered an invalid input for start offset. Try again.");
                             catch (NumberFormatException nfe)
                                  System.out.println(
                                       "You entered an invalid value for the start offset. Try again.");
                   * Input end offset.
                   inputInvalid = true;
                   while (inputInvalid)
                        System.out.print("Enter the end offset: ");
                        tempInput = in.readLine();
                        if (tempInput.equals(""))
                             System.out.println("default value used.\n");
                             inputInvalid = false;
                        else
                             try
                                  endOffset = Integer.parseInt(tempInput);
                                  if (endOffset <= numberOfAccesses && endOffset >= 0)
                                       inputInvalid = false;
                                  else
                                       System.out.println(
                                            "You entered an invalid input for end offset. Try again.");
                             catch (NumberFormatException nfe)
                                  System.out.println(
                                       "You entered an invalid value for the end offset. Try again.");
                   * Create a Hashtable, or a Hashmap?
                   inputInvalid = true;
                   while (inputInvalid)
                        System.out.print(
                             "Use HashMap or HashTable (enter m for HashMap, t for HashTable)? ");
                        String tempMapTable = in.readLine();
                        if (tempMapTable.equals("m"))
                             mapOrTable = true;
                             inputInvalid = false;
                        else if (tempMapTable.equals("t"))
                             mapOrTable = false;
                             inputInvalid = false;
                        else if (tempMapTable.equals(""))
                             System.out.println("default value used.\n");
                             inputInvalid = false;
                        else
                             System.out.println(
                                  "You entered an invalid input. Try again.");
              catch (IOException i)
                   System.out.println("IOException caught: " + i.getMessage());
              * End of obtaining input section. *****
              * Create a HashTable or HashMap of the size and distribution specified.
              Object hash;
              if (mapOrTable)
                   // create a HashMap
                   hash = new HashMap(numberOfElements);
              else
                   // create a HashTable
                   hash = new Hashtable(numberOfElements);
              char c[] = new char[sizeOfElement];
              for (int i = 0; i < numberOfElements; i++)
                   if (mapOrTable)
                        ((HashMap) hash).put(new Integer(i), new String(c));
                   else
                        ((Hashtable) hash).put(new Integer(i), new String(c));
              c = null; // Explicitly release c.
              * Create the specified number of threads.
              AccessorThread accessor[] = new AccessorThread[numberOfThreads];
              long seed;
              for (int i = 0; i < numberOfThreads; i++)
                   // Have a different seed for creating random number for each thread.
                   seed = System.currentTimeMillis() + 77 * i;
                   accessor[i] =
                        new AccessorThread(
                             hash,
                             numberOfElements,
                             focusedAccess,
                             numberOfAccesses,
                             startOffset,
                             endOffset,
                             seed);
                   // Start the thread.
                   accessor.start();
              * Make main wait for all threads to die before continuing.
              try
                   for (int i = 0; i < numberOfThreads; i++)
                        accessor[i].join();
              catch (InterruptedException ie)
                   System.out.println(
                        "InterruptedException caught: " + ie.getMessage());
              * Threads have now been run, so create a statistical report.
              System.out.println(
                   "The following settings were used for this test: \n"
                        + "Number of elements: "
                        + numberOfElements
                        + "\n"
                        + "Size of elements: "
                        + sizeOfElement
                        + "\n"
                        + "Number of threads: "
                        + numberOfThreads
                        + "\n"
                        + "Focused access: "
                        + focusedAccess
                        + "\n"
                        + "Number of accesses: "
                        + numberOfAccesses
                        + "\n"
                        + "Start offset: "
                        + startOffset
                        + "\n"
                        + "End offset: "
                        + endOffset);
              System.out.print("HashMap or HashTable: ");
              if (mapOrTable)
                   System.out.println("HashMap.\n");
              else
                   System.out.println("HashTable.\n");
              System.out.println("Statistic report: ");
              long avgTime;
              long avgTotalTime = 0;
              for (int i = 1; i <= numberOfThreads; i++)
                   avgTotalTime += accessor[i - 1].getAccessTime();
                   avgTime = accessor[i - 1].getAccessTime() / numberOfAccesses;
                   System.out.println(
                        "Thread "
                             + i
                             + "... "
                             + accessor[i
                             - 1].getStatus()
                             + " Total access time: "
                             + accessor[i
                             - 1].getAccessTime()
                             + " ms. Avg individual access time: "
                             + avgTime
                             + " ms.");
              avgTotalTime = avgTotalTime / numberOfThreads;
              // Make it an average over all threads.
              System.out.println(
                   "\nThe average total access time over all threads: "
                        + avgTotalTime
                        + " ms.");
    File#2: AccessorThread.java
    import java.util.Hashtable;
    import java.util.HashMap;
    import java.util.Random;
    * Created on May 13, 2003
    * @author llai
    * Threaded class that accesses a hashtable a certain number of times
    * and measures the access time for a certain number of accesses.
    public class AccessorThread extends Thread
         private Object hash;
         private int numberOfElements;
         private boolean focusedAccess;
         private int numberOfAccesses;
         private int startOffset;
         private int endOffset;
         private long seed;
         private long totalAccessTime;
         private String status;
         * Constructor
         * @param h the Hashtable or HashMap
         * @param keyToAccess the key to access for this thread
         * @param numberOfAccesses the number of access times
         * @param startOffset the start offset
         * @param endOffset the end offset
         public AccessorThread(
              Object h,
              int numberOfElements,
              boolean focusedAccess,
              int numberOfAccesses,
              int startOffset,
              int endOffset,
              long seed)
              this.hash = h;
              this.numberOfElements = numberOfElements;
              this.focusedAccess = focusedAccess;
              this.numberOfAccesses = numberOfAccesses;
              this.startOffset = startOffset;
              this.endOffset = endOffset;
              this.seed = seed;
              status = "Status: alive.";
         * @return the total access time.
         public long getAccessTime()
              return totalAccessTime;
         * @return the status of the thread.
         public String getStatus()
              return status;
         * @return the seed.
         public long getSeed()
              return seed;
         * Run method, accesses the hashtable at keyToAccess for
         * numberOfAccesses times, and measures the response time for
         * a certain number of those accesses.
         public void run()
              * Begin accessing the table, time only after startOffset accesses,
              * and only up to (numberOfAccesses - endOffset) accesses.
              * Access one value if focusedAccess on.
              * Access random values if focusedAccess off.
              Random numGenerator = new Random(seed);
              if (focusedAccess)
                   Object keyToAccess =
                        new Integer(numGenerator.nextInt(numberOfElements));
                   // Access without timing for the first startOffset accesses.
                   int i;
                   // Check if hash is a HashMap or Hashtable.
                   if (hash instanceof HashMap)
                        for (i = 0; i < startOffset; i++)
                             ((HashMap) hash).get(keyToAccess);
                        // Now start timing for the accesses.
                        long startTime = System.currentTimeMillis();
                        while (i < numberOfAccesses - endOffset)
                             ((HashMap) hash).get(keyToAccess);
                             i++;
                        long stopTime = System.currentTimeMillis();
                        totalAccessTime = stopTime - startTime;
                        // Finish accessing the remainder of endOffset times if endOffset is not >= (numberOfAccesses - startOffset).
                        while (i < numberOfAccesses)
                             ((HashMap) hash).get(keyToAccess);
                             i++;
                   else if (hash instanceof Hashtable)
                        for (i = 0; i < startOffset; i++)
                             ((Hashtable) hash).get(keyToAccess);
                        // Now start timing for the accesses.
                        long startTime = System.currentTimeMillis();
                        while (i < numberOfAccesses - endOffset)
                             ((Hashtable) hash).get(keyToAccess);
                             i++;
                        long stopTime = System.currentTimeMillis();
                        totalAccessTime = stopTime - startTime;
                        // Finish accessing the remainder of endOffset times if endOffset is not >= (numberOfAccesses - startOffset).
                        while (i < numberOfAccesses)
                             ((Hashtable) hash).get(keyToAccess);
                             i++;
              // Or else !focusedAccess, therefore access random values.
              else
                   * Get random keys to access and store in an array of Integer objects.
                   * Limit the array to 1000 integer objects.
                   int numberOfRandomInts = numberOfAccesses;
                   if (numberOfAccesses > 1000)
                        numberOfRandomInts = 1000;
                   Integer keysToAccess[] = new Integer[numberOfRandomInts];
                   for (int q = 0; q < numberOfRandomInts; q++)
                        keysToAccess[q] =
                             new Integer(numGenerator.nextInt(numberOfElements));
                   int i;
                   if (hash instanceof HashMap)
                        for (i = 0; i < startOffset; i++)
                             ((HashMap) hash).get(keysToAccess[i % numberOfRandomInts]);
                        // Now start timing for the accesses.
                        long startTime = System.currentTimeMillis();
                        while (i < numberOfAccesses - endOffset)
                             ((HashMap) hash).get(keysToAccess[i % numberOfRandomInts]);
                             i++;
                        // Stop the timing.
                        long stopTime = System.currentTimeMillis();
                        totalAccessTime = stopTime - startTime;
                        // Finish accessing the remainder of endOffset times if endOffset is not >= (numberOfAccesses - startOffset).
                        while (i < numberOfAccesses)
                             ((HashMap) hash).get(keysToAccess[i % numberOfRandomInts]);
                             i++;
                   else if (hash instanceof Hashtable)
                        for (i = 0; i < startOffset; i++)
                             ((Hashtable) hash).get(keysToAccess[i % numberOfRandomInts]);
                        // Now start timing for the accesses.
                        long startTime = System.currentTimeMillis();
                        while (i < numberOfAccesses - endOffset)
                             ((Hashtable) hash).get(keysToAccess[i % numberOfRandomInts]);
                             i++;
                        // Stop the timing.
                        long stopTime = System.currentTimeMillis();
                        totalAccessTime = stopTime - startTime;
                        // Finish accessing the remainder of endOffset times if endOffset is not >= (numberOfAccesses - startOffset).
                        while (i < numberOfAccesses)
                             ((Hashtable) hash).get(keysToAccess[i % numberOfRandomInts]);
                             i++;
              status = "Status: dead.";
    # File #3: run.sh
    echo Compiling the program...
    javac Driver.java AccessorThread.java
    export CLASSPATH=.
    echo Running the program...
    java Driver

  • Synchronized blocks within servlet doPost and/or doPost

    Hey,
    Does anyone know if there are any potential problems with using a synchronized block within a servlet doGet or doPost method? The blocks are local (I'm not synchronizing the whole doGet or doPost method) and synchronized on the servlet using the "this" keyword.
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    synchronized(this)
    try
    /** critical section **/
    } catch (Exception e) {System.out.println("error " + e);}
    Does anyone know any reason that this shouldn't be done?
    thanks,
    Bryan

    Thanks to both respondants.
    The synchronized block is needed in this case to fix an existing problem. The fix could also be made by restructuring the application a bit, but I hesitate to do so in this case.
    I'm aware that it's best to avoid doing any thread operations in Servlets and was wondering whether this extended to synchronized blocks as well. Thanks again.
    Without introducing too much uneccessary detail, it's sufficient to say that the problem occurs when two users are simultaneously in the block at the same time.
    Thanks again,
    Bryan

  • Synchronization problems in synchronized block

    I am facing problems in the synchronizaed block similar to this :
    sychronized(object)
    //object manipulations
    object notifyAll();
    I am facing a problem when 2 requests are fired at the same time and none of them enter this block. Since this is re\lated to the server, server is getting freezed and none of the further requests are entertained.
    Please help me in this.
    Thanks is advance.

    Thanks for all your replies.
    Let me a bit more clearer about my problem.
    I have
    1. 2 classes which have synchronized blocks on one object of a different class
    2. This object which is synchronized is shared among both the classes.
    When an individual request comes, it is processes without any issues. Sometimes, when multiple requests come simultaneously when lock on the object is free, none of requests get the lock on the object. I tried putting a breakpoint where lock is provided, none of the threads are entering the synchronized block.
    So at this point server is not able to entertain any of the further requests also.

  • Synchronized {blocks} are not synchronized ?

    Hi
    I have a stored procedure containing a method with a synchronized block :
    public class MyClass {
    private static Connection conn;
    public static void insert(String stringData) {
    synchronized (conn) {
    //LOGGING
    Date startTime = new java.util.Date();
    ... some code ...
    //LOGGING
    Date stopTime = new java.util.Date();
    }I suppose that when a lot of concurrent users wil use the stored procedure, the synchronized block of code will not be executed at the same time. But when I do that my log dates are overcrossing, that means concurrent execution.
    How can I make this code really synchronized ??
    thanks,
    Xavier
    null

    radiatejava wrote:
    You mentioned there could be some thread caching - can you pls explain why/how ? Since the threads are not accessing the variable directly and instead they are querying the object using a method, why would the method return some old value ? I understand in case of direct access to the variable, a thread can cache the variable. Do you mean to say that threads will also cache the methods ? Otherwise, how is it possible to return the stale value. I am not expecting a blind answer like XClass is not thread safe (I too agree to this) but some explanation on how caching is being done with method calls too.You are thinking of it in a wrong way. It doesn't matter if methods are cached or not, methods are just static code blocks. The important thing to understand is that all data can be cached unless it is volatile or synchronized. The integer "inside" XClass is data, and that data might get cached, so e.g. getVar can return the cached value. It doesn't need to read the value from main memory. The same applies to setVar, it doesn't need to update the value in main memory.

  • Actions after synchronized block happens-after?

    Hi,
    I'd like to verify that my intuitive understanding of synchronization is correct here. I've read the Java language specification but I couldn't find anything in my example. This relates very loosely to the double-checking (anti)pattern.
    My question is specifically: Say I have the code:
    public void method() {
        synchronized(anyObject) {
            actionA();
        actionB();
    }Does actionA() then have a happens-before relationship with actionB()?
    Thanks a lot!

    Thanks, but I'm not sure I understand.
    In my intuition, if a thread enters method(), it must wait (possibly no time at all) to acquire the anyObject lock before it can execute actionB() from a program perspective.
    What I read in the Java Specs was "If x and y are actions of the same thread and x comes before y in program order, then hb(x, y)." I wasn't sure if a synchronized block counts as an "action" in this case.
    Let me rephrase my question to be more specific. For any given thread that enters method(), can I be sure that actionA() on that thread will execute before actionB() on the same thread?
    Thanks!
    Edited by: bombax on Nov 8, 2012 10:11 AM

  • Java synchronized block question...

    If I have the following setup
    Hashtable h = ...; // there will only be one instance of h in the program's execution
    public void A(...) {
        syncronized(h) {
            // read or write from h
    public void B(...) {
        syncronized(h) {
            // read or write from h
    }I understand that only one of the synchronized blocks can execute at a time, however, does that also mean that each will be seeing the most recent copy of h? For instance, if I write something to h in A(), can I be guaranteed that when I read from h in B() that I will always read h directly from memory and not some cached value on that particular thread?
    Thanks!

    I was under the impression though that if thread 1 calls A() and adds something to h, then thread 2 calls B() and reads from h that thread 2 might have a different copy of h and not see the change that thread 1 made.
    I've been looking around and it seems that as long as you used synchronized as soon as the lock ends any changes to the object will be written to the main memory and also any time a lock starts the object is read from memory and not from that particular thread's cache (which may not contain the recent changes). Which I guess answers my original question, and Yes, each time one of those sync blocks starts they will have the most recent value of h, no matter what thread last modified it.

  • Synchronized block

    Hi,
    Can any body comment on the following?
    "Only one of the synchronized methods in a class object can be executed by ANY thread at a time"
    Is the above true for synchronized blocks also, I mean if one thread is in a synchronized blk and executing wait, other thread cant be in the other synchronized blk executing notify???
    Zulfi.

    This means that wait notify must be encapsulated in a
    synchronize blk.Yes.
    Everything is fine but are there any other methods of
    an object where I can demonstrate that two threads
    cant call its two different methods at the same
    time??It will be nigh impossible to prove that two threads can't access a set of blocks of code at the same time, because even if they could, there's no way for you to force them to. If you don't see them in these blocks at the same time, it might be that they can be, but the scheduler just happened to work out such that they weren't.
    You could do something like this, which, though it doesn't prove anything, makes a pretty strong suggestion:
    public synchronized m1() {
        System.out.println("going to sleep");
        Thread.sleep(3600000); // sleep for an hour
        System.out.println("woke up");
    public synchronized m2() {
       System.out.println("In m2");
    }Have one thread call m1. Either have the invoking thread sleep for a few seconds or use wait/notify to make sure that the m1 thread actually gets cpu time and calls m1.
    Then start one or more threads that all m2. Since the first thread will be sleeping for an hour, and your program's not doing anything else, it's extremely extremely likely that the other thread(s) will get CPU time. If you don't see "In m2", it's almost a guarantee that the only reason is because they're waiting on the lock that the first thread holds.
    If you want to be more clever, have all the threads print out times just before and after they enter m1 and m2. Change the sleep time in m1, and observe the the time that the other threads wait tracks that.
    Note that this is still not a guarantee that those threads can't enter that block. But reading and understanding the docs, and seeing this behavior that is consistent with what the docs say, should be enough to convince you.

  • Is volatile necessary for variables only accessed inside synchronized block

    Hi,
    I am using ExecutorService to execute a set of threads. Then the calling thread needs to wait until all of them are done to reuse the thread pool to run another set of threads (so I can't use the ExecutorService.shutdown() to wait for all of the threads at this point). So I write a simple monitor as below to coordinate the threads.
    My question is: will it work? someone suggests that it might not work because it will busy spin on the non-volatile int which may or may not be updated with the current value from another thread depending on the whims of the JVM. But I believe that variables accessed inside synchronized blocks should always be current. Can anyone please help me to clarify this? Really appreciate it.
         * Simple synchronization class to allow a thread to wait until a set of threads are done.
         class ThreadCoordinator{
         private int totalActive = 0;
         public synchronized void increment(){
         totalActive++;
         notifyAll();
         public synchronized void decrement(){
         totalActive--;
         notifyAll();
         public synchronized void waitForAll(){
         while(totalActive != 0){
         try{
         wait();
         }catch (InterruptedException e){
         //ignore
         }

    Don't do that. Just save the Futures returned by the ExecutorService, and call get() on them all. This will only return when all the tasks have finished.

Maybe you are looking for

  • Report  from system on different stock levels-min, max stock levels

    hI gURUS, Is there any Standard Report  from  SAP system to see on different stock levels-minIMUM stock, maximum stock levels

  • Xorg settings not persistent

    Just did a fresh install of ArchLinux, got everything setup how I'd like, and then started fiddling with getting my displays configured. I knew it would be a chore since one of my displays reports corrupted EDID information, which throws everything o

  • Using the capture with the canopus converter

    The other day I was able to capture an dvd to it's end.  Today I'm working with another old dvd that I want to capture in CS4 however, it quits 18 mintutes into the capturing stating max amount has been captured. I think I may have my set points wron

  • Can't download 10.6.4

    I've been trying for days to download the new Mac OS X Update 10.6.4 and I keep getting that grey screen with the black box in the center that says I need to shut the computer down, or the computer just freezes. I have one of the new iMacs from late

  • Setting up Contact forms on AS3, Flash CS5????

    Does anyone have a clear answer for me please, I have been through Training with Trani on HD and also with the Lynda.com package, as I try to make the second contact form - the program tells me that there is a function repitition so what must I do ca