comp.lang.java.programmer
http://groups-beta.google.com/group/comp.lang.java.programmer
[EMAIL PROTECTED]

Today's topics:

* Ejb: best way to implement an update method with BMP - 2 messages, 2 authors
 
http://groups-beta.google.com/group/comp.lang.java.programmer/browse_thread/thread/2fadf7c755facb41
* Document Management System - 1 messages, 1 author
 
http://groups-beta.google.com/group/comp.lang.java.programmer/browse_thread/thread/ea79341ea412d566
* best pratices in Exception Handling - 1 messages, 1 author
 
http://groups-beta.google.com/group/comp.lang.java.programmer/browse_thread/thread/b7f7ffa192845fec
* Java beats them all - 4 messages, 2 authors
 
http://groups-beta.google.com/group/comp.lang.java.programmer/browse_thread/thread/519011440b614d43
* POPL 2005 Call for Participation - 1 messages, 1 author
 
http://groups-beta.google.com/group/comp.lang.java.programmer/browse_thread/thread/e8a58634397fe7b4
* how to response to user's mouse click on JTabbedPane's tabTitle? - 2 
messages, 2 authors
 
http://groups-beta.google.com/group/comp.lang.java.programmer/browse_thread/thread/c7846fed0be53d2a
* Correct Semaphore Implementation in Java - 5 messages, 4 authors
 
http://groups-beta.google.com/group/comp.lang.java.programmer/browse_thread/thread/8259aec1ceed4f8f
* choosing random item from set with weighted probability - 3 messages, 3 
authors
 
http://groups-beta.google.com/group/comp.lang.java.programmer/browse_thread/thread/da98e83f7a2c858b
* Ant vs Makefiles - 1 messages, 1 author
 
http://groups-beta.google.com/group/comp.lang.java.programmer/browse_thread/thread/e81556a5c62ba767
* How do you do this? - 2 messages, 2 authors
 
http://groups-beta.google.com/group/comp.lang.java.programmer/browse_thread/thread/f653c0cceabd25b4
* Best way to do this - 1 messages, 1 author
 
http://groups-beta.google.com/group/comp.lang.java.programmer/browse_thread/thread/8e38d69ac964c0ee
* Finding raw types in 1.5 - 1 messages, 1 author
 
http://groups-beta.google.com/group/comp.lang.java.programmer/browse_thread/thread/cbe0331906e9f613
* Advanced question about generics - 1 messages, 1 author
 
http://groups-beta.google.com/group/comp.lang.java.programmer/browse_thread/thread/70947db3058ccce1

==============================================================================
TOPIC: Ejb: best way to implement an update method with BMP
http://groups-beta.google.com/group/comp.lang.java.programmer/browse_thread/thread/2fadf7c755facb41
==============================================================================

== 1 of 2 ==
Date: Fri, Nov 26 2004 6:39 pm
From: Andrea Desole  

Sudsy wrote:
> Andrea Desole wrote:
> 
>> I want to write my first update method for an EJB using BMP. My 
>> favourite solution would be:
>>
>> bean.setA();
>> bean.setB();
>> bean.update();
>>
>> The problem is that an update can only be made in the ejbStore method, 
>> which is called at the end of a method configured to be used with a 
>> transaction, in this case bean.update(). But, even if I use a 
>> transaction with update, I will then have a call to ejbLoad when I 
>> start it, which basically means that my new values for A and B will be 
>> overwritten with the old ones. I think there are mainly two 
>> possibilities:
> 
> <snip>
> 
> I suggest a careful reread of the documentation. The container will
> "bracket" your method calls (setA, setB) with calls to ejbLoad and
> ejbStore. You need to understand your BMP entity bean's responsibilities.
> A good book (with examples) is "Enterprise JavaBeans Component
> Architecture" published by Sun Microsystems Press, ISBN 0-13-035571-2.
> I would expect that you could also find a good tutorial on Sun's web
> site. In fact, typing "+bmp +tutorial" into the search string box at
> <http://java.sun.com> provides the following:
> <http://java.sun.com/developer/onlineTraining/J2EE/Intro2/jdbc_bmp/jdbc_bmp.html>
>  
> 
> Pay particular attention to the bean lifecycle.
> 
I looked at it, but that should happen usually if the method has a 
transaction associated. At least, that's what I understand from the J2EE 
1.4 tutorial, (page 936), and from the book "Enterprise Javabeans", 
pages 250-251. From this documentation, and from the specification, I 
also understand that the container can call these methods whenever it is 
considered necessary.
Not every method has to have a transaction. So, if I configure my 
transaction properly in the ejb-jar file, there should be no need to 
call ejbStore from my setters, and it will be called only in update.
Right?



== 2 of 2 ==
Date: Fri, Nov 26 2004 1:08 pm
From: Sudsy  

Andrea Desole wrote:
<snip>
> I looked at it, but that should happen usually if the method has a 
> transaction associated. At least, that's what I understand from the J2EE 
> 1.4 tutorial, (page 936), and from the book "Enterprise Javabeans", 
> pages 250-251. From this documentation, and from the specification, I 
> also understand that the container can call these methods whenever it is 
> considered necessary.
> Not every method has to have a transaction. So, if I configure my 
> transaction properly in the ejb-jar file, there should be no need to 
> call ejbStore from my setters, and it will be called only in update.
> Right?

 From the book I mentioned earlier:
"All business methods, even if they only perform a data lookup, /must/
execute within a transaction in order for the EJB container to ensure
data integrity between the in-memory entity bean and the database."
(pp. 212, emphasis mine)

