Andrew Trumper

Greenhorn
+ Follow
since Sep 08, 2001
Cows and Likes
Cows
Total received
0
In last 30 days
0
Total given
0
Likes
Total received
0
Received in last 30 days
0
Total given
0
Given in last 30 days
0
Forums and Threads
Scavenger Hunt
expand Ranch Hand Scavenger Hunt
expand Greenhorn Scavenger Hunt

Recent posts by Andrew Trumper

Originally posted by Paul Clapham:

Which is pretty much like the code you posted, now that I stare at it for long enough. I don't like it either, but I can say why. When the referenced object disappears and all you're left with is the "shell" SoftReference object, then the hashCode changes and the meaning of equals changes. I don't like that. You could deal with the hashCode problem by storing it in an instance variable the first time you calculate it from the referenced object. The equals problem I don't know -- maybe you should reload the referenced object if it isn't there.



He's also got this.get() check for null and another this.get() afterwards.. This can fail since object are not gc()ed from any specific thread and the second this.get() can return null!

The SoftReference should not be the key and should not need an equals/hashCode(). A key should be the key. Either that or use a WeakHashMap with SoftReferences for the values (but the object for the keys). That way you don't need to clean up the HashMap when the object goes bye-bye.

If you don't use a WeakHashMap you'll want to add something to the cached object's finalizer to remove the entry in the table. Just remember, the remove opperation has to be thread safe with respected to the rest of the cache.
12 years ago

Originally posted by trebor iksrazal:
Hi all,

The code below attempts to do InetAddress.isReachable() on all possible IP's in a subnet, and try to do snmp walk on those that respond. This code works ok, albeit slowly - 25 seconds on a class A subnet. Even worse, on a big class A subnet, I get "java.net.ConnectException: No buffer space available" after around 1000 InetAddress.isReachable() calls.



Sounds like InetAddress.isReachable() is leaking. It has is the past ->

http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5082105
(fixed in 1.5.0_01)
(There are many other bugs in the database as well for even older 1.5 JVMs concerning InetAddress.isReachable() )

Could concievably some other resource is leaking as well.

Originally posted by Nicholas Carrier:
Ok I'm looking at the API and I can create Thread like objects in two diff
Now, in writing this post I think I found my own answer. The reason that you can create it in two different ways is because of the difference between implementing something and extending something. Whereas if it "is a" thread you would extend it, but if it "is something else" then you can implement Runnable so that you get the benefits of the Thread class without the deadly diamond of death problem.

Can someone just let me know if I am right, thanks?



Yes and no. "Deadly diamond of death"? Not sure what that is but I want one...

Implementing runnable and passing it to a thread object is and example of extendability using composition which can be thought of as a has-a relationship (Thread has a runnable).

Extending thread is an example of extendability through inheritance which can be thought of as an is-a relationship.

NOTE: Please don't think of inheritance and composition purely in terms of has-a and is-a. This is an over-simplification.

Runnable and Thread both exists because Runnable is independently usefll of Thread. A good example of this is Swing.invokeLater(). Thread pools also juggle Runnables and some state machines can be implemented with runnables too..

As for Thread allowing extendability through inheritance and composition.. I'm not sure why they did this. The general rule is if extensibility can be done using composition instead of inheritance without major drawbacks then do it using composition. I'm guessing they allow for both because it was very easy to implement. I think someone might have liked the idea that you can have code "belong" extend a Thread even though this has led to countless people thinking that only code in a Thread object can be run as a Thread.

Which method should you use? *sigh*. When dealing with threads there are more important things to worry about. To be honest I don't use either myself since I only use threads indirectly through a large concurrency library I wrote.

Originally posted by Tejas Chachcha:

Is there any solution to this scenario? If we want to make access from different jvms synchronized? Does it mean that synchronization/threading can make java somewhat plateform independent?



There's a few ways. One way is to have a process "own" that resource. Another is to make use of the file system's atomicity and java.io.File's createNewFile() method to create files on a file system that represent resources you want to lock. This second method is usally used despite the fact you have to watch out for a bunch of things like the app dying without releasing the lock... (This is usually fixed by some sort of keep-alive time stamp thing).

See ->
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4676183
.. why making use of deletion on exit doesn't always work

I've used both app based system wide locks and file based system wide locks in past projects with great success...
Hello there!

