~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

Since not all the links have been updated yet:
here's a good one, too: http://docs.oracle.com/javase/tutorial/

I have now updated the links to remove references of sun.com. Let me know if there are still any broken/sun links in there. :)

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

There are some site wide issues going on (as already highlighted by other ongoing threads in the feedback forum). Hopefully it should be fixed in some time when Dani/Deceptikun are online.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

Yup, things don't seem to be working as expected and this is happening to almost everyone. Hopefully Dani/Deceptikun should be able to solve these issues as soon as they are online. :)

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

I'm think something has broke causing some basic Daniweb functionalities to not work correctly. Hopefully this should be fixed in some time as soon as Dani/Deceptikun are online.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

A lot of Daniweb functionality like editing post for moderators, moving threads etc. doesn't seem to be working at the moment. I'll sure Dani/Deceptikun will look into it when they are online. Please bear with us. :)

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

Minor stuff aside, this snippet has other problems. UUID is unique because of all the bits it has. Substring of a random number itself isn't random. If you'll read the UUID specification (which I think the UUID class follows), the different range of bits in an UUID stands for different components. You can't pick them apart and expect them to be unique. My personal vote goes out to the nextLong method of the SecureRandom class. You get a long datatype back and it's crptographically strong.

On a related note:

The objective was to give a certain custom Object a unique identifier in order to allow me to store them in a hashmap

IdentityHashMap doesn't work for you? Also, for live objects, identityHashcode is also unique since it is basically the memory address of that object which has to be unique unless we end up re-using the address space (which happens something is garbage collected hence the warning that it works only for live objects).

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

does it take time to update?

Yes, Dani said it might take around a day to update the images at the bottom of the forum.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

I still haven't got around to watching the original Berserk anime so I have put the movies on hold for the time being. Also, since the movie was released at around 3rd Dec in Japan, it takes some time for the subbed/dubbed version to appear at online stores/websites.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

Hi folks,

Winter 2012/2013 anime season will start in a few days! Here is a list of the anime which will air this coming season. As far as initial thoughts go, this season doesn't look that exciting. The anime which I'll be definitely following are:

I normally present a list of promising shows but this time around, reading the description isn't helping me a lot so I'll just leave it off to watching the first few episodes and then deciding for myself.

So, what's your list? Any promising anime I should look out for?

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

How so? ;)

Because you folks convert a GIF to a static image even if you don't have to. Oh the shattered hopes and dreams... :)

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

When you upload an avatar, we resize it internally to ensure that it's 80x80, and the method we use to do that only returns the first frame of an animated image.

And what happens if the original image is 80x80? You still resize it? If not, we now have a way of uploading animated avatars. If yes, you folks are bad guys. ;)

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

So the advantage of using a constructor over a setter is that a constructor can initialize more than a variable, which is what a setter does?

Not really, the main advantage of using a constructor to initialize all member fields is to ensure one-shot initialization of objects which when coupled with the use of final fields, is a good thing when writing multi-threaded code. If you use setters to initialize your object, there exists a point wherein you have an incomplete instance available which isn't a good thing. As an example:

Person p = new Person();
// some conditional check/logic
p.setName("Sanjay");
p.setAge(42);

The problem with the above code is that you have a possibility of having an "invalid" Person instance in your code; a Person object which doesn't have any fields set.

They should be private and have methods that access them...encapsulate, encapsulate, encapsulate!

Unfortunately, this kind of boilerplate is actually a Java language limitation. In C#, one can freely access public fields and if abstraction/encapsulation is required, they can be converted in "method" calls without changing any client code. Something similar can be done for Python (in which everything is public anyways).

So yes, though it's a good thing to lean towards encapsulation by creating an army of getters and setters (typical Java way of doing pretty much anything), it's worthwhile to note that it really isn't an accepted OO practice but more like a language limitation.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