-- 
Java/J2EE/JSP/Struts/Tiles/C/UNIX consulting and remote development.





==============================================================================
TOPIC: Document Management System
http://groups-beta.google.com/group/comp.lang.java.programmer/browse_thread/thread/ea79341ea412d566
==============================================================================

== 1 of 1 ==
Date: Fri, Nov 26 2004 5:51 pm
From: "Ike"  

Does anyone know of any Document Management Sytems projects out there where
there may be code available to study how such a thing is structured? Thanks,
Ike






==============================================================================
TOPIC: best pratices in Exception Handling
http://groups-beta.google.com/group/comp.lang.java.programmer/browse_thread/thread/b7f7ffa192845fec
==============================================================================

== 1 of 1 ==
Date: Fri, Nov 26 2004 10:52 am
From: Chris Smith  

 <[EMAIL PROTECTED]> wrote:
> I am a rookie Java developer.
> I am looking for a guide on design and architecture in Exception
> generation and handling.
> 
> I have found a lot of tutorial on the syntax, but not one on how to
> actually design a sensible Exception handling.

For some general concepts, head over to www.ppjdg.org, click "Java 
Essentials" in the left margin, and then "Exception Handling Practices" 
from the resulting list.  That's the slide piece to a 30-minute 
presentation I prepared about a year ago on the topic.

I think you're making a mistake, though, in looking for architectural 
advice regarding exception handling.  The mechanism is already there.  
All you need to do is be sure that you're throwing and catching the 
right exceptions at the right times.  If you try to architect your 
exception handling in the common sense of that word, you're going to 
create unneeded complexity and make it harder for others to approach 
your code.

-- 
www.designacourse.com
The Easiest Way To Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation




==============================================================================
TOPIC: Java beats them all
http://groups-beta.google.com/group/comp.lang.java.programmer/browse_thread/thread/519011440b614d43
==============================================================================

== 1 of 4 ==
Date: Fri, Nov 26 2004 5:57 pm
From: John Bailo  

John Bailo wrote:

> Jeff_Relf wrote:
>  
>> No, mark the time  Before  you create the threads,
>> let the threads run right away  ( not suspended )
>> but have them what for a global int to be set to 1 before they terminate,
>> ...i.e. have them do a  Sleep( 0 )  while the global is not 1.
> 
> Ok, here's my c# mono version.

And here's the java version.

As before, once the threads are started ( and I watched it in the eclipse
debugger, where I can see all 2000 threads being started ).

Shut down takes less than a millesecond!

18
523
18
523

Here's the code:

/*
 * Created on Nov 25, 2004
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */

/**
 * @author jbailo
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */


public class SimpleThread extends Thread {

        public SimpleThread(String str) {
                super(str);
        }
                
        public void run() {     
                //for(int i = 0; i < 10; i++) {
                //System.out.println(getName());
                
                while(!TwoThreadsDemo.Run)
                try{
                        sleep((long)(0));
                } catch(Exception e) {}
                
                TwoThreadsDemo.counter++;
        }
                
}




/*
 * Created on Nov 25, 2004
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */

/**
 * @author jbailo
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */


import java.util.*;

public class TwoThreadsDemo {
        
        public static boolean Run = false;
        public static int counter = 0;

        public static void main(String[] args) {
                
                
                Calendar cal = new GregorianCalendar();

                 //int time = sec*1000+ms;
                

                 
                 
                
                for (int i = 0; i < 2000; i++)
                        new SimpleThread("#" + i).start();
                
                
                
                 int sec = cal.get(Calendar.SECOND);             // 0..59
                 int ms = cal.get(Calendar.MILLISECOND);         // 0..999
                 
                 System.out.println(sec);
                 System.out.println(ms);

                 Run = true;            
                 
                while(counter<1000)
                {}
                 
                 sec = cal.get(Calendar.SECOND);             // 0..59
                 ms = cal.get(Calendar.MILLISECOND);         // 0..999
                 System.out.println(sec);
                 System.out.println(ms);
                
                //System.out.println("Time is" + time);
                
        }
}

//







