Compare commits

...

6 Commits

77 changed files with 403 additions and 83 deletions

5
.gitignore vendored
View File

@ -2,7 +2,7 @@
out/
!**/src/main/**/out/
!**/src/test/**/out/
target/
### Eclipse ###
.apt_generated
.classpath
@ -27,4 +27,5 @@ bin/
### Mac OS ###
.DS_Store
/.idea/
.idea/
*.iml

3
.idea/.gitignore generated vendored
View File

@ -1,3 +0,0 @@
# Default ignored files
/shelf/
/workspace.xml

14
.idea/compiler.xml generated
View File

@ -1,14 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CompilerConfiguration">
<annotationProcessing>
<profile name="Maven default annotation processors profile" enabled="true">
<sourceOutputDir name="target/generated-sources/annotations" />
<sourceTestOutputDir name="target/generated-test-sources/test-annotations" />
<outputRelativeToContentRoot value="true" />
<module name="java_test" />
</profile>
</annotationProcessing>
<bytecodeTargetLevel target="21" />
</component>
</project>

View File

@ -1,8 +0,0 @@
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="AutoCloseableResource" enabled="true" level="WARNING" enabled_by_default="true">
<option name="METHOD_MATCHER_CONFIG" value="java.util.Formatter,format,java.io.Writer,append,com.google.common.base.Preconditions,checkNotNull,org.hibernate.Session,close,java.io.PrintWriter,printf,java.io.PrintStream,printf,java.lang.foreign.Arena,ofAuto,java.lang.foreign.Arena,global,java.util.concurrent.Executors,newFixedThreadPool" />
</inspection_tool>
</profile>
</component>

View File

@ -1,20 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="RemoteRepositoriesConfiguration">
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Maven Central repository" />
<option name="url" value="https://repo1.maven.org/maven2" />
</remote-repository>
<remote-repository>
<option name="id" value="jboss.community" />
<option name="name" value="JBoss Community repository" />
<option name="url" value="https://repository.jboss.org/nexus/content/repositories/public/" />
</remote-repository>
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Central Repository" />
<option name="url" value="https://maven.aliyun.com/repository/central" />
</remote-repository>
</component>
</project>

14
.idea/misc.xml generated
View File

@ -1,14 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="MavenProjectsManager">
<option name="originalFiles">
<list>
<option value="$PROJECT_DIR$/pom.xml" />
</list>
</option>
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_21" default="true" project-jdk-name="21" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>

8
.idea/modules.xml generated
View File

@ -1,8 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/java_test.iml" filepath="$PROJECT_DIR$/java_test.iml" />
</modules>
</component>
</project>

6
.idea/vcs.xml generated
View File

@ -1,6 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>

BIN
java_pid16957.hprof Normal file

Binary file not shown.

View File

@ -1,8 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="AdditionalModuleElements">
<content url="file://$MODULE_DIR$" dumb="true">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
</content>
</component>
</module>

View File

@ -0,0 +1,68 @@
package jvm;
import java.lang.System; // Import System for nanoTime and printf
/**
* A Java class to replicate the calculation performed by the Python script.
*/
public class Calculation {
/**
* Performs the iterative calculation.
*
* @param iterations The number of iterations for the loop.
* @param param1 The first parameter used in the calculation.
* @param param2 The second parameter used in the calculation.
* @return The result of the calculation.
*/
public static double calculate(int iterations, int param1, int param2) {
// Initialize the result as a double
double result = 1.0;
// Loop from 1 to iterations (inclusive)
for (int i = 1; i <= iterations; i++) {
// Calculate the first value of j
// Use double for j to ensure floating-point arithmetic
double jMinus = (double)i * param1 - param2;
// Subtract 1.0 / jMinus from the result (use 1.0 for double division)
result -= (1.0 / jMinus);
// Calculate the second value of j
double jPlus = (double)i * param1 + param2;
// Add 1.0 / jPlus to the result
result += (1.0 / jPlus);
}
// Return the final calculated result
return result;
}
/**
* The main entry point of the program.
*
* @param args Command line arguments (not used).
*/
public static void main(String[] args) {
// Define the parameters for the calculation
final int ITERATIONS = 100_000_000; // Use underscore for readability (Java 7+)
final int PARAM1 = 4;
final int PARAM2 = 1;
// Record the start time using System.nanoTime() for higher precision
long startTime = System.nanoTime();
// Perform the calculation and multiply the result by 4.0
double finalResult = calculate(ITERATIONS, PARAM1, PARAM2) * 4.0;
// Record the end time
long endTime = System.nanoTime();
// Calculate the duration in nanoseconds
long durationNanos = endTime - startTime;
// Convert the duration to seconds (as a double)
double durationSeconds = durationNanos / 1_000_000_000.0;
// Print the final result, formatted to 12 decimal places
System.out.printf("Result: %.12f%n", finalResult);
// Print the execution time, formatted to 6 decimal places
System.out.printf("Execution Time: %.6f seconds%n", durationSeconds);
}
}

