Synchronized execution of threads

How do I synchronize the execution of two threads?
I am using two threads, the main thread to handle input and output, and a secondary thread to execute third party procedural code.
The main thread has to wait for commands from the procedural thread and then relay those to the client.
While the client has control, the procedural thread has to wait and vice versa. I couldn't get this to work yet.
Below is the simplest example I could extract from the code. I have tried it with java.util.concurrent as well but couldn't pause the main (servlet) thread with that, only threads in the thread pool.
Your help will be greatly appreciated!
Here is the code :
[http://connexioncafe.info/java/SyncExample.java|http://connexioncafe.info/java/SyncExample.java]
Thank you in advance!

I'll try and post the code in three parts:
* This is a simulation of a server.  It has two threads:
* [1] main thread used for input and output (in this case communication with command line client).
*      it could be a servlet in practice
* [2] and a procedural thread for executing third party code (e.g. PHP)
* The main thread start the procedural thread
*      *the main thread waits
* the procedural thread reads a stack, one item at a time
* if the command in the stack is an input or output command
* *the procedural thread sets the command on the main thread
* *the procedural thread notifies/wakes up the main thread [A]
* *the procedural thread waits
* the main thread is woken up by the procedural thread [A]
* *it executes the command as set by the procedural thread
* *it sets the result on the message variable
* *it notifies/wakes up the procedural thread
* *the main thread waits for the next command from the procedural thread [B]
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class SyncExample {
//a simple int value that is visible by both threads used for messaging
public int message = -1;
//a command that is passed between threads either executing on the client or server side
public int command = -1;
//all the possible commands
public static final int DO_INPUT = 1;
public static final int DO_OUTPUT = 2;
public static final int DO_QUIT = 3;
public static final int DO_STORAGE = 4;
public static final int DO_PROCESS = 5;
//commands with an int value greater or equal to SERVER_SIDE executes on the server side
public static final int SERVER_SIDE = 3;
//a lock used to wait() the procedural thread
public final Object procLock = new Object();
//a lock used to wait() the main thread
public final Object mainLock = new Object();
//a lock used to sync message value between threads
public final Object msgLock = new Object();
//a lock used to sync command value between threads
public final Object cmdLock = new Object();
//========================================================================== Procedural Thread
public class ProcThread extends Thread {
//some third party code that will be executed by this thread
private AlgorithmI aProc;
//some functions that will be used to execute the third party code
private final SysFunctions sysFunctions;
public ProcThread(AlgorithmI aProc, SysFunctions sf) {
this.aProc = aProc;
this.sysFunctions = sf;
@Override
public void run() {
int cmd = 0;
for (int i = 0; i < aProc.getStack().length; i++) {
cmd = aProc.getStack();
if (cmd >= SERVER_SIDE) {
switch (cmd) {
case DO_STORAGE:
sysFunctions.storage();
break;
case DO_PROCESS:
aProc.calculate();
break;
default:
break;
} else {
setCommand(cmd);
//TODO: RESUME MAIN THREAD SO THAT IT CAN COMMUNICATE WITH CLIENT
synchronized (mainLock) {
mainLock.notify();
//TODO: PAUSE THIS PROCEDURAL THREAD UNTIL MAIN THREAD HAS COMPLETED THE COMMAND
synchronized (procLock) {
try {
procLock.wait();
} catch (InterruptedException ex) {
//interrupted
switch (cmd) {
case DO_INPUT:
aProc.setValue(getMessage());
break;
case DO_OUTPUT:
break;
default:
break;
* An interface that has to be implemented by third party procedures
public interface AlgorithmI {
public void calculate();
public int[] getStack();
public void setValue(int message);
//written by someone else which I do not have control over
public class ThirdPartyProcedure implements AlgorithmI {
//just two values that will be added together
private int value1 = 0;
private int value2 = 0;
// an array of commands that will be executed by ProcThread
private int[] stack = {
SyncExample.DO_STORAGE,
SyncExample.DO_INPUT,
SyncExample.DO_STORAGE,
SyncExample.DO_INPUT,
SyncExample.DO_STORAGE,
SyncExample.DO_PROCESS,
SyncExample.DO_STORAGE,
SyncExample.DO_OUTPUT,
SyncExample.DO_QUIT};
public synchronized void setValue(int value) {
if (value1 == 0) {
value1 = value;
} else {
value2 = value;
public void calculate() {
setMessage(value1 + value2);
public int[] getStack() {
return stack;
// continued below...
Edited by: datahpile on Aug 20, 2010 6:27 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

Similar Messages

  • [svn:bz-trunk] 12951: Changed synchronized PropertyProxyRegistry#getRegistry method to non-synchronized to avoid threads blocking in message push .

    Revision: 12951
    Revision: 12951
    Author:   [email protected]
    Date:     2009-12-15 02:17:31 -0800 (Tue, 15 Dec 2009)
    Log Message:
    Changed synchronized PropertyProxyRegistry#getRegistry method to non-synchronized to avoid threads blocking in message push.
    Checkintests: Pass with the usual 3-4 tests that time out with and without this change.
    QA: Yes
    Doc: No
    Modified Paths:
        blazeds/trunk/modules/core/src/flex/messaging/io/PropertyProxyRegistry.java

    Revision: 12951
    Revision: 12951
    Author:   [email protected]
    Date:     2009-12-15 02:17:31 -0800 (Tue, 15 Dec 2009)
    Log Message:
    Changed synchronized PropertyProxyRegistry#getRegistry method to non-synchronized to avoid threads blocking in message push.
    Checkintests: Pass with the usual 3-4 tests that time out with and without this change.
    QA: Yes
    Doc: No
    Modified Paths:
        blazeds/trunk/modules/core/src/flex/messaging/io/PropertyProxyRegistry.java

  • ProcessChain-asynchronous execution fails but synchronous execution pass

    Hello Experts,
    I am having a problem in the execution of our process chains in Prod. When executing thru rspc, Process chain stops at intermediate point & does not execute and status is red. When I execute it synchronously, it passes. Not sure why it is failing when running thru rspc. Looking at the logs in SM37, I only see logs for the non-synchronous executions and the status of the individual steps in PC is canceled and their log shows "Job or process BI_PROCESS_COMPRESS, waiting for event   is unknown" as the error for all steps. What is the difference b/w asynchronous and synchronous execution, and what could be the reason for the above problem. The process chains were running fine until recently.
    Some more info:
    In the rsprocess log, the actual_state has 'J- Framework error upon completion' and the PC runs has meta_api as blank (it was 'X' until recently).
    Thanks.

    Antonio,
    The code has some problem ...
    Change
    if (descriptor = tpacall(service_name,
    (char *)sendbuf,
    sendlen,
    0) == -1)
    To
    if ((descriptor = tpacall(service_name,
    (char *)sendbuf,
    sendlen,
    0) )== -1)
    It should be ok.
    Wayne
    <Antonio Rodriguez> wrote in message news:[email protected]..
    Hi,
    I have a problem with asynchronous messages. When my program calls
    tpacall() this function always returns 0. This is a invalid descriptor to
    tpgetrply() and my program fails. If I use TPGETANY flag then my program
    works well, but I would like to use the descriptor.
    Why tpacall function always returns 0? Can I know when the reply is
    available without calling tpgetrply function? While the reply isn't
    available, my program has to continue its execution. Does tpgetrply function
    block the program execution?
    My Tuxedo version is: BEA Tuxedo, Version 8.0, 32-bit, Patch Level 306
    I find enclosed some program code line
    Thanks,
    ANTONIO.
    int descriptor;
    FBFR32* sendbuf,recvbuf;
    long sendlen,recvlen;
    << call tpinit() >>
    << sendbuf = allocated with tpalloc() >>
    << recvbuf = allocated with tpalloc() >>
    if (descriptor = tpacall(service_name,
    (char *)sendbuf,
    sendlen,
    0) == -1)
    userlog("tpacall() fails");
    return -1;
    if (tpgetrply(&descriptor,
    (char**)&recvbuf,
    (long*)&recvlen
    ,0) == -1)
    userlog("tpacall() fails");
    return -1;
    tpfree(sendbuf);
    tpfree(recvbuf);
    << call tpterm() >>

  • TestStand Execution and Thread Limits?

    Is there a limit to the number of executions and threads that TestStand can support?  If not, what is the "practical" limit of Test Sockets for a modern PC running 64-bit Windows?  I understand this is a pretty broad question that is probably based upon the contents of the sequences along with the PC resources (RAM, CPU).  However, I am curious to find out what would be suggested/experienced.
    I am looking at implementing "monitoring" ten to hundreds of signals on a system in parallel.  The loop rate for each signal read is specified in a configuration file that can change at runtime.  To implement this in TestStand, a sequence in a new thread would be required for each unique loop rate (signal monitor).  This would possibly create hundreds of threads under an execution.
    Any advice would be appreciated!
    Thanks
    CLA, CTA

    There will be a limit... probably when you run out of free memory blocks of a sufficient size. This will vary according to what modules are loaded, what has been allocated and freed at what locations, whether large address awareness is enabled, etc. Your best bet is to test how many TestStand threads you can create in your system within an application that is as close as possible to your desired application and then estimate the reliably obtainable maximum number threads as a fraction of that.

  • Synchronized method in Thread

    Hi All,
    Can u show how to use synchronized method in thread.So that only one thread can access the resource at a time so that other needs to wait.Can u give me a sample example regarding this.So that it will be much more useful.
    Thanx,
    m.ananthu

    synchronized public void method1(){
    // code for the method....
    }Hope it helps.

  • Synchronizing many reader threads with one writer thread?

    Hi
    I was wondering if there is a way in java to allow different threads to read an object simultaneously however to block them all only when the object is being updated. Here is an example:
    I have the following object which is shared between many Servlet instances:
    public class ActiveFlights
         private final HashMap<String,Flight> flights;
         private final Object lock;
         public ActiveFlights()
              flights = new HashMap<String, Flight>();
              lock = new Object();
         public void updateFlights(ArrayList<FlightData> newFlights)
              synchronized (lock)
                   //some code which updates the HashMap
         public ArrayList<Flight> getSomeFlights()
              ArrayList<Flight> wantedFlights = new ArrayList<Flight>();
              synchronized (lock)
                   //some code which selects flights from the HashMap
              return wantedFlights;
    }Now all the Servlet doGet() functions call the getSomeFlights() method. There is also a Timer object which calls the updateFlights() method once every few minutes.
    I need the synchronized blocks in order that the Timer doesn't try to update my object while it is being read by a Servlet however this is not optimal since it also causes each Servlet doGet() to block the others even though it would be possible for to doGet()'s to read the object simultaneously.
    Is there a better way of doing this?
    Thanks
    Aharon

    It is highly unlikely this is a real performance issue for you. Unless you know this is a bottle neck, you don't need to change your code.
    However, as an exercise, you can just use ConcurentHashMap for lockless Map access. However, there is still a risk of getting a read in the middle of a write.
    Instead you can take a snapshot copy of the Map and use this snapshot for reads. See below.
    In term of coding style;
    - I suggest you use the Map and List interfaces where ever possible.
    - You don't need to create a seperate lock object, the Map will do the same job.
    - Use can create the HashMap on the same line as it is declared removing the need to define a constructor.
    public class ActiveFlights {
         private final Map<String, Flight> flights = new HashMap<String, Flight>();
         private volatile Map<String, Flight> flightCopy = new HashMap<String, Flight>();
         public void updateFlights(List<FlightData> newFlights) {
              //some code which updates the HashMap
              // this takes a snapshot copy of the flights.  Use the copy for reads.
              flightCopy = new HashMap<String, Flight>(flights);
         public List<Flight> getSomeFlights() {
              // take a copy of the reference, neither the reference, nor the map it refers to will change over the life of this method call.
              final Map<String, Flight> flightCopy = this.flightCopy;
              final List<Flight> wantedFlights = new ArrayList<Flight>();
              //some code which selects flightCopy from the HashMap
              return wantedFlights;
    }

  • Synchronized methods and thread locking

    Hi can someone please explain the difference between these two examples in the context of object locking
    public void method1(){
        synchronized(this){
    }And
    StringBuffer aStringBufferObject = new StringBuffer("A");
    public void method2(){
        synchronized(aStringBufferObject){
    }I know the first example will obtain a lock on the this instance and the second will obtain a lock of the aStringBufferObject instance. But i dont really understand what the effect or the difference of teh two is.
    For example, in the second example, will threads still be able to execute the code inside the synchronized block because the lock is not related to the 'this' instance?
    I know that synchronizing a method or a block of code prevents multiple threads to access that block/method at the same time but what is the purpose of specifying the object to lock on and what is the difference in the way the object is specified as in teh above examples.
    Thanks
    Edited by: ziggy on Jul 24, 2011 3:23 PM

    Shortly put, the synchronized(object) doesn't lock the object reference in any way. It locks the code inside the synchronized's brackets, so that code can run it only when they have locked object (or in truth, when they have acquired object's monitor).
    Since only one thread at a time can lock an object (obtain an object's monitor), this means that 2 threads executing blocks that synchronize on the same object can't run at the same time, ensuring thread safety (among other things).

  • Pause execution with thread

    What I am trying to do is display a JLabel and then after 5 seconds I wish to hide the label. I have the following code but it does not work???
    label.setText("hi")
    try {Thread.sleep(5000);} catch (InterruptedExecution e){}
    label.setText(null)

    Try this code:import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    public class Test extends JFrame implements ActionListener {
        private int state;
        private String[] texts;
        private JLabel label;
        public Test () {
            state = 0;
            texts = new String[] {
                "1",
                "2"
            label = new JLabel ();
            label.setHorizontalAlignment (SwingConstants.CENTER);
            setLabelText ();
            JButton button = new JButton ("Change the label text in a second");
            button.addActionListener (this);
            getContentPane ().setLayout (new GridLayout (2, 1, 5, 5)); // beautiful GUI
            getContentPane ().add (label);
            getContentPane ().add (button);
            setDefaultCloseOperation (EXIT_ON_CLOSE);
            setTitle ("About changing a label");
            pack ();
            setLocationRelativeTo (null);
            show ();
        private void setLabelText () {
            label.setText (texts[state]);
        public void actionPerformed (ActionEvent event) {
            state = (state + 1) % texts.length;
            new java.util.Timer ().schedule (new TimerTask () {
                public void run () {
                    setLabelText ();
            }, 1000);
        public static void main (String[] parameters) {
            new Test ();
    }Kind regards,
    Levi

  • How to start a thread after the execution/termination of another thread.???

    Hello,
    How to start a thread after the execution/termination of another thread....???
    For example:
    consider two threads: ThreadA and ThreadB
    I could start the ThreadB after the execution of ThreadA.
    How to identify the termination of one thread.....???
    Please help me...
    Thanks & Regards,
    Kayalvizhi

    What do you mean with "it doesn't work"? Do you get a compiler error? Do you get an exception at runtime? What's the error message?
    Jesper

  • Does a reentrant dll call monopolize the calling thread?

    If I understand thing correctly, threading for a dll call is the same as threading for a vi whose execution priority is set to subroutine.
    To review threading in subvis:
    (1) the thread in which a subroutine-execution-priorty-vi call is made is monopolized by the subroutine-execution-priorty-vi since labview cannot time slice the thread.
    (2) if the subroutine-execution-priority-vi is not reentrant, then other threads that call the vi may be suspended because they are competing for the same code resource.
    (3) if the subroutine-execution-priority-vi is reentrant, then other threads may call the vi simultaneously. However, within any particular thread the vi must complete because of point (1).
    In
    sum, the OS timeslices between the threads, and labVIEW timeslices within the threads. If a vi's execution priority is set to subroutine, then the thread under which it is running is monopolized by the vi. Yes?
    A reentrant dll call would be equivalent to a reentrant subvi call in which the subvi's execution priority is set to subroutine. Yes?
    If the above is correct then this should also be correct:
    Using an API call to return the thread ID, you could use the the thread ID at the front and back side of a dll call, as well as in a message library function callable from a dll, to theoretically message labVIEW upon the dll return. The message would be uniquely identifiable because a dll call cannot be superceded by another dll call from within the same thread. Yes?
    I'm not saying that it would be particularly efficient to do so, only that it could be done. And depending on the messaging, it could be a useful option in the dll call configuration dialog box.
    In consider
    ation of "magic",
    Kind Regards,
    Eric

    Eric,
    I'm not sure I understand exactlly what you are trying to do here.
    If you want LV to react to a dll error, why don't you just pass a return
    code that's not zero? Then, back in LV, read the return code. If it's not
    zero, create an error, and pass this to the rest of the code. The rest of
    the code is (or should, following good programming practise) has an error
    in, and the code will not execute if the input error is TRUE. It does not
    even have to be the return code, it could be any input value. The input
    values can be changed in the code, and the modified value is returnd to
    LabVIEW.
    If you want to generate an error, and put it into a buffer to be read later
    on in LV, you'll have to synchronise the code. This is the consequence for a
    construction like this, and is the same for several windows API's
    (GetLastError, etc.). the buffer will stay in memory, untill all instances
    of the dll are released from LV memory.
    BTW: A dll could create another thread. This thread can run on the
    background, like the good old TRS's in dos. (A thread like this could even
    call a LabVIEW VI that is build in a dll, just like any other api.)
    BTW: A thread created by a dll can be made to be automatically released when
    the thread is detatched, or when the process is detached. This is important,
    because LV will crash if the dll is removed from memory, but the thread is
    not stopped properly.
    Regards,
    Wiebe.
    "Eric6756" wrote in message
    news:[email protected]...
    > Greg,
    >
    > As I think I lost you in the point of this line of questions, let me
    > back up.
    >
    > A couple of week ago I asked the following question, "Is there a
    > labVIEW library call that can be made from a dll to tell labVIEW to
    > abort the calling vi thread?" To that question you made the following
    > statement:
    >
    > "... and I doubt that there is a function to do that from a DLL as the
    > DLL could be arbitrarily deep down the stack and the function called
    > would have to magically find the VI that it wants to abort. And don't
    > forget that DLLs can be called by multiple VIs at the same time."
    >
    > You seem to be saying here that what I'm asking for is not possible.
    > And having thought about this for a while, I didn't understand why
    > not.
    >
    > For the moment I'm going to ignore the caveat you just put into the
    > dll calling presumptions I've made and assume the dll is going to
    > execute synchronously within a thread. As the original question
    > suggests, the objective here is to message labVIEW from a dll to
    > provide the same functionallity as a CIN, namely return an error code
    > to labVIEW from a dll.
    >
    > A library function could do this as follows:
    >
    > First, the library function would have two modes; set error, and
    > return error
    >
    > (1) set error:
    >
    > 1.1 get the set error caller thread ID from API
    > 1.2 get the passed in error
    > 1.3 store the error and associated thread ID locally
    >
    > (2) return error
    > 2.1 get return error caller thread ID from API
    > 2.2 locate the error, if any, associated with thread ID
    > 2.3 return the error and clear it locally
    >
    > Now, if a dll encountered an error that it wanted labview to deal
    > with, it would call the error function to set the error code. When
    > the dll call returns control to labVIEW, labVIEW could call the
    > function to return the error. This of course works only if the dll
    > call is synchronous within a thread. Obviously, if the dll releases
    > the thread before it returns, then more than one dll call can be made
    > from the thread and the presumption that an error could be uniquely
    > associated with a thread is itself an error.
    >
    > Having looked at your reply again, I think though your answering a
    > different question than I asked. I just wanted a function to message
    > labVIEW to abort the vi chain, I don't want to abort a vi chain from
    > within the dll. It is a feature of CIN calls which I wanted in dll
    > calls.
    >
    > That a dll call may not be synchronous within a thread throws a wrench
    > in the works. Apparently I've just chased down a dead end.
    >
    > Hey, but thanks for the wrench...
    > Kind Regards,
    > Eric

  • Threading: Sharing same resource (List)

    Hi,
    I'm facing one strange problem.
    What I have done is as follows:
    1. I have created two threads; Thread1 and Thread2. Both these share the same object (List)
    2. Thread1: It add 50 elements to list.
    3. Thread2: It reads 50 elements from the list.
    Expected output is:
    In Thread-2 it might throw ArrayIndexOutofBounds exception because it may try to read the value which Thread1 has not inserted yet.
    Actual output is:
    Yes; It throws the ArrayIndexOutofBounds exception but not due to above expected reason.
    When second time Thread-2 is executed; list size is not updated although Thread1 and
    Thread2 point to same references.
    First I thought that it is due to Thread-1 and Thread-2 have separate stack; but this is
    also not true since list variable is on the heap. And both Thread point to this.
    This is very strange.
    Please find the below code:
    package xyz;
    import java.util.ArrayList;
    import java.util.List;
    public class ThreadTry {
    public static void main(String[] args) {
    List list=new ArrayList<Integer>(50);
    Thread myThread1=new Thread(new Thread1(list));
    Thread myThread2=new Thread(new Thread2(list));
    myThread1.start();
    myThread2.start();
    //writes to list
    class Thread1 implements Runnable{
    List list;
    public Thread1(List list) {
    this.list=list;
    public void run() {
    for(int i=0;i<50;i++){
    System.out.println("{");
    System.out.println(" Start Adding *********************************");
    list.add(i);
    System.out.println(" Thread-1 adding: "+i+" List size is: "+list.size());
    System.out.println(" Adding is done ********************************");
    System.out.println("}");
    System.out.println("");
    //read lists
    class Thread2 implements Runnable{
    List list;
    public Thread2(List list) {
    this.list=list;
    public void run() {
    for(int i=0;i<50;i++){
    System.out.println("------Read : "+i+"-th element.");
    System.out.println("------Thread-2 reading: "+" List size is: "+list.size()+" ; element: "+list.get(i));
    }Regards,
    Leena

    It's perfectly possible that thread2 is being run before thread1, you can't depend on the order of execution between threads.
    To make it safe you need to do something like:
    // in thread 1
    synchronized(list) {
          list.add(i);
          list.notifyAll();
    // in thread 2
    int v = 0;
    synchronized(list) {
       while(i >= list.size()) {  // wait until list has enough entries
            list.wait();
            v = list.get(i);
       };

  • Readers Writers problem and Synchronized doubts

    I made this code for implementing some Lock because I have to permit the write/read action on shared file between different threads. I would like to let more than one thread reading at the same time and just one for the writing
    This is my code, it's in italian but in english the class name would be AccessManager
    import java.io.Serializable;
    public class GestoreAccessi implements Serializable{
    //number of reader
    private int lettori= 0;
    //flag for someone writing
    private boolean scrittura= false;
    //number of writer waiting
    private int scrittoriAttesa = 0;
    private String nome;
    //Il gestore accessi prende un nome
    public GestoreAccessi(String nom) {
    nome = nom;
    //Blocco per la lettura -- Lock for Reading
    public synchronized void lockRead() {
    try {
    //Fino a che c'e' qualcuno in scrittura o processi che aspettano per la scrittura mi metto in attesa -- If ther is some thread writing or waiting for write
    while (scrittura || scrittoriAttesa > 0) {
    wait();
    //Altrimenti aumento la variabile dei thread in lettura -- Add one thread reading
    ++lettori;
    } catch (InterruptedException ex) {
    //Fine del processo di lettura -- Finish reading
    public synchronized void unlockRead() {
    --lettori;
    // solo gli scrittori sono in attesa e uno soltanto deve essere svegliato
    if (lettori == 0) {
    notifyAll();
    //Blocco per la scrittura -- Start Writing
    public synchronized void lockWrite() {
    ++scrittoriAttesa;
    //Fino a che ci sono lettori o qualcuno che scrive aspetto -- if there are readers o someone writing
    while (lettori > 0 || scrittura) {
    try {
    wait();
    } catch (InterruptedException ex) {
    --scrittoriAttesa;
    //Altrimenti inizio il processo di lettura -- Start the process of reading
    scrittura = true;
    //Fine del processo di scrittura
    public synchronized void unlockWrite() {
    scrittura = false;
    notifyAll(); // sblocca uno o piu' lettori o uno scrittore
    Before all critical part I create a GestoreAccessi object and invoce the .lock.. method and finish the critical part the .unlock.. Do you think it's a good way to solve the problem?
    I have some doubts on the multiple reading at the same time. I read on synchronized: "First, it is not possible for two invocations of synchronized methods on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.
    Second, when a synchronized method exits, it automatically establishes a happens-before relationship with any subsequent invocation of a synchronized method for the same object. This guarantees that changes to the state of the object are visible to all threads."
    It's possible to two different thread read at the same time? The .lockRead() method is synchronized: if one thread has acess in a critical part it takes the lock and no other thread would be able to have an access on the same part?! How can i do this? I have not to declare synchronized the read method?
    Please help me and sorry for my bad english!!
    Bless from Italy

    >
    I made this code for implementing some Lock because I have to permit the write/read action on shared file between different threads. I would like to let more than one thread reading at the same time and just one for the writing
    >
    Multiple threads and even applications can read the same file at the same time; it is writing that is problematic.
    There is nothing in what you posted that even shows any 'file' manipulation so no comments can be made about that.
    It looks like you took those quotes from this Java Tutorial Page on Synchronizeds Methods
    http://docs.oracle.com/javase/tutorial/essential/concurrency/syncmeth.html
    Those quotes are accurate as far as synchronizing a particular instance is concerned but that would not prevent some other code from trying to read/write the same file. But again, you code doesn't even include any file-related objects that you are trying to control access to.
    See the Java Tutorial section on 'Lock Objects'
    http://docs.oracle.com/javase/tutorial/essential/concurrency/newlocks.html

  • Is ThreadPoolExecutor.execute(Runnable) thread-safe?

    Is ThreadPoolExecutor.execute(Runnable) thread-safe, i.e. is it safe
    to invoke this method from multiple threads without making any
    special arrangements to ensure that not more than one thread is
    in the execute() method of the ThreadPoolExecutor object at the same time
    (such as synchronizing on the ThreadPoolExecutor object)?
    I can find nothing in the Java 6 documentation to say it is thread-safe
    (Executor, ExecutorService, ThreadPoolExecutor and package documentation).
    Note that I am not asking anything about the actual execution of the Runnables.
    I am asking about the act of inserting the Runnables into the thread pool.

    Thanks to everyone who replied.
    The three example implementations in the interface documentation for Executor, including the one where the Runnable is executed by the invoking thread, are thread-safe but only the last one needs to do anything special (namely make the execute(...) method synchronized) to be thread-safe. It is not clear whether the thread-safety of the first two implementations is conscious or accidental. Even if conscious that would not imply that it is necessary.
    I think the published documentation (unless I've missed something) is deficient. The method would not be useless if not thread-safe. I don't think thread-safety is a safe default assumption. I think a package that supports concurrent programming should be clear on where it is thread-safe.
    I've had a quick look at the source code in the 1.6 JDK implementation. It makes a serious and plausible effort to be thread-safe. It was written by Doug Lea.
    I'm going to assume the method is thread-safe, based on looking at the source code.

  • Problems with synchronizing an element in an array

    I have a class that extends ArrayList. I have another class called "Elem" that works as elements for the ArrayList. Multiple threads will work on this list.
    When I get an element from the ArrayList I would like to lock only this element so another thread can delete other elements in the list.
    I have made this method for getting and locking an element:
         public String get(int id)
              String res ="No such file, try command list";
              int size = this.size();
              for (int i = 0; i<size;i++)
                   Elem ifo = (Elem)this.get(i);
                   if(ifo.getId() == id)
                        synchronized(ifo)
                             try {
                                  Thread.sleep(4000);
                             } catch (InterruptedException e) {
                                  e.printStackTrace();
                             res = ifo.getData() + " Received";
                        break;
              return res;
         }I have made the operation last for 4 seconds because I test if the object is locked with the follwing delete method:
         public synchronized String del(int id)
              String res =" no file";
              int size = this.size();
              for (int i = 0; i<size;i++)
                   Elem ifo = (Elem)this.get(i);
                   if(ifo.getId() == id)
                        super.remove(ifo);
                        res = ifo.getId() + " deleted!";
                        break;
              return res;
         }But when I run the program and start reading an element that I try to delete at the same time it gets deleted! Why does the "del" method not block until the element has been read?

    Ok here is what I am trying to do.
    1) Thread 1 get an element from list A. At the SAME
    time thread 2 deletes a different element from list
    A.Everything I've said still applies. What do you mean "at the SAME time"? And why does it have to be "at the SAME time"? What if whatever triggers cause the two actions happen "at the SAME time," but the actual actions happen a millisecond apart?
    currently only serial execution works, since all the
    methods on the list are synchronized.Again, anytime you're accessing shared data from multiple threads, you must synchronize. That syncing may be very, very brief--say just to atomically update a counter or "available" bitmap or something, but if there's shared data--such as a bitmap that keeps track of which slots are used--read/updates, like "find an available one, mark it used, and give me its index"--must be atomic, so there must be some synchronization.
    Or else different threads get different sections of the array assigned to them.

  • Thread not running ?

    hi everyone :)
    im trying to make a multithreaded producer / consumer with stack as a shared recourse.
    the below code compiles fine ( in JCreator ), but when i run it i get "press any key to continue..." instead of the expected "pushed" "popped"......
    does anyone have an idea what it wrong.... im lost :)
    thanks in advance
    class Buffer {
         private final int MAX_BUFFER_SIZE = 16;
         private int buffer[] = new int[ MAX_BUFFER_SIZE ];
         private int no_in_buffer=0;
         public void push( int i ) {
              try {
                   if( no_in_buffer == MAX_BUFFER_SIZE ) {
                        throw (new Exception("ErrorBufferFull"));
                   } else {
                        System.out.println( "Pushed" );
                        buffer[no_in_buffer++] = i;
              } catch( Exception e ) {
                        System.err.println(e.getMessage());
                        e.printStackTrace();
         public int pop() {
              try {
                   if( no_in_buffer == 0 ) {
                        throw (new Exception("ErrorBufferEmpty"));
                   } else {
                        System.out.println( "Popped" );
                        return buffer[no_in_buffer--];
              } catch( Exception e ) {
                        System.err.println(e.getMessage());
                        e.printStackTrace();
                        return 0;
    class Consumer implements Runnable {
         protected Thread execution;
         private Buffer buffer;
         public Consumer( Buffer r ) {
              buffer = r;     
         public synchronized void begin() {
              if(execution == null ) {
                   System.out.println( "Consumer begin() called" );
                   execution = new Thread( this );
                   execution.setPriority( Thread.MIN_PRIORITY );
                   execution.start();     
         public synchronized void end() {
              if( execution != null ) {
                   execution.interrupt();
                   execution = null;     
         public void run() {
              try {
                   Thread myself = Thread.currentThread();
                   while( execution == myself ) {
                        System.out.println( "Consumer running" );
                        buffer.pop();
              } finally {
                   synchronized( this ) {
                        execution = null;     
    class Producer implements Runnable {
         protected Thread execution;
         private Buffer buffer;
         public Producer( Buffer r ) {
              buffer = r;     
         public synchronized void begin() {
              if(execution == null ) {
                   System.out.println( "Producer begin() called" );
                   execution = new Thread( this );
                   execution.setPriority( Thread.MIN_PRIORITY );
                   execution.start();     
         public synchronized void end() {
              if( execution != null ) {
                   execution.interrupt();
                   execution = null;     
         public void run() {
              try {
                   Thread myself = Thread.currentThread();
                   while( execution == myself ) {
                        System.out.println( "Producer running" );
                        buffer.push( (int) Math.random() % 10 );
              } finally {
                   synchronized( this ) {
                        execution = null;     
    class App {
         public static void main( String args[] ) {
              Buffer r = new Buffer();
              Producer p = new Producer( r );
              Consumer c = new Consumer( r );
              p.run();
              c.run();

    You should start your threads using start () instead of run ().
    Kind regards,
    Levi

Maybe you are looking for