Select Page

Base on the given prompt and starter code, finish a code that is complete, run correctly, and a good coding style.(To accomplish this code, an experience on multi-threading in Java needed. The code will need synchronized keyword along with extending the Thread class.)


Don't use plagiarized sources. Get Your Custom Essay on
JAVA Multi Threaded Encryption
Just from $10/Page
Order Essay


Unformatted Attachment Preview

Having a good coding style makes your code readable and easier to understand for everyone
reading it. The idea is to treat it as if another programmer will continue to maintain the code after
you. Follow each of these basic style guidelines which you will be graded on:
1. File header:​ At the top of your file, include a 2-4 sentence summary about the file. Include
your name and email as well as references to sources used.
2. Class Header: ​Describe in 1-2 sentences the purpose and capabilities of your Class. Talk
about important instance variables if there are any.
3. Method Header:​ Describe method functionality briefly and mention special cases if there
are some. Include arguments and return value descriptions.
4. Use proper indenting​: Indent each block of code consistently (e.g., method body, loop
body). Line up the lines in the block so that they are all indented to the same degree. USE
a. See examples of this in the book and in the code samples below.
5. Use descriptive variable names​: The names of your variables should describe the data
they hold. Almost always, your variable names should be words (or abbreviations), not
single letters. An exception to this rule is loop control variables that designate an index in an
array. i, j, and k are accepted names for these. It is preferable to have clear, longer,
reasonable variable names in your code overall (example: lowerCaseLetter and
upperCaseLetter are better than letter1 and letter2. l1 and l2 are unacceptable.).
6. Avoid using magic numbers​: Magic numbers are direct usages of numerical or text values
throughout the code that should be refactored for readability and easier code maintenance.
These values should be stored in a variable (usually named with caps and underscores).
These variables names should also be descriptive and placed in the beginning of the
class/method grouped together.
a. See examples of this in the book and in the code samples below.
7. Write short methods​: Break your methods up into sub-methods if they are getting too
complicated or long. If you find yourself having to repeat typing similar code (can be
copy-pasted), then modularize the code by making a new helper method.
8. Write short lines​: Each line of code should be no longer than 80 characters, so it can fit in
a reasonable size window. Your vim setup should highlight lines that are longer than 80
characters. You may find that you need to wrap your lines of code to preserve the character
limit (examples below). You can do so by following these general principles:
a. Break after a comma (example 1, 3 and 4)
b. Break before an operator (example 2 and 5)
c. Align the new line with the beginning of the expression at the same level of the
previous line (example 4 and 5)
d. If the above rules lead to confusing code or to code that’s squished up against the
right margin, indent 8 spaces instead. (all examples)
Example Method Code Style
​ ​/** Return the score of the letter in scrabble.
* @param letter The letter in question
* @return The scrabble value of the letter
* */
private int letterScore( char letter )
char lowerCaseLetter = Character.toLowerCase( letter );
switch (lowerCaseLetter) {
case ‘a’: return 1;
case ‘b’: return 3;
case ‘c’: return 3;

case ‘z’: return 10;
default: return 0;
Example Magic Number Refactor:
/** In this example, 7 is used as the max password size. To avoid having
* to sprinkle the value 7 all over the code, MAX_PASSWORD_SIZE is used
* instead, which makes more sense. If the max password size needs to be
* changed, the value is updated everywhere MAX_PASSWORD_SIZE is used.
* */
public class Foo {
public void setPassword(String password) {
// don’t do this
if (password.length() > 7) {
System.out.println(“Password is too long!”);
//This should be refactored to:
public class Foo {
public static final int MAX_PASSWORD_SIZE = 7;
public void setPassword(String password) {
if (password.length() > MAX_PASSWORD_SIZE) {
System.out.println(“Password is too long!”);
Example Line Wrapping Style
//Example 1: calling a method
someMethod(longExpression1, longExpression2, longExpression3,
longExpression4, longExpression5);
//Example 2: math expression
longName1 = longName2 * (longName3 + longName4 – longName5)
+ 4 * longname6;
//Example 3: method header
int someMethod(int anArg, Object anotherArg, String yetAnotherArg,
Object andStillAnother) {

//Example 4: method header with a lot of arguments
private static synchronized horkingLongMethodName(int anArg,
Object anotherArg, String yetAnotherArg,
Object andStillAnother) {

//Example 5: conditional statements
if ((condition1 && condition2)
|| (condition3 && condition4)
||!(condition5 && condition6)) {
if ((condition1 && condition2) || (condition3 && condition4)
||!(condition5 && condition6)) {
If you’re curious, more coding style guides can be found on the Oracle website.
Programming Assignment 9
[Multi-threaded Encryption]
Due: 11:59 pm, Friday, March 8th, 2019
In this assignment, we will be getting hands-on experience on multi-threading in Java. We will
be looking into how to utilize the synchronized keyword along with extending the Thread class.
Before we start:
1. This write-up is the main documentation of this assignment. However, ​you are still
responsible for being aware of possible further hints/clarifications made in the lecture,
discussion slides, and related pinned/emailed Piazza posts;
2. If not specifically declared in the writeup, you cannot make any assumptions about the
inputs of the method you are implementing;
3. If certain methods return ​String or ​char​, it is important that your program returns a
String​/​char​ formatted/shown exactly as it is in the examples;
4. You are responsible for testing your code on your ieng6 account (which has the same
java version setup as our autograder) before submission. Failure to compile will result in
0 points being awarded for the corresponding sections.
Start by logging onto your ieng6 account. Then create and enter your source directory:
$​ mkdir ~/PA9
$​ ​cd​ ~/PA9
Download your ​starter files​ and copy them to your source directory on ieng6.
How to test your code:
To test your code, you will want to compile the file you are working on and then run it. Doing this
is simple but important for you to understand.
$​ c
​ d​ ~/PA9
$ j
​ avac ​.java
You have just used the java compiler to compile your code into a class file that the Java Virtual
Machine (the computer) can understand. You should now see ​.class in your
directory. Now you need to run it.
$​ ​java​
This executes your file by entering the ​main method in the file. You can change the inputs to
your algorithm by changing the code in the ​main method. Note that you don’t specify any file
extensions (neither .class nor .java) when using the ​java​ command.
PS – We will be using the autograder on gradescope to test your submission against a standard
set of tests written by the course instructors. Keep that in mind while submitting your code. You
do not have as much freedom with code structure as you did with PA8.
Multi-threading, A simple example
Multi-threading is an important Java feature that allows for concurrent ​execution of two or
more parts of a program for maximum utilization of CPU​. ​Each part of such a program is
called a thread.
For a more detailed explanation on threads check out ​this link​.
Now let’s take a look at how we can create threads. There are two ways in which you
can achieve this 1. Extending the ​Thread​ class
2. Implementing the ​Runnable​ interface
One extends a class, allowing for single inheritance. The other implements an interface
which allows it to extend from another base class, thereby supporting multiple
For the purpose of this assignment, you can use any of the above-mentioned ways of
creating new threads. A simple example is given below, courtesy of ​Oracle​ ->
public​ ​class​ HelloRunnable ​implements​ Runnable { ​//implementing Runnable
​//need to override the run method
​public​ ​void​ ​run​() {
System.out.println(​”Hello from a thread!”​);
​public​ ​static​ ​void​ ​main​(String args[]) {
​// call Thread.start() to start a new thread
(​new​ Thread(​new​ HelloRunnable())).start();
Instead of creating a new XYZRunnable class for creating threads, you can use the
shorthand mentioned below //….inside any function/method, taking main as example
public​ ​static​ ​void​ ​main​(String args[]) {
Thread t1 = ​new​ Thread(​new​ Runnable() {
​public​ ​void​ ​run​() {
System.out.println(​”Hello from a thread!”​);
​//…do some data manipulation
​//starts the thread calls the run method of that thread
t1.start(); ​//NOTE – t1.start() and not
Avoid the common pitfall of calling run() instead of start()
This code does the exact same thing as the first snippet. It saves us some time by not
having to create a new XYZRunnable class implementing Runnable, rather we create
an anonymous class that implements the R
​ unnable​ interface which is inside an
anonymous subclass of T
​ hread​.
A detailed explanation for various ways of creating threads can be found ​here​.
For the purpose of this assignment, you need to know of these three Thread methods :
1. start() – ​causes a thread to begin execution, the Java Virtual Machine calls the run
method of this thread. The result is that two threads are running concurrently: the current
thread (which returns from the call to the start method) and the other thread (which
executes its run method).
2. join()​ – ​This java thread join method puts the current thread on wait until the thread on
which it’s called is dead.
3. sleep() – ​method can be used to pause the execution of the current thread for a
specified time in milliseconds
Now that we have covered the basics of threads. Let’s take a simple example that illustrates
why synchronization (thread locks) is an important paradigm in Java programming.
You are planning to go to a movie at 5 pm. You inquire about the availability of the tickets at
4 pm. The representative says that they are available. You relax and reach the ticket
window 5 minutes before the show. I’m sure you can guess what happens: it’s a full house 🙁
The problem here was in the duration between the check and the action. You inquired at 4
and acted at 5. In the meantime, someone else grabbed the tickets. Such a scenario is
called a race condition – specifically a “​check-then-act​” scenario of race conditions.
Think of yourself as a thread, let us call you Thread1. The other person who got the tickets
is another thread, called Thread2. The movie theater is the CPU. Now you may think that
Thread2 is a bad person because he/she stole your “rightful” tickets. But that’s not really the
case here. The mistake you made was that you never really claimed that those tickets are
yours and you would like the movie theater to hold them for you. And that’s what
synchronization is all about. If only you had synchronized your ticket buying plan, you
would have been sitting in the movie theater watching ​How to Train Your Dragon: The
Hidden World ​munching on expensive popcorn, not crying about it in front of the ticket
The lesson we learn from the above fictional story is that whenever you are trying to access a
shared memory location that you plan to read and modify, it is imperative that you synchronize
your read/write operation with respect to other threads in the system. You claim that you’re
going to access this specific memory location and till you are done, no other thread should
access this location.
For example if​ (x == ​5​) ​// The “Check”
y = x * ​2​; ​// The “Act”
​// If another thread changed x in between “if (x == 5)” and “y = x * 2″ above,
​// y will not be equal to 10.
The point being, y could be 10, or it could be anything, depending on whether another
thread changed x in between the check and act. You have no real way of knowing.
If you are confused as to why we didn’t really need to worry about multi-threading before in
any of the first 8 programming assignments, it is because all those programs were single
threaded. The main thread didn’t have any competing threads that it needed to care about.
How do we solve this problem? High-Level pseudocode is given below
// Figure out a way to obtain lock for x
if​ (x == ​5​) {
y = x * ​2​; ​// Now, nothing can change x until the lock is released.
​// Therefore y = 10
} ​// release lock for x
Now let’s formalize how we will use this concept specifically for JAVA The Java synchronized Keyword synchronized​(​this​){ //obtain a lock on the current instance of the object
if​ (x == ​5​) {
y = x * ​2​; ​// Now, nothing can change x until the lock is released.
​// Therefore y = 10
More information about the synchronized keyword can be found ​here
PS – You can also use Lock to take a lock on objects but for the purpose of this assignment we
will stick with the synchronized keyword. If you’re inquisitive, you can check ​this​ link. Don’t worry
if you don’t understand this in detail.
Starter code explanation Now that we know what synchronization is, let’s dive into the given starter code:
What you’re supposed to do in this program is to write the code for a UserDetail encrypter and
decrypter that works with multi-threaded systems.
Code Files: Details explained below.
You’ll use the following logic for encryption and decryption in your encrypt
and decrypt methods for and
For encryption, we replace each character of the string with a character that has
an ASCII value 5 greater than the current character. For decryption, we subtract 5
from the ASCII value of each character in the string to get a new character.
This class stores the password as an array of characters (just like the username inside
UserDetails class)
1. As usual the constructor for the class, public Password(String password)
2. String showPassword(), the method that returns the password as a string. This is the
function you would call from the UserDetails class inside the showPassword() method
and the getUserDetails()
3. void encrypt(), the method that encrypts the password. This method should be thread
safe, as multiple threads can try to encrypt the password at once. You should use a
sleep of 5 milliseconds in this method. (This simulates the time taken for encryption.)
4. Void decrypt(), the method that decrypts the password. This method should be thread
safe, as multiple threads can try to decrypt the password at once. You should use a
sleep of 10 milliseconds in this method. (This simulates the time taken for decryption.)
This is the file where you’ll store the user details. The three instance variables that you’ll need
for this class are
private​ c
​ har​ username[]; ​//array of characters for storing username
private​ Password password; ​//An Object of the Password class
boolean​ encrypted;
The following methods need to be implemented for the UserDetails class 1. The constructor of the class (notice how you input String but store a character array)
This should set up the instance variable within the class
UserDetails(String username, String password)
2. String showUserName()
When this function is called return the userName as a string
3. String showPassword() – Return the Password as a string when this function is called
4. String getUserDetails() – return the user name followed by the password (complete
details). Use “|” as a separator for username and password – ​”Rajat|mypassword”
5. void encrypt() – This function should encrypt the username as well as the password. This
is the entire crux of the assignment. To make the process multi-threaded, we will create
two threads here, let’s call them threadUser, threadPass. Inside their run() function you’ll
perform the task of encrypting the values entered in username array and the password
object respectively(might want to call the encrypt method inside the password class, see
below). You should execute these threads simultaneously for encryption. This function
sets the value of ‘encrypted’ to true, if the data is not encrypted and encrypts it.
Otherwise if the data is already encrypted, this function returns.
Also, do keep in mind that this entire process needs to happen in a synchronized way,
since you do not want any other thread messing around with you instance variable while
you are encrypting them (if any other thread starts changing the name while you are
encrypting it then it might lead to the wrong name being encrypted). You should use a
sleep of 6 milliseconds in threadUser which encrypts the username. (This simulates the
time taken for encryption.)
Once you are done with encrypting the name and the password. Make sure you kill the
threads before exiting out of this function. (HINT – Can you use the join method here
6. Void decrypt() – This method will have the exact same structure as encrypt. The only
difference is going to be the operation being performed on the data. This will decrypt the
data but everything else remains the same – Two threads, one for decrypting username,
another for the password. Killing them before you exit. You should use a sleep of 11
milliseconds in thread which decrypts the username. (This simulates the time taken for
decryption.) You should execute these threads simultaneously for encryption. This
function sets the value of ‘encrypted’ to false, if the data is not decrypted and decrypts it.
Otherwise if the data is already decrypted, this function returns.
IMPORTANT – Think of all possible scenarios that can happen while you’re trying to perform
some operation on the UserDetails class. Can they change when you are encrypting them? Can
they change when you are decrypting them? The answers to the above questions will guide you
where you need to use the synchronized blocks.
UtilClasses ​-
Then we have 4 different utility classes Two for the entire UserDetails class – UserEncrypterUtil, UserDecrypterUtil
Two for the Password class – EncrypterUtil and DecrypterUtil
All these four utility classes extend from the Thread Class (has been given to you in the starter
You can use these Utilities inside your main method to check how things are behaving when
there are multiple threads in the system. A sample implementation has been provided to you in
the file which is part of your starter code.
Let’s take a look at what you’re supposed to implement for these utility classes
1. Constructor – Take a look at the starter code and implement the constructor accordingly.
2. Overriding run() For UserEncrypterUtil and EncrypterUtil, you need to run a “for” loop 10 times and inside
the for loop, you need to call the concerned object’s encrypt method.
For UserDecrypterUtil and DecrypterUtil, you need to run a “for” loop 10 times and call
the concerned object’s decrypt method.
CipherShifter is a class that extends the Thread class. Cipher shifter is an additional layer of
encryption. It would be ideally called after an encrypt operation, so the encryption is even
Calling CipherShifter odd no. of times further encrypts the text and calling it an even
number of times decrypt whatever text was passed to it originally.
In the CipherShifter …
Purchase answer to see full

Order your essay today and save 10% with the discount code ESSAYHSELP