Java Queries Here..

quicky008

Technomancer
Yes,after writing a custom copy method for copying the contents of 1 file to another,its working.It was stupid of me to assume that copy was referencing some built in copy function in java.I had confused it with Files.copy(),which is intended for a somewhat different usage.
 

TheSloth

The Slowest One
In case of doubts, always move the cursor over the class/method/identifier name to find out more info about it provided by IDE. Always read the stack trace carefully. Some basic pointers to debug your code quicker. I have overlooked details and wasted lot of times looking for solutions which were not even my problems and always hated myself for not looking into the errors in more details.
 

quicky008

Technomancer
a friend has asked for my assistance with a program that he needs as a part of some kind of "project work".The program is as follows:

"Wap in java to create a console based application to encrypt and decrypt a message (using cipher text/unicode exchange etc)."

While i have done some elementary coding in java,i really dont know much about encryption,especially things like this "unicode exchange".Can anyone give me some pointers as to what it really is and how i could possibly incorporate it into a program on encryption?Some tutorials or sample code detailing the process of encryption using unicode would have been very helpful indeed.

I am by no means a java expert thus any help i received with this would be greatly appreciated.
 

Desmond

Destroy Erase Improve
Staff member
Admin
You might want to look into the javax.crypto package. It contains classes that allow you to perform almost any kind of encryption.

Specifically read up about the Cipher class and how to use it.
 

quicky008

Technomancer
i found some documentation on the crypto package,like this one here:

*docstore.mik.ua/orelly/java-ent/jnut/ch26_01.htm

However it all seems rather difficult to understand.Is there any hands on guide/tutorial that explains everything in a noob friendly way?Also what exactly is unicode exchange-is that a system of encryption like RSA,DES etc?
 

Desmond

Destroy Erase Improve
Staff member
Admin
I found this after a quick search: Java Cipher Class Example Tutorial - Encryption and Decryption Example

Might be what you need.

I have never heard of unicode exchange myself, perhaps you should ask for clarification.
 

quicky008

Technomancer
When i attempt to run the foll. program:

Java:
public class Main extends Thread {

    public static int amount = 0;

    public static void main(String[] args) {
        Main thread = new Main();
        thread.start();
        // Wait for the thread to finish
        while(thread.isAlive()) {
            System.out.println("Waiting...");
        }

        // Update amount and print its value
        System.out.println("Main: " + amount);
        amount++;
        System.out.println("Main: " + amount);
    }

    public void run() {
        amount++;
    }
}

I get the foll. Output:

Waiting...
Waiting...
Main: 1
Main: 2


Can anyone explain why it happens? I am trying to understand mutithreading but this example is getting me confused.

Why have they used isalive()? Why is the waiting message displayed twice?
 
Last edited:

Desmond

Destroy Erase Improve
Staff member
Admin
Can anyone explain why it happens? I am trying to understand mutithreading but this example is getting me confused.
Here's what's happening:

1. You start the thread, the run() method gets called, `amount` gets incremented by 1 and the thread terminates. The program prints `Waiting...` until this termination occurs.
2. You print the value of `amount`, which is now 1 because of being incremented in the run() method.
3. You increment the value of `amount` in the main() method, the value is now 2.
4. You print the value of `amount` again.

I don't know what you are trying to test with this program though.

Why have they used isalive()? Why is the waiting message displayed twice?
isAlive() just returns true or false based on whether the thread is alive or not. Since your thread is only incrementing the value of `amount` exactly once, the thread does not live for long. Once it finishes executing all lines of code in the `run()` method, the thread terminates immediately, that is why it prints "Waiting..." twice because it terminates quickly. You can get the thread to be alive longer by calling a `Thread.sleep()` method in your `run()` method. This will result in many more "Waiting..." messages to be printed.
 

TheSloth

The Slowest One
replace your while loop with
while(thread.isAlive()) {

System.out.println("Waiting..."+thread.getName() + " -- " + thread.getState());
}
Now you can check in which state thread was. isAlive is true if thread has started and not terminated yet.
 

Desmond

Destroy Erase Improve
Staff member
Admin
Also, it's a better practice to use a Runnable rather than extending a Thread. You don't need to extend a Thread class unless you absolutely have to.
 

quicky008

Technomancer
Thanks a lot for the replies.

The source of the above code was a tutorial on threads that i found on W3schools:

*www.w3schools.com/java/java_threads.asp

This example can be found under the topic entitled "Concurrency problems"

I agree that using the runnable interface seems like a better idea,as extending the Thread class could prevent the class containing the code from extending other classes,if needed.

It seems the purpose of using threads is to allow the code/program to operate more efficiently by "doing multiple things at the same time"-i can't quite understand from the above example how this is being accomplished.Rather than using threads,one could simply achieve this by calling a function that's dedicated to that particular task(such as incrementing the value of amount in the above example)-so what added advantage does a thread bring to the table?

Can anyone please point me to a simple example that illustrates the above concept ie thread being used to do multiple things simultaneously in a more lucid manner?