There appears to be no solution in Java 1.1, which I happen to know is what you were using at the time. The solution in later Javas (I think Java 1.4 and up) is to build a Socket object like this ->

socket = new Socket();

then build a an address to bind to like this ->

InetAddress address = InetAddress.getByName( hostAddressString );
SocketAddress socketAddress = new InetSocketAddress( address, port );

then connect like this ->

socket.connect( socketAddress );

This is, incidentally, a good example of why constructors with side effects are not a good idea. The point of a constructor is to allocate resources and return a usable object. Doing IO in a constructor is completely infuriating because

1) If you have IO you have threading since doing any IO on the event thread is asking for trouble

2) Usually you want to decide what to run on a thread first then have that code run on some specific thread. Doing IOin a constructor means that you need to pass all the params for the object and build it in the thread instead of passing the object itself - this can make code hard to make generic since the parameters needed to setup one type of object may be different for another.

3) It's surprising - people doing expect constructors to block!

4) It makes inheritance hierarchies difficult.

5) Most importantly, it basically ensures that there's no way to cancel the IO from another thread since there's no way to gain a reference to the object doing the IO. Not quickly freeing resources like io file descriptors and threads quickly means you will run out of resources if you're starting and stopping tasks quickly - like if a user it clicking on a search button madly..

This is in addition to all the other pre-existing constructor gotchas like letting object references escape in constructors and the confusing fun when constructors find themselves in inheritance hierarchies...

Originally posted by Drew Lane:
Hmmm...this seems more complicated than I had hoped. I probably didn't explain this very well, either.
I actually don't have any other of my own threads running at this point (I was actually referring to the AWT thread, etc.).
So, the main thing I want to accomplish is that the for loop is completed and the buf array is always full when the user tries to save the file by pressing a button. What's been happening is that sometimes the array gets partially full and I get a partial (corrupt) file saved.
Unfortunately, I have to use that for loop to read() the file due to some bugs in the implementation I'm using. It's the only method that seem to work consistantly.
From looking at the code that was posted, I like the idea of the wait/notify. Can I use this concept with the gui I made so that when the user pushes the button to save the file, it will wait until it's notified by the thread that the for loop has completed?
Maybe I just need to make the run method synchronized?
I hope this is more understandable.
Regards,
Drew





This should do what you're looking for although the implementation is cheese.

Originally posted by ShihChao Lin:
Hi:
Can anyone tell me why the synchronized for following code does not work?
I was hoping the output will be
AAAAA
BBBBB
But the result was
AAAAAAAAAA
Thanks for your help



What you ment to do was:

public class SyncTest extends Thread{
static StringBuffer letter = new StringBuffer("A");
private static synchronized void printChar() {
char c;
c = letter.charAt(0);
for (int i=0; i< 5; i++) {
System.out.print(c);
}
System.out.println("");
c++;
letter.setCharAt(0, c);
}
public void run(){
printChar();
}
public static void main(String[] args) {
SyncTest t1 = new SyncTest();
SyncTest t2 = new SyncTest();
t1.start();
t2.start();
}
}

Originally posted by sun par:
I am new to Swing, so I guess I misinterpreted.. This was what I read from jfc unleashed chapter 2
]


Speed really does mean different things to different people. In the example your citing hey are not comparing the same thing. In one case someone is adding items to a list one at a time. After each item is added the list is ready to be used, the scrollbars are update etc.. in the other case not only are all the items being added at once, but the "items" (The strings) are being generated on the fly and are therefore not stored anywhere.
When I read of swing vs awt "speed" comparisons I always think of GUI widget responsiveness. Swing GUIs almost always feel more sluggish than AWT GUIs. The reasone for this is the widgets in an awt program do most of their painting and whatnot in native code with native system widgets. Awt object usualy only go into java code for events and some resizing code. Swing objects by comparison are always emulating a look and feel and do so in java code using an abstracted graphics library. There is quite a bit of overhead associated with that.
I have written my own List object using an awt scrollpane and a pane. Adding 10 000 items to it takes very little time (about 100ms) as in addition to an add(Object o) function I have an add(Object[] o) function for batch adding. The most expensive opperation is either sorting all the list items or copying them across.. I don't allow someone to create a list from a data model or play with the internal data model as that would bring up some nasty threading issues which swing ignores but I really can't.
15 years ago
In my experience sleep is the way to go. The yeild loops I've coded tend to be huge processor hogs. I've had to replace them all in the program I've been developing.
The sleep value should be significantly large as well. 1 sec or more.... if possible of course.
Why didn't you just do test.run()?
I'm not sure if this post is redundent but here goes for the fun of it:
1) RE:
===========
It doesn't seem to me like they are all together different. You never started the first thread and the second 2 threads seem to have the same output. The thing that confuses me is that when I run it on my NT box, the two threads appear to run sequentially, not concurrently. I would think that you would see
i = 0
i = 1
i = 0
i = 2
i = 1
--------------------
This is easy. The program is too small to involve time slicing, as someone correctly pointed out.
2)