> 
> The run times so far produced:
> 
> 1 - 1.2s
> 
> BUT -- .NET seems to tank at about 1100 threads.
> 
> So my test only uses 1000 threads.
> 
> Next up -- java !
> 
> 
> using System;
> using System.Threading;
> using System.IO;
> using System.Diagnostics;
> 
> namespace threadtest {
> 
> internal class ThreadClass
> {
>  public void Performjob()
>  {
> 
>   while(!Mainclass.Run)
>         Thread.Sleep(0);
>   
>   Mainclass.TC++;
>   
> }
> 
> public class Mainclass
> {
> 
> public static bool Run = false;
> public static int TC = 0;
> 
> 
>  public static int Main (string[] args)
>  {
>   
>   ThreadClass j = new ThreadClass();
>         try{
> 
>                 for(int i=0; i<1000; i++)
>                 {
>                         Thread backgroundThread =
>                                         new Thread(new
>                                         ThreadStart(j.Performjob));
>                                         backgroundThread.Start();
>                 }
>                 } catch ( Exception e )
>                 {
>                         Console.WriteLine( "Error: " + e.ToString());
>                 }
>   
>                 int intsec =
>                 DateTime.Now.Second*1000+DateTime.Now.Millisecond;
>    
>                 Run = true;
>   
>         while(TC<1000)
>                 Thread.Sleep(0);
>   
>         intsec = DateTime.Now.Second*1000+DateTime.Now.Millisecond -
>         intsec;
>                 Console.WriteLine("end main, intsec {0}", intsec);
>   
>         return 0;
>  }
> }
> }
> 
> 
> 
> 
> 
>> 
>> Set the global to 1 and then wait on the 2,000 terminations.
>> After the last thread has terminated,
>> mark the time and note the difference.
> 

-- 
http://www.texeme.com




== 2 of 4 ==
Date: Fri, Nov 26 2004 6:20 pm
From: Jeff_Relf  


Hi  John, your:  while( counter < 1000 ) {}
is not equivalent to my:
  pH = TH - 1 ;  Loop ( _2000 ) WaitForSingleObject( * ++ pH, INFINITE );
  
Ray did it right  ( using C, but not 2.6 ), and it was 1.8 times slower.

By the way, Why all the blank lines... geez.

Re: <<
  for (int i = 0; i < 2000; i++)
    new SimpleThread("#" + i).start();  >>

Does that really spawn the threads, 
...weren't you just watching the constructor in the debugger ?




== 3 of 4 ==
Date: Fri, Nov 26 2004 6:27 pm
From: John Bailo  

Jeff_Relf wrote:

> Does that really spawn the threads,
> ...weren't you just watching the constructor in the debugger ?

No, Eclipse actually shows the threads being created.

Here's a screenshot:

http://home.earthlink.net/~jabailo/imgs/eclipsethreads.jpg



-- 
http://www.texeme.com




== 4 of 4 ==
Date: Fri, Nov 26 2004 9:16 pm
From: Jeff_Relf  


Hi John,  You told me: <<  Sorry, Jeffie, Only The Best Languages  ( Java )
  Get to Launch 2000 Threads Fast  >>
  
No, C++ on the 2.6 Linux kernel would be at least as fast, if not more.

And I noticed that you couldn't do it in C#.
  
And showing zero milliseconds is not too cool I think,
I'd either increase the precision or, better yet, try 100,000 threads.





==============================================================================
TOPIC: POPL 2005 Call for Participation
http://groups-beta.google.com/group/comp.lang.java.programmer/browse_thread/thread/e8a58634397fe7b4
==============================================================================

== 1 of 1 ==
Date: Fri, Nov 26 2004 10:28 am
From: [EMAIL PROTECTED] (David Walker) 

POPL 2005 Call for Participation

32nd Annual ACM SIGPLAN - SIGACT 
Symposium on Principles of Programming Languages 

Long Beach, California
January 12-14, 2005
http://www.cs.princeton.edu/~dpw/popl/05/

Scope of the Conference

The annual Symposium on Principles of Programming Languages is a forum
for the discussion of fundamental principles and important innovations
in the design, definition, analysis, transformation, implementation
and verification of programming languages, programming systems, and
programming abstractions.

Important Dates

* Hotel reservation deadline:  December 21, 2004 
* Reduced fees deadline:  December 30, 2004 (11:59 PM, EST USA) 
  - Register at http://www.regmaster.com/popl2005.html 
* Main conference:  January 12-14, 2005.
* Affiliated events:  January 10-11 and January 15, 2005

Invited Speakers

* Pat Hanrahan (Stanford University)
* Rob Pike (Google):  Interpreting the Data
* Peter Selinger (University of Ottawa):  Programming Languages for
Quantum Computing

Location & Hotel

The POPL 2005 conference site is Hyatt Regency Long Beach, 200 South
Pine Avenue, Long Beach, CA.  Complete information concerning how  to
book rooms and travel to Long Beach may be found at the conference web
site (http://www.cs.princeton.edu/~dpw/popl/05/).  The Hyatt Regency
is right next to a variety of entertainment areas, including the
Shoreline Village, the Rainbow Harbor, and the Shoreline Marina, which
offer sport fishing, boat rentals, personal boat rentals, shopping,
great food and other diversions.  For those wishing to take in some
sun this January, one can walk east from the hotel, about a 1/4 mile,
along the Shoreline Marina, to a large, sandy, public beach. In
addition, the remarkable Aquarium of the Pacific, which houses more
than 12,500 animals and offers the possibility of coming face-to-face
or even touching the world's greatest predators, is only a 1/4 mile
west.  On Thursday January 13th, we will be having a tour and banquet
on the Queen Mary ocean liner.  Be sure to reserve your room by
December 21st, 2004 and register for the conference by December 30th,
2004.

Program

Wednesday, Jan 12

8:30AM -- 9:30AM: Invited talk: Interpreting the Data, Rob Pike
(Google)

10AM Session:

* Associated Types with Class 
  - Manuel Chakravarty, Gabriele Keller, Simon Peyton-Jones, Simon
Marlow
* Environmental Acquisition Revisited 
  - Richard Cobbe, Matthias Felleisen 
* Polymorphic Bytecode: Compositional Compilation for Java-like
Languages 
  - Davide Ancona, Ferrucio Damiani, Sophia Drossopoulou, Elena Zucca 
* A Simple Typed Intermediate Language for Object-Oriented Languages 
  - Juan Chen, David Tarditi
 
1:30PM Session:

* Parametric Polymorphism for XML 
  - Haruo Hosoya, Alain Frisch, Giuseppe Castagna 
* A Bisimulation for Type Abstraction and Recursion 
  - Eijiro Sumii, Benjamin Pierce 
* A Syntactic Approach to Eta Equality in Type Theory 
  - Healfdene Goguen 
* Slot Games: A Quantitative Model of Computation 
  - Dan Ghica 

4PM Session:

* Synthesis of Interface Specifications for Java Classes 
  - Rajeev Alur, Pavol Cerny, P. Madhusudan, Wonhong Nam 
* Dynamic Partial-Order Reduction for Model Checking Software 
  - Cormac Flanagan, Patrice Godefroid 
* Proof-Guided Underapproximation-Widening for Multi-Process Systems 
  - Orna Grumberg, Flavio Lerda, Ofer Strichman, Michael Theobald 
* Transition Predicate Abstraction and Fair Termination 
  - Andreas Podelski, Andrey Rybalchenko 

6PM: Business meeting / PC report

Thursday, Jan 13

8:30AM: Invited talk:  Programming Languages for Quantum Computing,
Peter Selinger (University of Ottawa)

10AM Session:

* Communicating Quantum Processes 
  - Simon Gay, Rajagopal Nagarajan 
* Downgrading Policies and Relaxed Noninterference 
  - Peng Li, Steve Zdancewic 
* A Probabilistic Language Based Upon Sampling Functions 
  - Sungwoo Park, Frank Pfenning, Sebastian Thrun 
* Mutatis Mutandis: Safe and Predictable Dynamic Software Updating 
  - Gareth Stoyle, Michael Hicks, Gavin Bierman, Peter Sewell, Iulian
Neamtiu

1:30PM Session:

* Transactors: A Programming Model for Maintaining Globally Consistent
Distributed State in Unreliable Environments
  - John Field, Carlos Varela 
* Theoretical Foundations for Compensations in Flow Composition
Languages
  - Roberto Bruni, Hernan Melgratti, Ugo Montanari 
* From Sequential Programs to Multi-Tier Applications by Program
Transformation
  - Matthias Neubauer, Peter Thiemann 
* Combinators for Bi-Directional Tree Transformations: A Linguistic
Approach to the View Update Problem
  - Nathan Foster, Michael Greenwald, Jonathan Moore, Benjamin Pierce,
Alan Schmitt

4:30PM:  Tour and conference dinner on the Queen Mary ocean liner

Friday, Jan 14

8:30AM: Invited talk, Pat Hanrahan (Stanford University)

10AM Session:

* Separation Logic and Abstraction 
  - Matthew Parkinson, Gavin Bierman 
* Permission Accounting in Separation Logic 
  - Richard Bornat, Cristiano Calcagno, Peter O'Hearn, Matthew
Parkinson
* Context Logic and Tree Update 
  - Cristiano Calcagno, Philippa Gardner, Uri Zarfaty 
* Connecting Effects and Uniqueness with Adoption 
  - John Tang Boyland, William Retert 

1:30PM Session:

* A Semantics for Procedure-Local Heaps and its Abstractions 
  - Noam Rinetzky, Jörg Bauer, Thomas Reps, Mooly Sagiv, Reinhard
Wilhelm
* Region-Based Shape Analysis with Tracked Locations 
  - Brian Hackett, Radu Rugina 
* Precise Interprocedural Analysis using Random Interpretation 
  - Sumit Gulwani, George Necula 
* Numeric Analysis of Array Operations 
  - Denis Gopan, Thomas Reps, Mooly Sagiv 

4PM Session:

* Scalable Error Detection using Boolean Satisfiability 
  - Yichen Xie, Alex Aiken 
* Automated Soundness Proofs for Dataflow Analyses and Transformations
via Local Rules
  - Sorin Lerner, Todd Millstein, Erika Rice, Craig Chambers 
* The Java Memory Model 
  - Jeremy Manson, William Pugh, Sarita Adve 

Program Chair:

Martín Abadi
University of California, Santa Cruz
Computer Science Department
Santa Cruz, CA 95064
E-mail: [EMAIL PROTECTED]


General Chair:

Jens Palsberg
University of California, Los Angeles
Computer Science Dept, 
4531K Boelter Hall, 
Los Angeles, CA 90095
Phone: 310-825-6320 
Fax: 310-794-5057
E-mail: [EMAIL PROTECTED]
Program Committee:

Martín Abadi, UC Santa Cruz (chair)
Rastislav Bodik, UC Berkeley
Perry Cheng, IBM (T.J. Watson Research Center)
William Cook, UT Austin
Michael Ernst, MIT
Giorgio Ghelli, Università di Pisa
Yossi Gil, Technion
Ralf Hinze, Universität Bonn
Martin Hofmann, Ludwig-Maximilians-Universität München
Alan Jeffrey, Bell Labs, Lucent / DePaul University
Andrew Kennedy, Microsoft Research (Cambridge)
Naoki Kobayashi, Tohoku University
Julia Lawall, University of Copenhagen
Andrew Myers, Cornell University
Gordon Plotkin, University of Edinburgh
François Pottier, INRIA (Rocquencourt)
Sriram Rajamani, Microsoft Research (Redmond)
John Reppy, University of Chicago
Zhong Shao, Yale University
Henny Sipma, Stanford University 

Treasurer:

Manuel Fähndrich

Publicity:

David Walker




==============================================================================
TOPIC: how to response to user's mouse click on JTabbedPane's tabTitle?
http://groups-beta.google.com/group/comp.lang.java.programmer/browse_thread/thread/c7846fed0be53d2a
==============================================================================

== 1 of 2 ==
Date: Fri, Nov 26 2004 6:35 pm
From: Chas Douglass  

Kleopatra <[EMAIL PROTECTED]> wrote in
news:[EMAIL PROTECTED]: 

[ship]
> allow me two comments on your code:
> 
> a) the "type" prefixes (forgot - how are they called, it's been too
> long ago <g>) are unusual in java.
[snip]

"Hungarian" notation.

/me shudders

Chas Douglass





== 2 of 2 ==
Date: Fri, Nov 26 2004 8:11 pm
From: Grant Wagner  

Chas Douglass wrote:

> Kleopatra <[EMAIL PROTECTED]> wrote in
> news:[EMAIL PROTECTED]:
>
> [ship]
> > allow me two comments on your code:
> >
> > a) the "type" prefixes (forgot - how are they called, it's been too
> > long ago <g>) are unusual in java.
> [snip]
>
> "Hungarian" notation.
>
> /me shudders