In that case just use a random number generator supplied by the standard library. If you want "good quality" random numbers (numbers which can't be predicted), use the SecureRandom class or just use the Random class. Do note that this class doesn't offer strong guarantees like the UUID class.

// E.g.
Random r = SecureRandom.getInstance("SHA1PRNG");
System.out.println(r.nextLong());

BTW, you will get better answers if you actually tell us why you need random/unique numbers...

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

UUID.randomUUID().toString() gives the random-almost-unique string you are looking for. Replace the dashes which are present in the returned string if you don't need them.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

Look into the UUID class offered by Java. Though the probability of collision is not 0%, it's still very low. Read this.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

Two more ways of doing it:

Holder idiom is normally used when you need lazy initialization. Enum approach is used to cut down on the line count and is good if you don't want lazy initialization and error handling when creating singleton instances.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

I still think the best approach is to use xbat's account to remove what that idiot did, although i have no idea on how the system on this site works...just seems reasonable.

I have a feeling that in the future Daniweb will have an option of allowing the "owner" to "override" pretty much every user action action. That should take care of cases like this.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

IIRC, this happens when Daniweb includes some content (javascript/images/widgets etc.) from an external domain which is not allowed or is blocked by your ISP. Corporate ISP's are notorious for blocking a lot of sites. So basically it starts loading some resource and perpetually hangs up because the host/domain is blocked by your work proxy. Not 100% sure but this might be one of the reasons.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

Think about which piece of code (or specifically which method call) in your above snippet is responsible for doing the comparisons. Read up on the Javadocs of the Comparable.compareTo method. Anything you see in there which can "reverse" the checks you are making?

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

The universal solved is probably the fairest system

But is still open to abuse. SO system also has problems since it can award just a single person with the correct answer. I think the way it is done on MSF (Microsoft forums) is the best; you are allowed to mark multiple answers as the correct answer. In such cases, the OP can mark all answers which helped him/her inch closer to the solution without causing problems like starvation (only one contributor gets the solved count bumped) or mass distribution (everyone who posted in the thread has his count bumped up).

This also gives a bit more meaning to the solved post count since I have seen a lot of folks who like to post and are absolutely off-the-mark when replying or trying to help out someone. Not a bad thing mind you, but I really don't feel comfortable looking at numbers which might be the result of a collateral-reputation-shower. :)

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

Juno has performance and stability issues, at least I faced them. I would recommend grabbing the latest 3.X version of Eclipse with Java 7 for best results unless you are bound by a predetermined version of Eclipse or Java.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

Is it done via socket connection?

Yes

Is it using Java sockets or the client browser have it's own socket to establish a connection with the Tomcat server? Or does the client browser uses the socket provided by the operating system to establish a connection to the Tomcat server?

Socket API is provided by the OS. The socket libraries provided by runtimes like JVM(Java), Python, Ruby are all wrappers over the OS sockets. These networking libraries/infrastructure just provide an abstraction so that you don't need to know the implementation details of the socket API for each and every platform/OS.

I don't think a servlet uses socket connection but rather has a listener on a port

This statement is incorrect and doesn't make a lot of sense.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

BTW... What is up with those check marks that show around posts?

It's a new feature that was introduced recently as explained by Dani here.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

I'll assume you are using Eclipse here. IIRC, Eclipse "Export JAR" doesn't have the option to collpase the dependency jars into a single JAR. For this to work, just make sure you have a dummy (or necessary) main class in your project. Then click Export -> Runnable JAR. Options 1 and 2 provide you the choice to have dependent JARs collapsed into the given JAR.

If not Eclipse, you can always try out One Jar but I personally have no experience with it.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

I'll try to answer the points applicable to me:

What value do you get from helping people?

It sucks to be stuck on something when you are trying to learn stuff. This is when books don't help and the online resources are not enough. My aim here is to just help out people who deserve it so that they can learn stuff quickly and get into the thick of things rather than get frustrated and give up on something. Of course, doing this for each and everyone is not possible but I try. And anyways, who doesn't like to show off? ;)

Has DaniWeb helped you forward your career?

Yes; when helping out folks you end up trying a bunch of stuff yourself. This helps me learn new things which in turn makes me a better person at my workplace (well, at least technically).

Have DaniWeb community members evolved into quality online friends?