RE:
======================
I was aware that Windows did timeslicing, but your post got me to thinking maybe there just wasn't a big enough slice of time. So I made the break statement so that it broke at 100 instead. Still no swapping between threads. Then, I upped it to 1000. THEN, I saw a swapping. But here is the funny thing. At around 620 the threads switched on the processor, which is pretty neat, BUT the first thread which was preempted at 620 never completed! The other thread went from 0 to 999 and the program terminated. So it looked like this Thread th1 went from 0 to 620 and then th2 went from 0 to 1000 and the program terminated. How on Earth did this happen???
-------------------
This happens because the original code is broken.. Let me explain...
here's the code with line numbers:
1: class TestThread{
2: public static void main(String args []){
3: Thread1 t1 = new Thread1();
4: Thread th1 = new Thread(t1);
5: Thread th2 = new Thread(t1);
6: th1.start();
7: th2.start();
8: }
9: }// End of TestThread
10: class Thread1 implements Runnable{
11: int i;
12: public void run(){
13: i = 0;
14: while(true){
15: System.out.println("Value of i = " + i++);
16: if ( i == 10)break;
17: }
18: }
19: }

Lines 3,4, 5 and 11 are very stange because here we a runnable object that inherits is put into a thread and then started. So basically one single object is used by two threads. The object (of class Thread1) has an instance variable i. What results is a classic synchronization problem. Two threads modifying one variable i. This leads to, assuming time slicing gets involved, one thread finishing and the other thread going into an inf loop.
Here's some code that works:
Working code 1:
1: class TestThread{
2: public static void main(String args []){
3: Thread1 t1 = new Thread1();
4: Thread th1 = new Thread(t1);
5: Thread th2 = new Thread(t1);
6: th1.start();
7: th2.start();
8: }
9: }// End of TestThread
10: class Thread1 implements Runnable{
11: public void run(){
12: int i; //the varible "i" has been moved here.
13: i = 0;
14: while(true){
15: System.out.println("Value of i = " + i++);
16: if ( i == 10)break;
17: }
18: }
19: }

Working code 2:
1: class TestThread{
2: public static void main(String args []){
3: //this line is gone.
4: Thread th1 = new Thread1(); //change here.
5: Thread th2 = new Thread1(); //change here.
6: th1.start();
7: th2.start();
8: }
9: }// End of TestThread
10: class Thread1 extends Thread{
11: int i;
12: public void run(){
13: i = 0;
14: while(true){
15: System.out.println("Value of i = " + i++);
16: if ( i == 10)break;
17: }
18: }
19: }

to see the time slicing you need to set the break at around 1000 or even higher depending on the speed of your machine.
For added fun try running this code:
1: class TestThread{
2: public static void main(String args []){
3: //this line is gone.
4: Thread th1 = new Thread1(); //change here.
5: Thread th2 = new Thread1(); //change here.
6: th1.start();
7: th2.start();
8: }
9: }// End of TestThread
10: class Thread1 extends Thread{
11: int i;
12: public void run(){
13: i = 0;
14: while(true){
15: System.out.println("Value of i = " + i++);
16: try {yeild();} catch (Exception ex) {}
17: if ( i == 10)break;
18: }
19: }
20: }
yeild() tells the thread to yeild the processor and give other threads a chance to run. This means the output should be more staggered.

------------------
I am working on a program that creates about 50 threads that open new sockets. Occasionaly the user might want to cancel this action, which means all those threads have to be stopped (no, I don't use stop(), but I do set a flag, interrupt and join()). The thing is, it seems like
new Socket(ip, port);
is occasionaly getting stuck for large lengths of time if the ip or port isn't valid. I would like to know how to unblock this call (ie: cancel it). I've tried interrupt(), closing the (not yet created) socket and yelling at it. Nothing appears to work.