He used one type of "Hungarian" notation, one a lot of developers
disagree with:

<url: http://blogs.msdn.com/ericlippert/archive/2003/09/12/52989.aspx />
"What Simonyi is saying here is that the point of Hungarian Notation is
to extend the concept of "type" to encompass semantic information in
addition to storage representation information."

<url: http://blogs.msdn.com/larryosterman/archive/2004/06/22/162629.aspx
/>
"The bottom line is that when you’re criticizing Hungarian, you need to
understand which Hungarian you’re really complaining about.  Hungarian as
defined by Simonyi isn’t nearly as bad as some have made it out to be."

<url: http://blogs.msdn.com/rick_schaut/archive/2004/02/14/73108.aspx />
"You see, there are really two distinct naming conventions known as
Hungarian Notation. I like to refer to them as Hungarian Notation and
Anti-Hungarian Notation."

<url: http://blogs.msdn.com/ericlippert/archive/2003/09/16/53015.aspx />
"If you're going to uglify your code with Hungarian Notation, please, at
least do it right.  The whole point is to make the code easier to read
and reason about, and that means ensuring that the invariants expressed
by the Hungarian prefixes and suffixes are actually invariant...In other
words, the name of a variable should reflect its meaning throughout its
lifetime, not merely its initialization."

I don't use Hungarian notation, but if I am going to disagree with the
use of a particular syntax style, I figure I should understand what I am
disagreeing with.