View File

@ -0,0 +1,166 @@
package jvm;
import java.lang.System; // Import System for nanoTime and printf
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
/**
* A Java class to replicate the calculation performed by the Python script,
* optimized using multithreading.
*/
public class Calculation2 {
/**
* Represents a task that calculates a partial sum for a given range of iterations.
* Implements Callable so it can be executed by an ExecutorService and return a result.
*/
private static class PartialCalculator implements Callable<Double> {
private final int startIteration;
private final int endIteration;
private final int param1;
private final int param2;
/**
* Constructor for the partial calculator task.
* @param startIteration The starting iteration (inclusive).
* @param endIteration The ending iteration (exclusive).
* @param param1 The first parameter for calculation.
* @param param2 The second parameter for calculation.
*/
public PartialCalculator(int startIteration, int endIteration, int param1, int param2) {
this.startIteration = startIteration;
this.endIteration = endIteration;
this.param1 = param1;
this.param2 = param2;
}
/**
* The computation performed by this task. Calculates the sum for the assigned range.
* @return The partial sum for the range.
*/
@Override
public Double call() {
double partialSum = 0.0;
// Loop through the assigned range of iterations
// Note: loop goes up to < endIteration
for (int i = startIteration; i < endIteration; i++) {
// Calculate the first value of j
double jMinus = (double)i * param1 - param2;
// Subtract 1.0 / jMinus from the partial sum
partialSum -= (1.0 / jMinus);
// Calculate the second value of j
double jPlus = (double)i * param1 + param2;
// Add 1.0 / jPlus to the partial sum
partialSum += (1.0 / jPlus);
}
return partialSum;
}
}
/**
* Performs the iterative calculation using multiple threads.
*
* @param iterations The total number of iterations for the loop.
* @param param1 The first parameter used in the calculation.
* @param param2 The second parameter used in the calculation.
* @param numThreads The number of threads to use for the calculation.
* @return The result of the calculation.
* @throws InterruptedException If thread execution is interrupted.
* @throws ExecutionException If computation threw an exception.
*/
public static double calculateParallel(int iterations, int param1, int param2, int numThreads)
throws InterruptedException, ExecutionException {
// Create a fixed-size thread pool
ExecutorService executor = Executors.newFixedThreadPool(numThreads);
// List to hold the Future objects representing the results of each task
List<Future<Double>> futureResults = new ArrayList<>();
// Calculate the approximate number of iterations per thread
int iterationsPerThread = iterations / numThreads;
int start = 1; // Start iteration from 1
// Divide the work and submit tasks to the executor
for (int i = 0; i < numThreads; i++) {
int end = start + iterationsPerThread;
// For the last thread, ensure it covers all remaining iterations
if (i == numThreads - 1) {
end = iterations + 1; // Go up to iterations (inclusive)
}
// Ensure end doesn't exceed the total iterations + 1 boundary
if (end > iterations + 1) {
end = iterations + 1;
}
// Create and submit the task for the calculated range
// The loop inside PartialCalculator runs from start (inclusive) to end (exclusive)
Callable<Double> task = new PartialCalculator(start, end, param1, param2);
futureResults.add(executor.submit(task));
// Set the start for the next chunk
start = end;
}
// Initialize the total result (starting from the base 1.0)
double totalResult = 1.0;
// Retrieve results from each Future and add to the total result
for (Future<Double> future : futureResults) {
// future.get() blocks until the result is available
totalResult += future.get();
}
// Shut down the executor service gracefully
executor.shutdown();
// Return the final combined result
return totalResult;
}
/**
* The main entry point of the program.
*
* @param args Command line arguments (not used).
*/
public static void main(String[] args) {
// Define the parameters for the calculation
final int ITERATIONS = 100_000_000;
final int PARAM1 = 4;
final int PARAM2 = 1;
// Determine the number of threads based on available processors
final int NUM_THREADS = Runtime.getRuntime().availableProcessors();
System.out.println("Using " + NUM_THREADS + " threads.");
// Record the start time
long startTime = System.nanoTime();
double finalResult = 0;
try {
// Perform the parallel calculation and multiply the result by 4.0
finalResult = calculateParallel(ITERATIONS, PARAM1, PARAM2, NUM_THREADS) * 4.0;
// Record the end time
long endTime = System.nanoTime();
// Calculate the duration
long durationNanos = endTime - startTime;
double durationSeconds = durationNanos / 1_000_000_000.0;
// Print the final result and execution time
System.out.printf("Result: %.12f%n", finalResult);
System.out.printf("Execution Time: %.6f seconds%n", durationSeconds);
} catch (InterruptedException | ExecutionException e) {
// Handle potential exceptions during parallel execution
System.err.println("Calculation failed: " + e.getMessage());
e.printStackTrace();
// Ensure System.exit is not used in production code without careful consideration
// System.exit(1);
}
}
}