Also how can i create and run multiple threads in the same program?I think in this example they have only created one thread that modifies the value of amount only one time.

Ever since i started learning java,the concept of threads has always kind of confounded me.Threads are supposed to make programming more efficient,but the examples i found online or in text books only increased my confusion rather than mitigating it.
 

quicky008

Technomancer
one more question,even though it may sound rather asinine:

Why is the method of running a thread created by extending Thread class different from that of the one where it has been created by implementing runnable interface?In case of the former,one only needs to invoke the start() method via an object of the class,but for the latter,it can be run by passing an instance of the class to a Thread object's constructor and then calling the thread's start() method- why does such a difference exist?Is it like this by design?

Also can anyone please suggest a guide or simple tutorial for ADT and message passing in java?
 

Desmond

Destroy Erase Improve
Staff member
Admin
i can't quite understand from the above example how this is being accomplished
The above example is demonstrating that you can increment the value of `amount` in parallel. Though it is not a very good example.
so what added advantage does a thread bring to the table?
It allows you to run things in parallel. For example, if you were to create a UI application in a single thread, you would not want the whole application to freeze if you want to trigger some long running job. In this case, you run the job in a separate thread and let your UI application run in the main thread. This way your UI application does not freeze and the job goes on in the background.
Can anyone please point me to a simple example that illustrates the above concept ie thread being used to do multiple things simultaneously in a more lucid manner?
Also how can i create and run multiple threads in the same program?I think in this example they have only created one thread that modifies the value of amount only one time.
Consider this code:

Java:
package come.desmonddavid.ThreadTest;