--
Grant Wagner <[EMAIL PROTECTED]>





==============================================================================
TOPIC: Correct Semaphore Implementation in Java
http://groups-beta.google.com/group/comp.lang.java.programmer/browse_thread/thread/8259aec1ceed4f8f
==============================================================================

== 1 of 5 ==
Date: Fri, Nov 26 2004 6:44 pm
From: [EMAIL PROTECTED] 

In article <[EMAIL PROTECTED]>,
Andrea Desole  <[EMAIL PROTECTED]> wrote:
>I wouldn't say it's correct. There are two things that don't convince me:
>1) a thread shouldn't be able to call V without calling P. You can't 
>release a resource if you don't get it

Well ....  But semaphores are a rather general synchronization
mechanism that can be used for things other than "acquire a resource
/ release the resource."  An example is a producer/consumer setup,
where you have one thread "producing" things and putting them in a
shared buffer, and another thread "consuming" them.  A reasonable way
to make the consumer wait if there is nothing to consume is by using
a semaphore, with the producer doing "V" operations and the consumer
doing "P" operations.

>2) notify is not deterministic. It would be better to have a FIFO queue, 
>or there is a chance, altough small, that a thread will wait forever
>I also know that some JVMs don't work as they should, and in some cases 
>a waiting thread can wake up without notify being called.
>There are probably a lot of resources on the web about this

A JVM that allows "wait" to complete without a corresponding "notify"
would be broken, no?  Can anyone point to evidence that these exist?
Just curious.

[ snip ]

-- 
| B. L. Massingill
| ObDisclaimer:  I don't speak for my employers; they return the favor.



== 2 of 5 ==
Date: Fri, Nov 26 2004 6:49 pm
From: "xarax"  

"Andrea Desole" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
>
> >
> > The problem is not related to spurious wake-ups. The code
> > in the procure method P() was broken, because it only used
> > "if(count==0)" rather than "while(count==0)". The code poster
> > asserted a fallacy about the efficacy of the implementation,
> > that it was impossible to return from the "wait()" without
> > being immediately able to take ownership of the semaphore.
> >
> > The while loop is required not due to spurious wake-ups,
> > but rather due to the fact that "wait()" releases the monitor
> > and then tries to re-acquire the monitor before returning to
> > the code that called wait(). A timing issue arises when two
> > or more threads concurrently attempting P() which will cause
> > the broken code to proceed with two threads holding the
> > semaphore. The while loop fixes that bug.
> >
>
> the code is synchronized, I don't see any problem with more threads
> accessing P, except the lack of a FIFO queue. Can you be clearer? I'm
> not sure I get this.

The code is not always synchronized, because wait() releases
the monitor. When notify() is called, the target thread becomes
dispatchable and it must compete with other threads to re-acquire
the monitor before returning from wait(). There may be another
thread already suspended at the outer synchronized block that
will get the monitor *after* the V() method exits and *before*
the wait() returns.

IIRC, the original posted Semaphore class is something
like this (please advise if there is any substantive
difference between this and the original code):
=====================================
public class Semaphore
{
    private int count = 1;

    public void procure()
    throws InterruptedException
    {
        synchronized(this)
        {
            if(count == 0) /* Should be while(count==0) */
            {
                /* releases the monitor, then re-acquires later */
                wait();
            }
            count--;
        }
    }