View File

@ -0,0 +1,36 @@
package jvm;
/**
* it converts from python code
* just check performance differences between python and java
*/
public class SpeedTest {
public double calculate(int iter, int param1, int param2) {
double result = 1.0;
for (int i = 1; i <= iter; i++) {
double jMinus = (double)i * param1 - param2;
// Subtract 1.0 / jMinus from the result (use 1.0 for double division)
result -= (1.0 / jMinus);
// Calculate the second value of j
double jPlus = (double)i * param1 + param2;
// Add 1.0 / jPlus to the result
result += (1.0 / jPlus);
}
return result;
}
public static void main(String[] args) {
SpeedTest speedTest = new SpeedTest();
long start = System.nanoTime();
double result = speedTest.calculate(100_000_000, 4, 1) * 4.0;
System.out.println(result);
long end = System.nanoTime();
long durationNanos = end - start;
double durationSeconds = durationNanos / 1_000_000_000.0;
System.out.println( durationSeconds );
}
}

View File

@ -0,0 +1,27 @@
package main.java.jvm;
/**
* in test method, x will assign to return value, here should be 1 (it will not throw any errors)
* then, the finally block will change x to 3, but the return value will not change
* How finally work is attach the code block in it to try block and catch block
*/
public class TryCatchDemo {
public int test() {
int x=0;
try {
x=1;
return x;
} catch (Exception e) {
x=2;
return x;
} finally {
x=3;
}
}
public static void main(String[] args) {
TryCatchDemo tryCatchDemo = new TryCatchDemo();
System.out.println(tryCatchDemo.test());
}
}

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,3 @@
artifactId=java-learning
groupId=com.kuaslab
version=1.0-SNAPSHOT

View File

@ -0,0 +1,54 @@
jvm/createthread/CreateByExecutorService.class
threaddemo/WeakReferenceExample.class
feature/ReduceTest.class
jvm/createthread/CreateByThreadGroup.class
jvm/ConstantPoolDemo.class
jvm/debugtool/JHSDBTestCase$Test.class
threaddemo/DeadLockFixDemo.class
threaddemo/lock/CLH.class
threaddemo/MultiThreadDemo.class
jvm/debugtool/DeadLockDemo$SyncAddRunnable.class
threaddemo/ProcessDemo.class
threaddemo/VolatileAtomicDemo.class
jvm/createthread/CreateByTimer$1.class
jvm/createthread/CreateByAnonymousClass.class
threaddemo/ThreadStateWithWait.class
jvm/gc/PrintMemoryAddress.class
jvm/classfile/TestClass.class
jvm/createthread/CreateByForkJoin.class
jvm/ShowObjectHeader.class
threaddemo/ThreadStateWithJoin.class
threaddemo/SafeVolatileDemo.class
threaddemo/ThreadShareVariable.class
threaddemo/ThreadStateWithSync.class
jvm/oom/HeapOOM.class
threaddemo/ThreadStateWithLockSupport.class
jvm/oom/JavaVMStackSOF.class
threaddemo/DeadlockDemo.class
jvm/oom/HeapOOM$OOMObject.class
threaddemo/InterruptTest.class
io/ReadAndUpload$1.class
main/java/recursive/TreeStructure.class
jvm/gc/MemoryAllocationYoung.class
jvm/createthread/CreateByTimer.class
jvm/createthread/CreateByThread.class
io/FileChunkInitReq.class
threaddemo/lock/CLHDemo.class
main/java/recursive/TreeNode.class
jvm/gc/TenuringThreshold.class
threaddemo/dataracing/CASByAtomicInteger.class
jvm/gc/ReferenceCountingGC.class
jvm/createthread/CreateByRunnable.class
jvm/createthread/CreateByCompletableFuture.class
io/ReadAndUpload.class
jvm/debugtool/JHSDBTestCase.class
jvm/debugtool/DeadLockDemo.class
threaddemo/lock/CLH$Node.class
jvm/debugtool/JHSDBTestCase$ObjectHolder.class
jvm/VarHandleDemo.class
main/java/jvm/ObjectCreate.class
jvm/createthread/CreateByFutureTask.class
threaddemo/ThreadLocalDemo.class
jvm/createthread/CreateByAnonymousClass$1.class
threaddemo/dataracing/SyncDemo.class
jvm/createthread/CreateByCallable.class