I would say yes. I'm not really a Twitter/Facebook type of person so I'm not in constant touch with others, but yes, I know a lot of good people here with whom I would definitely chat when I get time (new chat system, I'm looking at you!).

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

So this would likely be just as efficient as a non-recursive implementation because it uses tail recursion

Not sure if that was intended but the function you posted isn't tail recursive because the state information has to be saved on the stack frame to carry out the multiplication. :)

A tail recursive function would be something like:

int factorial1(int n, int accumulator) {
    if (n == 0)
        return accumulator;
    return factorial1(n - 1, n * accumulator);
}

int factorial(int n) {
    return factorial1(n, 1);
}

On a related note, JVM unfortunately doesn't do tail call optimizations so you'll either have to:

  • Convert code to use a non-resursive solution
  • Use an explicit stack data structure and modify your recursive code a bit
  • Use a JVM language like Scala which detects tail recursion and performs the necessary optimization before writing out the JVM bytecode
~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

But I do not know how this is done. Any idea?

I think I know what you are talking of. There is no way of setting a private field without constructor or setter injection unless you are OK with using reflection to set your fields. Look into the @Inject annotation which does exactly this. It has been some time since I have been actively involved with Spring so look at the Spring docs for details on this.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

The class won't compile?!

Because you have already assigned null once to the field s. The correct way is to do:

public class Test {
  private final String s;
  public Test(final String s) {
    this.s = s;
  }
}
~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

Array is a bad example because arrays in Java receive special treatment. Arrays are objects but you'll never see the source code for array of Object or array of primitives in the source distribution. They are dynamically created. For more gory details, read this

However, line one does assign seven to that variable, length.

final doesn't mean that it can never be assigned. final means something which has to be assigned once and only once.

how is length being set when neither a constructor nor a setter method can do this

As already mentioned, arrays receive special treatment in the JVM to the point that they have special opcodes assigned for creating arrays. Thus, when you attempt to create an array of given size, that size is set to the length field using the invisible constructor dynamically generated by the JVM (as mentioned above).

In the Spring framework, when doing dependency injection, even if a variable is private and there is no corresponding setter method, the variable will be changed upon initialization

Maybe I'm reading your question wrong, but a private field doesn't mean it can never be initialized by outside code. If you class has a constructor which takes care of initializing private and final fields, the outside code can simply call the constructor and the private variable will be initialized even when the outside code can't directly access the class privates.

Spring has two forms of injection: setter and constructor. …

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

if (play[] == card)

This line is invalid Java syntax. If you want to check if an int array contains a particular int value, you'll either have to loop over the array to check the occurrence of that value or convert the array to something like a Set (if ordering is not important) and then use its contains method.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

Two problems with your approach.

First the major one: As mentioned by James, never use busy loops (i.e. while(true) {} in your application code. It will always result in CPU spinning at 100%. There is almost always a better way of waiting for some event than to loop over it continuously. If you ever feel that there is no alternative left, at least sleep for an acceptable amount of time (e.g. 100ms) before testing the condition again. Also, the Thread.sleep call in your code is not really required. Explicit sleeps in application logic is almost always a sign of bad design. Try to find better way to solve the same stuff.

The second minor issue is that you are always creating a thread whenever there is a request to play a new sound. This is expensive since Java has OS threads and OS threads have a significant (comparatively) overhead during creation. Plus, if you are using a recent Java version (e.g. Java 5 and above), give preference to using Executor and ExecutorService over raw threads if possible.

Here is one possile way of how I would do it, not the best but still works good.

public class Noise {

    /**
     * @param args
     */
    public static void main(String[] args) throws Exception {
        final SoundHandler handler = new SoundHandler();
        handler.newSound("gunshots.mid");
        Thread.sleep(1000 * 100);
    }

}

class SoundHandler {

    private final Executor executor = Executors.newCachedThreadPool();

    public void newSound(String sound) {
        executor.execute(new SoundRunnable(sound));
    }

    class SoundRunnable implements Runnable {
        final String soundName; …
~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

70 WPM. Meh, that's pretty bad. ;)

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

Happy Birthday Dani; here's to hoping you take a day off from Daniweb and enjoy!:)

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

What matters is efficiency of code

No, what matters first and foremost is the code is doing the job it set out to do. Everything else (good design, efficiency etc.) comes after that.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

If I getting you right either alternative queue natively handles the sleep, notify etc.?

None of the queues use sleep AFAIK. Using sleep is a bad because you end up waiting for a fixed amount of time. Let's say you make the consumer thread sleep for 100ms waiting for data. What happens if the data arrives in 1ms? 99ms are wasted sleeping. This is the reason why pretty much everything in the standard library uses wait and notifyAll with some very rare exceptions (read: advanced implementations).

Both the queues I mentioned are blocking queues i.e. will cause blocking if required. It's just that their implementations are different -- one uses arrays underneath, the other uses linked lists.

The queue you were using - ConcurrentLinkedQueue, is a bit different in the sense that it doesn't support blocking natively. So if you have to implement producer-consumer for it, you'll have to do the hard work of co-ordinating the corresponding threads which is a pain and easy to mess up. I must agree though that this concurrent queue has a better chance of scaling given that it doesn't use blocking (wait/notifyAll) but is much harder to use. Just stick to simple implementations and work towards complex ones in case you have visbile performance/other issues.

I'll check it out; I don't have a purpose so much as just trying to play around and learn some stuff.

If you want to learn stuff, look at how the queues are implemented. In …

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

Second version all the way. I'm pretty sure the first version is for those who get paid by lines of code written. ;)

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

If you want a bounded queue (one with capacity) for producer consumer, use a LinkedBlockingQueue or ArrayBlockingQueue and its methods, put and take which automatically block/wake the corresponding thread.

For e.g. put on a full queue will block that particular producer whereas take on an empty queue will block that particular consumer. Perfect for your use case IMO.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

What is the purpose of the method start(), why not just put that code in main()?

And...

In main() Test is instantiated as an object and start is called like this: new Test().start();

Why not just make start a static method and call it from main?

Simply put, for reasons of flexibility and good practice. Ideally, main should just be the driver method with minimal logic so that in case you need to re-use the logic somewhere else, you can intantiate the class, with each instance having specific behaviour based on the arguments passed in. Putting logic in static methods hurt scalability and re-use, at least in a much larger context if not for this small program.

Long back I had to work with some code which used static variables for maintaining state and had significant amount of code in the main method. I had to jump through hoops to ensure that the code behaved as expected when called from multiple threads.

I know these things don't apply to your small snippet but I guess that's how my brain is wired to write code. :)

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

Synchronizing this statement should block the second thread from accessing the queue correct?

No, because your code synchronizes on this inside the ProductConsumer class which means the current instance of the ProductConsumer object. Since each thread has a different ProductConsumer instance, it doesn't prevent the threads from adding items to the queue concurrently. It would be a different thing if you synchronized on the queue though.

I would personally recommend starting with the Java trail and working through the concepts incrementally instead of continuing down this path of haphazard changes. :)

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

There is also a WindowsBuilder Pro which was previously a paid product but is now free thanks to Google. Never used it seriously but seems like it handles both SWT and Swing drag-n-drop GUI development and is available as an Eclipse plugin.

EDIT: Doh, beaten by James.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

loop until end of file, doing nothing.

hasNext doesn't mutate or change the cursor position. So the while loop results in an infinite loop since hasNext will always return true (for a non-empty file) given no lines are consumed. Basically, the code will only proceed if the file is completely empty.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

I've fixed the code to pass a the queue but now I get null pointer exceptions...

Your constructor definition of ProductConsumer is hosed. You write prodQueue = this.prodQueue instead of writing it the other way round. Think about it, do you really want to assign the passed in argument the value of prodQueue instance, which is by default null?

Are you sure that it is supposed to instantiate that way???

Yes, it's possible with the new Java 7 type inference.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

You seem to be having multiple threads utilizing multiple instances of the ProductProducer class i.e. each thread operates on a separate instance of the ProductProducer class which explains each item count occurring twice, once for each queue. If you want different instances to operate on the same queue, either declare the queue somewhere where it's visible by all the threads or pass in the Queue when constructing ProductProducer instances.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

Well, I can't help with this stuff but offer some advice. With a statement like:

Actually I don't even know where to start with that

I won't be surprised if you don't get replies even in Game oriented forums. As someone who has been on the "question answering" side of things for years now (newsgroups, forums etc.), the last thing a "helper" would want to see is a question in which the asker isn't clear about what he needs.

You say you are new with both 3D and LWJGL. I think the first logical step would be to get to know these things to a level at which you are comfortable enough to actually find out what's going wrong but don't know the solution to get around it. Since jMonkeyEngine is all Java, I would advise you to take out the source and "debug" through it when running the sample examples which come with it (either in Eclipse, Netbeans etc.).

The next problem is how to acquaint yourself with enough 3D knowledge to create your own engine. Search around google for queries like "starting 3d game development" etc. and you will definitely come across threads posted by others in the same situation as you. Also, are you aware of what kind of "features" a game engine provides? I would first recommend using a 'simple' engine, getting a feel of how the engine lets you program your own logic and then set out to write one. After …

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

Anything from plain theory to ready code would be appreciated. Thanks!

Not ready code but have you tried looking at the source code of an existing 3D engine like Jmonkey? Also, you will have more luck with your question in a game engine oriented message board.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

I am getting the results that Davey and James saw

I'm not James :/

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

I get 477 results using Daniweb internal search and around 620 results using the actual Google search filtered down for daniweb. I'm using Google Chrome version 22 on Win XP.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

I'm sorry I should said "Pattern pattern = Pattern.compile("^In our tests, downloads on port 6881\D+(\d+)\D+(\d+)");" is NOT working for me. But I think it is close. I just tried "^In our tests, downloads on port 6881\D+\d+\D+(\d+)\D+\d+\D+(\d+)" and that did not work either.

It really need not be that complicated. If you are sure of the format of the text, the simplest regex would be as shown in the below code:

public static void main(final String[] args) {
    final String sample = "In our tests, downloads on port 6881 achieved up to 12059 Kbps " +
            "while downloads on port 47649 achieved up to 9623 Kbps.";

    final Pattern pat = Pattern.compile(".+?(\\d+) Kbps.+?(\\d+) Kbps.*");
    final Matcher matcher = pat.matcher(sample);
    if(matcher.matches()) {
        int speed1 = Integer.parseInt(matcher.group(1));
        int speed2 = Integer.parseInt(matcher.group(2));
        System.out.printf("Speed 1 => %s and Speed 2 => %s", speed1, speed2);
    } else {
        System.out.println("No match found");
    }
}

This assumes that the speed is always followed by a space and then Kbps but I guess that's a fair enough assumption.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

After the 30 minute cutoff, you can't edit your original post. You now have two options:

  • Make a new post with the suggested edit
  • "Flag bad post" your original post and request a moderator to make changes on your behalf

I personally feel that the first option makes more sense since you don't have to wait for a moderator to make the changes so that you/others can see them. So yes, just make a new post saying that "edit: new snippet here" or something along those lines.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

I was using the try-catch to make sure the program doesn't crash and stop running

That's understandable, just make sure that in such cases resort of using the minimum number of catch blocks you can do away with.

isn't everyone these days?

Unfortunately no. A lot of people are stuck on 1.5 and a minority still uses 1.4 for legacy reasons *shudders*.

What is the better way?

If you have the freedom to use Java 7, you can significantly reduce the code boilerplate. Below is a sample template of how it might look like:

public class Test {

    public static final OpenOption[] options = { StandardOpenOption.APPEND,
            StandardOpenOption.CREATE };

    public static void main(final String[] args) {
        new Test().start();
    }

    public void start() {
        final String host = "somehost";
        final int port = 1234;
        final Path path = Paths.get("some", "random", "path");  /* /some/random/path */
        while(true) {
            try (BufferedWriter out = Files.newBufferedWriter(path, Charset.forName("UTF8"), options);
                    Omega omega = new Omega(host, port)) {
                // connect omega; read data; write data; sleep for some time
            } catch (Throwable t) {
                t.printStackTrace();
            }
            // when code reaches here, `out` and `omega` will be closed
            // irrespective of any exceptions thrown by the contained code.
        }
    }
}

class Omega implements AutoCloseable {
    String host;
    int port;

    public Omega(String host, int port) {
        this.host = host;
        this.port = port;
    }

    @Override
    public void close() throws Exception {
        // your closing code here
    }
}

The above code assumes you are …