    public void vacate()
    {
        synchronized(this)
        {
            if(count == 0)
            {
                notify();
            }
            count++;
        }
    }
}
=====================================

The design starts the semaphore.count field
at 1, which means that the semaphore is available.
Acquiring the semaphore changes the count to 0.
Releasing the semaphore changes the count to 1.

btw: I factored out the InterruptedException to
get rid of the recovery path. It's not relevant
to this discussion.

Now assume there are 3 threads, A, B, and C. Thread
A calls procure(), and the other threads are doing
something else so there is no contention for the
semaphore.

Thread A has acquired the semaphore and returned
from procure(). Now thread B calls procure(), which
acquires the monitor, checks for if(count==0) and sees
that another thread has already acquired the semaphore.
So, thread B calls wait(), which releases the monitor.

Now thread A calls vacate(), which acquires the
monitor. Then thread C calls procure(), which attempts
to acquire the monitor, but is blocked because thread
A already has the monitor. Meanwhile, thread B is still
waiting inside wait().

Thread A calls notify() which awakens thread B. Thread
B now attempts to re-acquire the monitor. Thread C is
still trying to acquire the monitor. Both thread B
and thread C are now competing for the monitor.

When thread A exits the vacate() method, the monitor
is released and it is unpredictable whether thread B
or thread C will acquire the monitor. If thread B
acquires the monitor, then all is well. However, if
thread C acquires the monitor, then it will see that
(count != 0) and it will proceed to change "count"
to 0, so that it will own the semaphore.

When thread C exits procure(), the monitor is released
and now thread B can acquire the monitor and return
from wait(). Since procure() does not loop back to
re-test the value of count (which is 0), thread B will
proceed to assume that it has acquired the semaphore
(thread C actually has acquired the semaphore). Thus,
both thread B and C will return from procure(), with
each thread believing that it has acquired the semaphore.

Both threads, believing they each have acquired the
mutex semaphore, will now enter their critical sections
and clobber each other.

In actual practice, the semaphore paradigm is much
more complicated, and is properly synchronized to avoid
the race condition described above. The above sample
Semaphore class is woefully broken to handle either
exclusive or shared semaphores.

Hope this helps.

-- 
----------------------------
Jeffrey D. Smith
Farsight Systems Corporation
24 BURLINGTON DRIVE
LONGMONT, CO 80501-6906
http://www.farsight-systems.com
z/Debug debugs your Systems/C programs running on IBM z/OS for FREE!





== 3 of 5 ==
Date: Fri, Nov 26 2004 9:01 pm
From: "Ann"  


"Frank Gerlach" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> There seem to be quite a number of not very clean and simple
> implementations
> of java Semaphores in the internet. The following example is extremely
> simple (the Java 1.5 implementation is overfeatured IMHO) and correct:

I guess it is fine to re-invent things if you have a lot of time
on your hands. Is there any practical application for your thing
that can't be achieved with normal methods?





== 4 of 5 ==
Date: Fri, Nov 26 2004 2:07 pm
From: Chris Smith  

 <[EMAIL PROTECTED]> wrote:
> A JVM that allows "wait" to complete without a corresponding "notify"
> would be broken, no?  Can anyone point to evidence that these exist?
> Just curious.

No, it would absolutely not be broken.  Recent versions of the API 
documentation even explicitly state that spurious wakeups are possible 
for Object.wait().

Froma practical standpoint, these can happen on UNIX operating systems 
when a signal is delivered during a wait; signals typically abort 
blocking system calls on UNIX and many UNIX implementations of pthreads 
carry this over to condition variable behavior (though the pthreads spec 
itself leaves the matter undefined).  However, whether your code plans 
to run on UNIX and related operating systems or not, the specification 
for Java clearly leaves open the possibility of spurious wakeups, and 
you should account for them by always using a predicate loop with your 
wait/notify.

Even without this possibility, predicate loops are always a good idea -- 
especially in Java where objects' monitors are often subject to multiple 
related uses.

-- 
www.designacourse.com
The Easiest Way To Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation



== 5 of 5 ==
Date: Fri, Nov 26 2004 2:21 pm
From: Chris Smith  

Frank Gerlach <[EMAIL PROTECTED]> wrote:
> I googled InterruptedException and cam up with this page:
>     http://www.milk.com/java-rants/rant01-interrupted.html
> It basically states that the exception ONLY occurs when someone in the same
> VM calls Thread.interrupt() on the thread in question. This page also 
> discusses four options of how to handle the exception. One is to consume it
> (like I do, with an error message that points to the error of using 
> Thread.interrupt()), another is to rethrow it. I concede that throwing 
> an exception might be a viable option IF you really need to call 
> Thread.interrupt().

If you're claiming to post code that's generally useful to others, 
perhaps you shouldn't assume that they won't be interrupting threads.  
InterruptedException may be impossible 90% or more of the time, but the 
right thing to do is to throw it and let the caller decide.

That, plus the bug with "if (count == 0)", makes this a very poor choice 
of Semaphore implementation.  Fortunately, in the current version of 
Java, there is already a Semaphore class available in 
java.util.concurrent, and I would bet money that it actually works, 
unlike yours.

-- 
www.designacourse.com
The Easiest Way To Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation




==============================================================================
TOPIC: choosing random item from set with weighted probability
http://groups-beta.google.com/group/comp.lang.java.programmer/browse_thread/thread/da98e83f7a2c858b
==============================================================================

== 1 of 3 ==
Date: Fri, Nov 26 2004 11:11 am
From: [EMAIL PROTECTED] (Digital Puer) 