View File

@ -0,0 +1,46 @@
/home/admin/projects/java_test/src/main/java/jvm/createthread/CreateByTimer.java
/home/admin/projects/java_test/src/main/java/jvm/ConstantPoolDemo.java
/home/admin/projects/java_test/src/main/java/threaddemo/WeakReferenceExample.java
/home/admin/projects/java_test/src/main/java/jvm/createthread/CreateByAnonymousClass.java
/home/admin/projects/java_test/src/main/java/recursive/TreeNode.java
/home/admin/projects/java_test/src/main/java/jvm/ObjectCreate.java
/home/admin/projects/java_test/src/main/java/threaddemo/ThreadShareVariable.java
/home/admin/projects/java_test/src/main/java/threaddemo/dataracing/SyncDemo.java
/home/admin/projects/java_test/src/main/java/threaddemo/ThreadStateWithWait.java
/home/admin/projects/java_test/src/main/java/jvm/gc/TenuringThreshold.java
/home/admin/projects/java_test/src/main/java/threaddemo/SafeVolatileDemo.java
/home/admin/projects/java_test/src/main/java/jvm/createthread/CreateByForkJoin.java
/home/admin/projects/java_test/src/main/java/jvm/gc/PrintMemoryAddress.java
/home/admin/projects/java_test/src/main/java/threaddemo/InterruptTest.java
/home/admin/projects/java_test/src/main/java/threaddemo/lock/CLH.java
/home/admin/projects/java_test/src/main/java/threaddemo/DeadLockFixDemo.java
/home/admin/projects/java_test/src/main/java/threaddemo/MultiThreadDemo.java
/home/admin/projects/java_test/src/main/java/jvm/createthread/CreateByCompletableFuture.java
/home/admin/projects/java_test/src/main/java/jvm/createthread/CreateByRunnable.java
/home/admin/projects/java_test/src/main/java/jvm/debugtool/JHSDBTestCase.java
/home/admin/projects/java_test/src/main/java/jvm/debugtool/DeadLockDemo.java
/home/admin/projects/java_test/src/main/java/io/ReadAndUpload.java
/home/admin/projects/java_test/src/main/java/threaddemo/ProcessDemo.java
/home/admin/projects/java_test/src/main/java/threaddemo/dataracing/CASByAtomicInteger.java
/home/admin/projects/java_test/src/main/java/threaddemo/ThreadStateWithSync.java
/home/admin/projects/java_test/src/main/java/jvm/createthread/CreateByExecutorService.java
/home/admin/projects/java_test/src/main/java/threaddemo/ThreadLocalDemo.java
/home/admin/projects/java_test/src/main/java/feature/ReduceTest.java
/home/admin/projects/java_test/src/main/java/io/FileChunkInitReq.java
/home/admin/projects/java_test/src/main/java/threaddemo/VolatileAtomicDemo.java
/home/admin/projects/java_test/src/main/java/jvm/createthread/CreateByFutureTask.java
/home/admin/projects/java_test/src/main/java/threaddemo/ThreadStateWithLockSupport.java
/home/admin/projects/java_test/src/main/java/threaddemo/lock/CLHDemo.java
/home/admin/projects/java_test/src/main/java/jvm/oom/HeapOOM.java
/home/admin/projects/java_test/src/main/java/jvm/createthread/CreateByThreadGroup.java
/home/admin/projects/java_test/src/main/java/threaddemo/ThreadStateWithJoin.java
/home/admin/projects/java_test/src/main/java/jvm/gc/ReferenceCountingGC.java
/home/admin/projects/java_test/src/main/java/recursive/TreeStructure.java
/home/admin/projects/java_test/src/main/java/jvm/VarHandleDemo.java
/home/admin/projects/java_test/src/main/java/jvm/createthread/CreateByThread.java
/home/admin/projects/java_test/src/main/java/jvm/oom/JavaVMStackSOF.java
/home/admin/projects/java_test/src/main/java/jvm/createthread/CreateByCallable.java
/home/admin/projects/java_test/src/main/java/jvm/gc/MemoryAllocationYoung.java
/home/admin/projects/java_test/src/main/java/threaddemo/DeadlockDemo.java
/home/admin/projects/java_test/src/main/java/jvm/classfile/TestClass.java
/home/admin/projects/java_test/src/main/java/jvm/ShowObjectHeader.java