public class ThreadTest {
    public static void main(String[] args) {
        Runnable r = () -> {
            System.out.println("Starting thread "+Thread.currentThread().getId());
            for(int i = 0; i < 10; i++) {
                long sleepTime = 1000L;
                try {
                    System.out.println(Thread.currentThread().getId()+": Sleeping for "+sleepTime+" milliseconds");
                    Thread.sleep(sleepTime);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("Exiting thread "+Thread.currentThread().getId());
        };
      
        Thread t1 = new Thread(r);
        Thread t2 = new Thread(r);
        Thread t3 = new Thread(r);
      
        t1.start();
        t2.start();
        t3.start();
    }
}

Here, I am defining a Runnable that logs some messages when the thread starts, sleeps and ends. It also prints the thread id in each message.

After this I am defining three Threads to run this Runnable and I start them. When you run this, you will get an output similar to the following:

Code:
Starting thread 11
11: Sleeping for 1000 milliseconds
Starting thread 13
Starting thread 12
12: Sleeping for 1000 milliseconds
13: Sleeping for 1000 milliseconds
12: Sleeping for 1000 milliseconds
11: Sleeping for 1000 milliseconds
13: Sleeping for 1000 milliseconds
13: Sleeping for 1000 milliseconds
12: Sleeping for 1000 milliseconds
11: Sleeping for 1000 milliseconds
11: Sleeping for 1000 milliseconds
13: Sleeping for 1000 milliseconds
12: Sleeping for 1000 milliseconds
11: Sleeping for 1000 milliseconds
12: Sleeping for 1000 milliseconds
13: Sleeping for 1000 milliseconds
Exiting thread 11
Exiting thread 13
Exiting thread 12

As you can see, the system creates three threads with ids as 11, 12 and 13. However, you will notice that every time you re-run the program, the sequence is different every time. This is because each of these threads are running in parallel. So, which thread executes when is chosen by the operating system. This is also not a very good example, but you can see how parallel processing works in this case.
 

Desmond

Destroy Erase Improve
Staff member
Admin
Threads are supposed to make programming more efficient,but the examples i found online or in text books only increased my confusion rather than mitigating it.
Threads can also make your code very complicated by potentially introducing problems such as race conditions, deadlocks, ConcurrentModificationExceptions, etc. So, you have to be very careful when using Threads. You should read up about thread safety in Java to see why this is important.
Why is the method of running a thread created by extending Thread class different from that of the one where it has been created by implementing runnable interface?In case of the former,one only needs to invoke the start() method via an object of the class,but for the latter,it can be run by passing an instance of the class to a Thread object's constructor and then calling the thread's start() method- why does such a difference exist?Is it like this by design?
Extending a Thread class may be beneficial in case when you already have some Thread functionality defined either as an abstract class or an existing concrete class and you need to enhance it's functionality. This however is a very special case and for most cases you will not need to extend a thread class since you simply need to run some piece of code. In this latter case, implementing a Runnable is simpler and thus preferable over extending a Thread class.
 

Desmond

Destroy Erase Improve
Staff member
Admin
Also can anyone please suggest a guide or simple tutorial for ADT and message passing in java?
What is ADT?

As for message passing, it's a broad topic. As in there are many ways to implement it. One way I can think of is to expose some methods after extending a Thread class and pass values to the thread using that.

Here is an example:

Java:
package come.desmonddavid.ThreadTest;

public class MessagePassingTest {
    public static void main(String[] args) throws InterruptedException {
        SquareThread st = new SquareThread();
        st.start();
        Thread.sleep(1000);
        st.feedValue(2);
        Thread.sleep(1000);
        st.feedValue(4);
        Thread.sleep(1000);
        st.feedValue(10);
        Thread.sleep(1000);
        st.quit();
    }
}

class SquareThread extends Thread {

    private volatile boolean valChanged = false;
    private volatile boolean quitThread = false;
    private volatile int value = 0;

    @Override
    public void run() {
  
        System.out.println("Starting SquareThread");
  
        while(true) {
            if(quitThread) {
                System.out.println("Exiting SquareThread");
                return;
            }
      
            if(valChanged) {
                System.out.println("Square of " + value + " is " + value * value);
                valChanged = false;
            }
        }
    }

    public void feedValue(int value) {
        this.value = value;
        valChanged = true;
    }

    public void quit() {
        quitThread = true;
    }

}

Here, SquareThread is a thread that runs in an infinite loop and waits for values or a request to terminate. The main thread (The thread that runs the main() method) then feeds values to this thread via the feedValue() method, waiting 1 second between feeding values three times. After than the main() method calls quit() and that terminates the thread. This is a very simple example, so I think you should be able to understand just by looking at it. If you have any doubts, then ask here.

Edit: This is also a good example of when extending Thread is beneficial.

Edit2: Also note that the variables in the thread use the volatile keyword. It's important to use either volatile variables or atomic datatypes because of thread safety. If I had not used volatile, the SquareThread may or may not see the new values that we pass to the thread via feedValue() or quit(). You can test what happens by removing the volatile keywords from the variables and run the program again.
 
Last edited:

TheSloth

The Slowest One
^This is good stuff.

@quicky008 Desmond has already linked one site above called Baeldung, this site is pretty much my goto for nearly all topics related to Java and java based frameworks. Apart from this you can refer howtodoinjava and jenkov. geeksforgeeks is also decent. BUT STOP referring w3schools, javatpoint tutorialspoint like sites. refer these if you don't find good examples on the sites I mentioned earlier. And also make a habit of reading official documentation for thorough understanding of some topics if you really want to know the internal workings.
 

quicky008

Technomancer
@Desmond David : Thank you for all the comprehensive & in-depth tutorials you posted in response to my queries.I will go through them tomorrow.

I attempted to study the code on achieving concurrency using threads that you posted earlier,but there were certain things in it that i didn't quite understand eg the foll. expression :

Runnable r = () ->


It seems the arrow symbol is a representative of lambda expressions in java,but i am not really familiar with it and thus couldn't grasp its purpose in this code.Also isn't runnable an interface that's present in java?Are you trying to instantiate runnable here?(not sure whether interfaces can be instantiated or not)

Also why is r being passed as a parameter to the constructor of the thread class here?

I agree that message passing is quite a broad and somewhat abstruse topic,and the examples i found online hardly helped me understand any of it.I will take a look at your code tomorrow-perhaps it will help clear things up to some extent(there's a tutorial available at geeksforgeeks but it seemed quite complicated from my preliminary inspection)


@TheSloth :Thanks for suggesting Baeldung,to be honest i never heard of it until today,and i must say that it does look really interesting.I will look up some of the things that i didn't understand all that well (eg message passing)in it tomorrow.

The reason many folks keep checking out w3schools,javatpoint etc is that their links pop up most frequently when one searches for something on google(programming related,that is).They are frustratingly popular it seems!
 

Desmond

Destroy Erase Improve
Staff member
Admin
It seems the arrow symbol is a representative of lambda expressions in java,but i am not really familiar with it and thus couldn't grasp its purpose in this code.Also isn't runnable an interface that's present in java?Are you trying to instantiate runnable here?(not sure whether interfaces can be instantiated or not)
Sorry, that was a force of habit. We use Java 8 at work, so I have developed a habit of using lambdas.

Basically, Runnable r = () -> {} is equivalent to:

Java:
Runnable r = new Runnable() {
    public void run() {
        // Do something
    }
}

Since Runnable has been made into a Functional Interface in Java 8, that means you can use a lambda when defining it. But you can also use an Anonymous Inner Class like the second example if you want. Interfaces can be instantiated like classes but since interface methods are not defined, you have to define them as well like I have with the run() method in the second example.

Also why is r being passed as a parameter to the constructor of the thread class here?
Because Thread has multiple overloaded constructors, one of them takes a Runnable as an argument. Reference: Thread (Java Platform SE 8 )

@TheSloth :Thanks for suggesting Baeldung,to be honest i never heard of it until today,and i must say that it does look really interesting.I will look up some of the things that i didn't understand all that well (eg message passing)in it tomorrow.
I still take reference from Baeldung, and I have over 9 years of experience working in software development.
The reason many folks keep checking out w3schools,javatpoint etc is that their links pop up most frequently when one searches for something on google(programming related,that is).They are frustratingly popular it seems!
I think they are okay for beginners.
 
Top Bottom