I have an algorithmic question (not necessarily tied to Java).

Suppose I have the text from a newspaper and want to choose
a letter from the text with proportional probability. For example,
if the letter 'e' occurs, say, 50 times out of a text of 150
characters, then 'e' will be chosen with probability 1/3. 

What is the best way to code this? I could set up an if-elseif ladder
like this:

x = random number [1 to total number of letters]
if (1 < x <= 10) /* 10, for example, because 'a' occurred 10 times */
  choose 'a'
else if (10 < x <= 14) /* because 'b' occurred 4 times */
  choose 'b'

This seems extremely tedious. Is there a better way?



== 2 of 3 ==
Date: Fri, Nov 26 2004 1:52 pm
From: Chris Smith  

Digital Puer <[EMAIL PROTECTED]> wrote:
> I have an algorithmic question (not necessarily tied to Java).
> 
> Suppose I have the text from a newspaper and want to choose
> a letter from the text with proportional probability. For example,
> if the letter 'e' occurs, say, 50 times out of a text of 150
> characters, then 'e' will be chosen with probability 1/3. 

<...>

> This seems extremely tedious. Is there a better way?

I don't really see any clever algorithm to do extremely well from any 
objective standpoint.  Here's how I would do it off-hand, though, which 
is a little easier on the programmer than what you wrote.  It also makes 
it easier later change things to load the probabilities from a resource 
or external file, which would be ideal.

The values in 'probabilities' should add up to one.  Because rounding 
error makes that hard to do precisely, the code will work for values 
less than one as well.  Values greater than one will shaft the latter 
values, but probably not enough to matter for cases of rounding error.

Here goes:

private static Map<Character, Double> probabilities
    = new HashMap<Character, Double>();

static
{
    // Initialize probabilities...
    probabilities.put('a', 1.0/6.0);
    probabilities.put('b', 1.0/6.0);
    probabilities.put('c', 1.0/6.0);
    probabilities.put('d', 1.0/6.0);
    probabilities.put('e', 1.0/3.0);
}

public static char getRandomChar()
{
    /* Loop causes a retry in case rounding error messes thing up. */
    while (true)
    {
        double p = Math.random();

        for (Map.Entry<Character, Value> entry : probabilities)
        {
            if (p < entry.getValue()) return entry.getKey();
            else p -= entry.getValue();
        }
    }
}

-- 
www.designacourse.com
The Easiest Way To Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation



== 3 of 3 ==
Date: Fri, Nov 26 2004 2:09 pm
From: "Matt Humphrey"  


"Chris Smith" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> Digital Puer <[EMAIL PROTECTED]> wrote:
> > I have an algorithmic question (not necessarily tied to Java).
> >
> > Suppose I have the text from a newspaper and want to choose
> > a letter from the text with proportional probability. For example,
> > if the letter 'e' occurs, say, 50 times out of a text of 150
> > characters, then 'e' will be chosen with probability 1/3.
>
> <...>
>
> > This seems extremely tedious. Is there a better way?
>
> I don't really see any clever algorithm to do extremely well from any
> objective standpoint.  Here's how I would do it off-hand, though, which
> is a little easier on the programmer than what you wrote.  It also makes
> it easier later change things to load the probabilities from a resource
> or external file, which would be ideal.
>
> The values in 'probabilities' should add up to one.  Because rounding
> error makes that hard to do precisely, the code will work for values
> less than one as well.  Values greater than one will shaft the latter
> values, but probably not enough to matter for cases of rounding error.
>
> Here goes:
>
> private static Map<Character, Double> probabilities
>     = new HashMap<Character, Double>();
>
> static
> {
>     // Initialize probabilities...
>     probabilities.put('a', 1.0/6.0);
>     probabilities.put('b', 1.0/6.0);
>     probabilities.put('c', 1.0/6.0);
>     probabilities.put('d', 1.0/6.0);
>     probabilities.put('e', 1.0/3.0);
> }
>
> public static char getRandomChar()
> {
>     /* Loop causes a retry in case rounding error messes thing up. */
>     while (true)
>     {
>         double p = Math.random();
>
>         for (Map.Entry<Character, Value> entry : probabilities)
>         {
>             if (p < entry.getValue()) return entry.getKey();
>             else p -= entry.getValue();
>         }
>     }
> }

You can remove the rounding problem by mapping from the character directly
to the integral counts and selecting the probability value from 0 to the
total count - 1. Because the sum totals the range of p, the final Map.Entry
will always be chosen if one is not chosen sooner.  This also makes
accumulating the counts easy--just keep adding them up along with a running
total.

Cheers,
Matt Humphrey  [EMAIL PROTECTED]  http://www.iviz.com/






==============================================================================
TOPIC: Ant vs Makefiles
http://groups-beta.google.com/group/comp.lang.java.programmer/browse_thread/thread/e81556a5c62ba767
==============================================================================

== 1 of 1 ==
Date: Fri, Nov 26 2004 12:18 pm
From: [EMAIL PROTECTED] (Harris L) 

Hi,

I am working on a project that is written in Java but it's mainly used
in Unix environments and uses Makefiles to build.

I want to develop on this project in a Windows environment and I want
to:

***Convert the Makefiles into Ant Build files*** 

Please note that I am not particularly familiar with either (Makefile
or Ant).

If any of you has any suggestions, pointers or references of how to do
this that it would be greatly appreciated.

Regards,
Harris




==============================================================================
TOPIC: How do you do this?
http://groups-beta.google.com/group/comp.lang.java.programmer/browse_thread/thread/f653c0cceabd25b4
==============================================================================

== 1 of 2 ==
Date: Fri, Nov 26 2004 12:48 pm
From: [EMAIL PROTECTED] (Corey) 

I am a bigginer programmer and I am wondering in GUI window how do you
just display text(not in a textbox)?



== 2 of 2 ==
Date: Fri, Nov 26 2004 2:00 pm
From: Chris Smith  

Corey <[EMAIL PROTECTED]> wrote:
> I am a bigginer programmer and I am wondering in GUI window how do you
> just display text(not in a textbox)?

Generally speaking, you use a JLabel.

-- 
www.designacourse.com
The Easiest Way To Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation




==============================================================================
TOPIC: Best way to do this
http://groups-beta.google.com/group/comp.lang.java.programmer/browse_thread/thread/8e38d69ac964c0ee
==============================================================================

== 1 of 1 ==
Date: Fri, Nov 26 2004 1:58 pm
From: Chris Smith  

Fran Garcia <[EMAIL PROTECTED]> wrote:
> I=3Fm developping an applet that plays a wav file and now I wanna add a
> slider to showing the position for the wav file, but I have no idea to
> do it. How can I communicate the read for the wav file and the slider.
> Listener, Timer or what?

Are you using the java.applet.AudioClip interface, or 
javax.sound.sampled.*?  If the former, you're not on solid ground trying 
to stretch the functionality this far.  You could probably kludge 
something together using a custom URLStreamHandler for your URL and 
wrapping the resulting InputStream to count the progress and report 
it... but that would be fairly ugly (also, I'm unsure if common browsers 
grant NetPermission("specifyStreamHandler"), which would be needed).

If you're using javax.sound.sampled.* then this is easier.  Post some 
code to play the sound, and I can help you get the progress meter going.

-- 
www.designacourse.com
The Easiest Way To Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation




==============================================================================
TOPIC: Finding raw types in 1.5
http://groups-beta.google.com/group/comp.lang.java.programmer/browse_thread/thread/cbe0331906e9f613
==============================================================================

== 1 of 1 ==
Date: Fri, Nov 26 2004 2:00 pm
From: Chris Smith  

I'm trying to convert some code to 1.5 from an earlier version of Java, 
and take advantage of generics.  Does anyone know of a tool to locate 
and list all occurrences of raw types in Java code?

-- 
www.designacourse.com
The Easiest Way To Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation




==============================================================================
TOPIC: Advanced question about generics
http://groups-beta.google.com/group/comp.lang.java.programmer/browse_thread/thread/70947db3058ccce1
==============================================================================

== 1 of 1 ==
Date: Fri, Nov 26 2004 1:04 pm
From: [EMAIL PROTECTED] (Jesper Nordenberg) 

Michal Kleczek <[EMAIL PROTECTED]> wrote in message news:<[EMAIL PROTECTED]>...
> Jesper Nordenberg wrote:
> > "Vincent Cantin" <[EMAIL PROTECTED]> wrote in message news:<[EMAIL 
> > PROTECTED]>...
> > 
> >>Hello,
> >>
> >>I have a class Server<C extends Connection> that accepts some connections 
> >>are for each of them creates an instance of C.
> >>
> >>Problem : the implementation of the class need to have C.class in order to 
> >>create its instance but it doesn't know it unless I ask the user of my 
> >>class 
> >>to give it in parameter.
> >>
> >>So the user of the class write something like that :
> >>
> >>    Server server = new Server<MyConnection>(MyConnection.class);
> >>
> >>but I would like him to only write something like that :
> >>
> >>    Server server = new Server<MyConnection>();
> >>
> >>Is there something in the language of Java 1.5 that can do implicitly what 
> >>I 
> >>want ?
> > 
> > 
> > No, not possible because of type erasure. A flexible solution is to
> > pass a factory object that create the instances, for example:
> > 
> > Server server = new Server<MyConnection>(new Factory<MyConnection>() {
> >   public MyConnection create() {
> >     return new MyConnection();
> >   }
> > });
> > 
> > public interface Factory<T> {
> >   T create();
> > }
> > 
> > This has several advantages over directly calling a constructor using
> > reflection.
> > 
> > /Jesper Nordenberg
> Hi,
> actually it is the same as the original solution - but more verbose.

No, it's not the same. The Factory solution is more flexible because
it allows you to use any constructor of the MyConnection class, or
even not to create a new object at all. For example:

final MyConnection connection = getConnection();

Server server = new Server<MyConnection>(new Factory<MyConnection>() {
  public MyConnection create() {
    return connection;
  }
});


Server server2 = new Server<MyConnection>(new Factory<MyConnection>()
{
  public MyConnection create() {
    return new MyConnection("This is an argument!");
  }
});

This is something you can't do by just passing the MyConnection.class
object.

/Jesper Nordenberg



==============================================================================

You received this message because you are subscribed to the Google
Groups "comp.lang.java.programmer" group.

To post to this group, send email to [EMAIL PROTECTED] or
visit http://groups-beta.google.com/group/comp.lang.java.programmer

To unsubscribe from this group, send email to
[EMAIL PROTECTED]

To change the way you get mail from this group, visit:
http://groups-beta.google.com/group/comp.lang.java.programmer/subscribe

To report abuse, send email explaining the problem to [EMAIL PROTECTED]

==============================================================================
Google Groups: http://groups-beta.google.com 

Reply via email to